1997-08-31 13:40:13 +02:00
|
|
|
/*-------------------------------------------------------------------------
|
|
|
|
*
|
1999-02-14 00:22:53 +01:00
|
|
|
* trigger.c
|
1997-09-07 07:04:48 +02:00
|
|
|
* PostgreSQL TRIGGERs support code.
|
1997-08-31 13:40:13 +02:00
|
|
|
*
|
2017-01-03 19:48:53 +01:00
|
|
|
* Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
|
2000-01-31 05:35:57 +01:00
|
|
|
* Portions Copyright (c) 1994, Regents of the University of California
|
|
|
|
*
|
|
|
|
* IDENTIFICATION
|
2010-09-20 22:08:53 +02:00
|
|
|
* src/backend/commands/trigger.c
|
2000-01-31 05:35:57 +01:00
|
|
|
*
|
1997-08-31 13:40:13 +02:00
|
|
|
*-------------------------------------------------------------------------
|
|
|
|
*/
|
|
|
|
#include "postgres.h"
|
|
|
|
|
1998-04-27 06:08:07 +02:00
|
|
|
#include "access/genam.h"
|
|
|
|
#include "access/heapam.h"
|
2008-05-12 02:00:54 +02:00
|
|
|
#include "access/sysattr.h"
|
2012-08-30 22:15:44 +02:00
|
|
|
#include "access/htup_details.h"
|
2003-03-31 22:47:51 +02:00
|
|
|
#include "access/xact.h"
|
1997-09-04 15:19:01 +02:00
|
|
|
#include "catalog/catalog.h"
|
2002-07-12 20:43:19 +02:00
|
|
|
#include "catalog/dependency.h"
|
1997-09-01 09:59:06 +02:00
|
|
|
#include "catalog/indexing.h"
|
2010-11-25 17:48:49 +01:00
|
|
|
#include "catalog/objectaccess.h"
|
2007-02-14 02:58:58 +01:00
|
|
|
#include "catalog/pg_constraint.h"
|
2016-02-11 21:51:28 +01:00
|
|
|
#include "catalog/pg_constraint_fn.h"
|
1998-04-27 06:08:07 +02:00
|
|
|
#include "catalog/pg_proc.h"
|
1997-08-31 13:40:13 +02:00
|
|
|
#include "catalog/pg_trigger.h"
|
2002-08-22 02:01:51 +02:00
|
|
|
#include "catalog/pg_type.h"
|
2006-04-27 02:33:46 +02:00
|
|
|
#include "commands/dbcommands.h"
|
2002-09-21 20:39:26 +02:00
|
|
|
#include "commands/defrem.h"
|
1998-04-27 06:08:07 +02:00
|
|
|
#include "commands/trigger.h"
|
1999-01-29 10:23:17 +01:00
|
|
|
#include "executor/executor.h"
|
1997-09-04 15:19:01 +02:00
|
|
|
#include "miscadmin.h"
|
2009-10-15 00:14:25 +02:00
|
|
|
#include "nodes/bitmapset.h"
|
2002-10-03 23:06:23 +02:00
|
|
|
#include "nodes/makefuncs.h"
|
2009-11-20 21:38:12 +01:00
|
|
|
#include "optimizer/clauses.h"
|
|
|
|
#include "optimizer/var.h"
|
|
|
|
#include "parser/parse_clause.h"
|
2011-04-07 08:34:57 +02:00
|
|
|
#include "parser/parse_collate.h"
|
2002-04-09 22:35:55 +02:00
|
|
|
#include "parser/parse_func.h"
|
2009-10-15 00:14:25 +02:00
|
|
|
#include "parser/parse_relation.h"
|
|
|
|
#include "parser/parsetree.h"
|
2008-05-15 02:17:41 +02:00
|
|
|
#include "pgstat.h"
|
2009-11-20 21:38:12 +01:00
|
|
|
#include "rewrite/rewriteManip.h"
|
2008-05-12 02:00:54 +02:00
|
|
|
#include "storage/bufmgr.h"
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
#include "storage/lmgr.h"
|
2007-11-04 02:16:19 +01:00
|
|
|
#include "tcop/utility.h"
|
1997-09-04 15:19:01 +02:00
|
|
|
#include "utils/acl.h"
|
1999-07-16 07:00:38 +02:00
|
|
|
#include "utils/builtins.h"
|
2009-08-04 18:08:37 +02:00
|
|
|
#include "utils/bytea.h"
|
2000-05-28 19:56:29 +02:00
|
|
|
#include "utils/fmgroids.h"
|
1999-07-16 07:00:38 +02:00
|
|
|
#include "utils/inval.h"
|
2002-03-29 23:10:34 +01:00
|
|
|
#include "utils/lsyscache.h"
|
2005-05-06 19:24:55 +02:00
|
|
|
#include "utils/memutils.h"
|
2011-02-23 18:18:09 +01:00
|
|
|
#include "utils/rel.h"
|
2008-03-26 19:48:59 +01:00
|
|
|
#include "utils/snapmgr.h"
|
1999-07-16 07:00:38 +02:00
|
|
|
#include "utils/syscache.h"
|
2008-03-26 22:10:39 +01:00
|
|
|
#include "utils/tqual.h"
|
2014-03-23 07:16:34 +01:00
|
|
|
#include "utils/tuplestore.h"
|
1997-09-04 15:19:01 +02:00
|
|
|
|
1997-09-01 09:59:06 +02:00
|
|
|
|
2007-11-04 02:16:19 +01:00
|
|
|
/* GUC variables */
|
2007-11-16 00:23:44 +01:00
|
|
|
int SessionReplicationRole = SESSION_REPLICATION_ROLE_ORIGIN;
|
2007-11-04 02:16:19 +01:00
|
|
|
|
2012-01-25 17:15:29 +01:00
|
|
|
/* How many levels deep into trigger execution are we? */
|
|
|
|
static int MyTriggerDepth = 0;
|
2007-11-04 02:16:19 +01:00
|
|
|
|
Fix column-privilege leak in error-message paths
While building error messages to return to the user,
BuildIndexValueDescription, ExecBuildSlotValueDescription and
ri_ReportViolation would happily include the entire key or entire row in
the result returned to the user, even if the user didn't have access to
view all of the columns being included.
Instead, include only those columns which the user is providing or which
the user has select rights on. If the user does not have any rights
to view the table or any of the columns involved then no detail is
provided and a NULL value is returned from BuildIndexValueDescription
and ExecBuildSlotValueDescription. Note that, for key cases, the user
must have access to all of the columns for the key to be shown; a
partial key will not be returned.
Further, in master only, do not return any data for cases where row
security is enabled on the relation and row security should be applied
for the user. This required a bit of refactoring and moving of things
around related to RLS- note the addition of utils/misc/rls.c.
Back-patch all the way, as column-level privileges are now in all
supported versions.
This has been assigned CVE-2014-8161, but since the issue and the patch
have already been publicized on pgsql-hackers, there's no point in trying
to hide this commit.
2015-01-12 23:04:11 +01:00
|
|
|
/*
|
2015-05-08 18:00:01 +02:00
|
|
|
* Note that similar macros also exist in executor/execMain.c. There does not
|
|
|
|
* appear to be any good header to put them into, given the structures that
|
|
|
|
* they use, so we let them be duplicated. Be sure to update all if one needs
|
|
|
|
* to be changed, however.
|
Fix column-privilege leak in error-message paths
While building error messages to return to the user,
BuildIndexValueDescription, ExecBuildSlotValueDescription and
ri_ReportViolation would happily include the entire key or entire row in
the result returned to the user, even if the user didn't have access to
view all of the columns being included.
Instead, include only those columns which the user is providing or which
the user has select rights on. If the user does not have any rights
to view the table or any of the columns involved then no detail is
provided and a NULL value is returned from BuildIndexValueDescription
and ExecBuildSlotValueDescription. Note that, for key cases, the user
must have access to all of the columns for the key to be shown; a
partial key will not be returned.
Further, in master only, do not return any data for cases where row
security is enabled on the relation and row security should be applied
for the user. This required a bit of refactoring and moving of things
around related to RLS- note the addition of utils/misc/rls.c.
Back-patch all the way, as column-level privileges are now in all
supported versions.
This has been assigned CVE-2014-8161, but since the issue and the patch
have already been publicized on pgsql-hackers, there's no point in trying
to hide this commit.
2015-01-12 23:04:11 +01:00
|
|
|
*/
|
2015-05-08 00:20:46 +02:00
|
|
|
#define GetUpdatedColumns(relinfo, estate) \
|
|
|
|
(rt_fetch((relinfo)->ri_RangeTableIndex, (estate)->es_range_table)->updatedCols)
|
2009-10-15 00:14:25 +02:00
|
|
|
|
2007-11-04 02:16:19 +01:00
|
|
|
/* Local function prototypes */
|
|
|
|
static void ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid);
|
2010-10-10 19:43:33 +02:00
|
|
|
static void SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger);
|
2001-06-01 04:41:36 +02:00
|
|
|
static HeapTuple GetTupleForTrigger(EState *estate,
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
EPQState *epqstate,
|
2003-08-04 02:43:34 +02:00
|
|
|
ResultRelInfo *relinfo,
|
|
|
|
ItemPointer tid,
|
Improve concurrency of foreign key locking
This patch introduces two additional lock modes for tuples: "SELECT FOR
KEY SHARE" and "SELECT FOR NO KEY UPDATE". These don't block each
other, in contrast with already existing "SELECT FOR SHARE" and "SELECT
FOR UPDATE". UPDATE commands that do not modify the values stored in
the columns that are part of the key of the tuple now grab a SELECT FOR
NO KEY UPDATE lock on the tuple, allowing them to proceed concurrently
with tuple locks of the FOR KEY SHARE variety.
Foreign key triggers now use FOR KEY SHARE instead of FOR SHARE; this
means the concurrency improvement applies to them, which is the whole
point of this patch.
The added tuple lock semantics require some rejiggering of the multixact
module, so that the locking level that each transaction is holding can
be stored alongside its Xid. Also, multixacts now need to persist
across server restarts and crashes, because they can now represent not
only tuple locks, but also tuple updates. This means we need more
careful tracking of lifetime of pg_multixact SLRU files; since they now
persist longer, we require more infrastructure to figure out when they
can be removed. pg_upgrade also needs to be careful to copy
pg_multixact files over from the old server to the new, or at least part
of multixact.c state, depending on the versions of the old and new
servers.
Tuple time qualification rules (HeapTupleSatisfies routines) need to be
careful not to consider tuples with the "is multi" infomask bit set as
being only locked; they might need to look up MultiXact values (i.e.
possibly do pg_multixact I/O) to find out the Xid that updated a tuple,
whereas they previously were assured to only use information readily
available from the tuple header. This is considered acceptable, because
the extra I/O would involve cases that would previously cause some
commands to block waiting for concurrent transactions to finish.
Another important change is the fact that locking tuples that have
previously been updated causes the future versions to be marked as
locked, too; this is essential for correctness of foreign key checks.
This causes additional WAL-logging, also (there was previously a single
WAL record for a locked tuple; now there are as many as updated copies
of the tuple there exist.)
With all this in place, contention related to tuples being checked by
foreign key rules should be much reduced.
As a bonus, the old behavior that a subtransaction grabbing a stronger
tuple lock than the parent (sub)transaction held on a given tuple and
later aborting caused the weaker lock to be lost, has been fixed.
Many new spec files were added for isolation tester framework, to ensure
overall behavior is sane. There's probably room for several more tests.
There were several reviewers of this patch; in particular, Noah Misch
and Andres Freund spent considerable time in it. Original idea for the
patch came from Simon Riggs, after a problem report by Joel Jacobson.
Most code is from me, with contributions from Marti Raudsepp, Alexander
Shulgin, Noah Misch and Andres Freund.
This patch was discussed in several pgsql-hackers threads; the most
important start at the following message-ids:
AANLkTimo9XVcEzfiBR-ut3KVNDkjm2Vxh+t8kAmWjPuv@mail.gmail.com
1290721684-sup-3951@alvh.no-ip.org
1294953201-sup-2099@alvh.no-ip.org
1320343602-sup-2290@alvh.no-ip.org
1339690386-sup-8927@alvh.no-ip.org
4FE5FF020200002500048A3D@gw.wicourts.gov
4FEAB90A0200002500048B7D@gw.wicourts.gov
2013-01-23 16:04:59 +01:00
|
|
|
LockTupleMode lockmode,
|
2003-08-04 02:43:34 +02:00
|
|
|
TupleTableSlot **newSlot);
|
2009-11-20 21:38:12 +01:00
|
|
|
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
|
|
|
|
Trigger *trigger, TriggerEvent event,
|
|
|
|
Bitmapset *modifiedCols,
|
|
|
|
HeapTuple oldtup, HeapTuple newtup);
|
2001-06-01 04:41:36 +02:00
|
|
|
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata,
|
2005-03-25 22:58:00 +01:00
|
|
|
int tgindx,
|
2001-10-25 07:50:21 +02:00
|
|
|
FmgrInfo *finfo,
|
2005-03-25 22:58:00 +01:00
|
|
|
Instrumentation *instr,
|
2001-10-25 07:50:21 +02:00
|
|
|
MemoryContext per_tuple_context);
|
2009-11-20 21:38:12 +01:00
|
|
|
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
|
|
|
|
int event, bool row_trigger,
|
|
|
|
HeapTuple oldtup, HeapTuple newtup,
|
2009-10-15 00:14:25 +02:00
|
|
|
List *recheckIndexes, Bitmapset *modifiedCols);
|
2014-10-23 18:33:02 +02:00
|
|
|
static void AfterTriggerEnlargeQueryState(void);
|
2000-06-09 00:38:00 +02:00
|
|
|
|
1997-09-04 15:19:01 +02:00
|
|
|
|
2002-07-20 21:55:38 +02:00
|
|
|
/*
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
* Create a trigger. Returns the address of the created trigger.
|
2002-07-20 21:55:38 +02:00
|
|
|
*
|
2009-11-20 21:38:12 +01:00
|
|
|
* queryString is the source text of the CREATE TRIGGER command.
|
|
|
|
* This must be supplied if a whenClause is specified, else it can be NULL.
|
|
|
|
*
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
* 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.
|
|
|
|
*
|
2007-11-04 02:16:19 +01:00
|
|
|
* constraintOid, if nonzero, says that this trigger is being created
|
|
|
|
* internally to implement that constraint. A suitable pg_depend entry will
|
2014-05-06 18:12:18 +02:00
|
|
|
* be made to link the trigger to that constraint. constraintOid is zero when
|
2010-01-17 23:56:23 +01:00
|
|
|
* executing a user-entered CREATE TRIGGER command. (For CREATE CONSTRAINT
|
|
|
|
* TRIGGER, we build a pg_constraint entry internally.)
|
2007-11-04 02:16:19 +01:00
|
|
|
*
|
2009-07-28 04:56:31 +02:00
|
|
|
* indexOid, if nonzero, is the OID of an index associated with the constraint.
|
|
|
|
* We do nothing with this except store it into pg_trigger.tgconstrindid.
|
|
|
|
*
|
2010-01-17 23:56:23 +01:00
|
|
|
* If isInternal is true then this is an internally-generated trigger.
|
|
|
|
* This argument sets the tgisinternal field of the pg_trigger entry, and
|
|
|
|
* if TRUE causes us to modify the given trigger name to ensure uniqueness.
|
2009-07-29 22:56:21 +02:00
|
|
|
*
|
2010-01-17 23:56:23 +01:00
|
|
|
* When isInternal is not true we require ACL_TRIGGER permissions on the
|
2012-02-23 21:38:56 +01:00
|
|
|
* relation, as well as ACL_EXECUTE on the trigger function. For internal
|
|
|
|
* triggers the caller must apply any required permission checks.
|
2009-01-22 21:16:10 +01:00
|
|
|
*
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
* Note: can return InvalidObjectAddress if we decided to not create a trigger
|
|
|
|
* at all, but a foreign-key constraint. This is a kluge for backwards
|
|
|
|
* compatibility.
|
2002-07-20 21:55:38 +02:00
|
|
|
*/
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
ObjectAddress
|
2009-11-20 21:38:12 +01:00
|
|
|
CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid,
|
2010-01-17 23:56:23 +01:00
|
|
|
bool isInternal)
|
1997-08-31 13:40:13 +02:00
|
|
|
{
|
1997-09-08 04:41:22 +02:00
|
|
|
int16 tgtype;
|
2009-10-15 00:14:25 +02:00
|
|
|
int ncolumns;
|
2012-06-25 00:51:46 +02:00
|
|
|
int16 *columns;
|
2005-03-29 02:17:27 +02:00
|
|
|
int2vector *tgattr;
|
2009-11-20 21:38:12 +01:00
|
|
|
Node *whenClause;
|
|
|
|
List *whenRtable;
|
|
|
|
char *qual;
|
1997-09-08 04:41:22 +02:00
|
|
|
Datum values[Natts_pg_trigger];
|
2008-11-02 02:45:28 +01:00
|
|
|
bool nulls[Natts_pg_trigger];
|
1997-09-08 04:41:22 +02:00
|
|
|
Relation rel;
|
2002-04-27 05:45:03 +02:00
|
|
|
AclResult aclresult;
|
1997-09-08 04:41:22 +02:00
|
|
|
Relation tgrel;
|
2002-09-04 22:31:48 +02:00
|
|
|
SysScanDesc tgscan;
|
1997-09-08 04:41:22 +02:00
|
|
|
ScanKeyData key;
|
1998-09-01 05:29:17 +02:00
|
|
|
Relation pgrel;
|
1997-09-08 04:41:22 +02:00
|
|
|
HeapTuple tuple;
|
2005-03-29 02:17:27 +02:00
|
|
|
Oid fargtypes[1]; /* dummy */
|
2000-07-03 05:57:03 +02:00
|
|
|
Oid funcoid;
|
2002-09-21 20:39:26 +02:00
|
|
|
Oid funcrettype;
|
2002-07-12 20:43:19 +02:00
|
|
|
Oid trigoid;
|
2010-01-17 23:56:23 +01:00
|
|
|
char internaltrigname[NAMEDATALEN];
|
2002-07-12 20:43:19 +02:00
|
|
|
char *trigname;
|
2002-10-03 23:06:23 +02:00
|
|
|
Oid constrrelid = InvalidOid;
|
2002-09-04 22:31:48 +02:00
|
|
|
ObjectAddress myself,
|
|
|
|
referenced;
|
2016-11-04 16:49:50 +01:00
|
|
|
char *oldtablename = NULL;
|
|
|
|
char *newtablename = NULL;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
if (OidIsValid(relOid))
|
2015-04-05 17:37:08 +02:00
|
|
|
rel = heap_open(relOid, ShareRowExclusiveLock);
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
else
|
2015-04-05 17:37:08 +02:00
|
|
|
rel = heap_openrv(stmt->relation, ShareRowExclusiveLock);
|
2002-03-22 00:27:25 +01:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
/*
|
|
|
|
* Triggers must be on tables or views, and there are additional
|
|
|
|
* relation-type-specific restrictions.
|
|
|
|
*/
|
Implement table partitioning.
Table partitioning is like table inheritance and reuses much of the
existing infrastructure, but there are some important differences.
The parent is called a partitioned table and is always empty; it may
not have indexes or non-inherited constraints, since those make no
sense for a relation with no data of its own. The children are called
partitions and contain all of the actual data. Each partition has an
implicit partitioning constraint. Multiple inheritance is not
allowed, and partitioning and inheritance can't be mixed. Partitions
can't have extra columns and may not allow nulls unless the parent
does. Tuples inserted into the parent are automatically routed to the
correct partition, so tuple-routing ON INSERT triggers are not needed.
Tuple routing isn't yet supported for partitions which are foreign
tables, and it doesn't handle updates that cross partition boundaries.
Currently, tables can be range-partitioned or list-partitioned. List
partitioning is limited to a single column, but range partitioning can
involve multiple columns. A partitioning "column" can be an
expression.
Because table partitioning is less general than table inheritance, it
is hoped that it will be easier to reason about properties of
partitions, and therefore that this will serve as a better foundation
for a variety of possible optimizations, including query planner
optimizations. The tuple routing based which this patch does based on
the implicit partitioning constraints is an example of this, but it
seems likely that many other useful optimizations are also possible.
Amit Langote, reviewed and tested by Robert Haas, Ashutosh Bapat,
Amit Kapila, Rajkumar Raghuwanshi, Corey Huinker, Jaime Casanova,
Rushabh Lathia, Erik Rijkers, among others. Minor revisions by me.
2016-12-07 19:17:43 +01:00
|
|
|
if (rel->rd_rel->relkind == RELKIND_RELATION ||
|
|
|
|
rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
|
2010-10-10 19:43:33 +02:00
|
|
|
{
|
|
|
|
/* Tables can't have INSTEAD OF triggers */
|
|
|
|
if (stmt->timing != TRIGGER_TYPE_BEFORE &&
|
|
|
|
stmt->timing != TRIGGER_TYPE_AFTER)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a table",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Tables cannot have INSTEAD OF triggers.")));
|
Implement table partitioning.
Table partitioning is like table inheritance and reuses much of the
existing infrastructure, but there are some important differences.
The parent is called a partitioned table and is always empty; it may
not have indexes or non-inherited constraints, since those make no
sense for a relation with no data of its own. The children are called
partitions and contain all of the actual data. Each partition has an
implicit partitioning constraint. Multiple inheritance is not
allowed, and partitioning and inheritance can't be mixed. Partitions
can't have extra columns and may not allow nulls unless the parent
does. Tuples inserted into the parent are automatically routed to the
correct partition, so tuple-routing ON INSERT triggers are not needed.
Tuple routing isn't yet supported for partitions which are foreign
tables, and it doesn't handle updates that cross partition boundaries.
Currently, tables can be range-partitioned or list-partitioned. List
partitioning is limited to a single column, but range partitioning can
involve multiple columns. A partitioning "column" can be an
expression.
Because table partitioning is less general than table inheritance, it
is hoped that it will be easier to reason about properties of
partitions, and therefore that this will serve as a better foundation
for a variety of possible optimizations, including query planner
optimizations. The tuple routing based which this patch does based on
the implicit partitioning constraints is an example of this, but it
seems likely that many other useful optimizations are also possible.
Amit Langote, reviewed and tested by Robert Haas, Ashutosh Bapat,
Amit Kapila, Rajkumar Raghuwanshi, Corey Huinker, Jaime Casanova,
Rushabh Lathia, Erik Rijkers, among others. Minor revisions by me.
2016-12-07 19:17:43 +01:00
|
|
|
/* Disallow ROW triggers on partitioned tables */
|
|
|
|
if (stmt->row && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a partitioned table",
|
|
|
|
RelationGetRelationName(rel)),
|
2017-01-24 16:20:02 +01:00
|
|
|
errdetail("Partitioned tables cannot have ROW triggers.")));
|
2010-10-10 19:43:33 +02:00
|
|
|
}
|
|
|
|
else if (rel->rd_rel->relkind == RELKIND_VIEW)
|
|
|
|
{
|
|
|
|
/*
|
|
|
|
* Views can have INSTEAD OF triggers (which we check below are
|
|
|
|
* row-level), or statement-level BEFORE/AFTER triggers.
|
|
|
|
*/
|
|
|
|
if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a view",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Views cannot have row-level BEFORE or AFTER triggers.")));
|
|
|
|
/* Disallow TRUNCATE triggers on VIEWs */
|
|
|
|
if (TRIGGER_FOR_TRUNCATE(stmt->events))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a view",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Views cannot have TRUNCATE triggers.")));
|
|
|
|
}
|
2014-03-23 07:16:34 +01:00
|
|
|
else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
|
|
|
|
{
|
|
|
|
if (stmt->timing != TRIGGER_TYPE_BEFORE &&
|
|
|
|
stmt->timing != TRIGGER_TYPE_AFTER)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a foreign table",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Foreign tables cannot have INSTEAD OF triggers.")));
|
|
|
|
|
|
|
|
if (TRIGGER_FOR_TRUNCATE(stmt->events))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a foreign table",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Foreign tables cannot have TRUNCATE triggers.")));
|
|
|
|
|
|
|
|
if (stmt->isconstraint)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a foreign table",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Foreign tables cannot have constraint triggers.")));
|
|
|
|
}
|
2010-10-10 19:43:33 +02:00
|
|
|
else
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
2010-10-10 19:43:33 +02:00
|
|
|
errmsg("\"%s\" is not a table or view",
|
2003-07-20 23:56:35 +02:00
|
|
|
RelationGetRelationName(rel))));
|
2002-03-22 00:27:25 +01:00
|
|
|
|
2002-04-12 22:38:31 +02:00
|
|
|
if (!allowSystemTableMods && IsSystemRelation(rel))
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
2003-08-01 02:15:26 +02:00
|
|
|
errmsg("permission denied: \"%s\" is a system catalog",
|
2003-07-20 23:56:35 +02:00
|
|
|
RelationGetRelationName(rel))));
|
1997-08-31 13:40:13 +02:00
|
|
|
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
if (stmt->isconstraint)
|
2011-07-09 04:19:30 +02:00
|
|
|
{
|
|
|
|
/*
|
|
|
|
* We must take a lock on the target relation to protect against
|
|
|
|
* concurrent drop. It's not clear that AccessShareLock is strong
|
2012-06-10 21:20:04 +02:00
|
|
|
* enough, but we certainly need at least that much... otherwise, we
|
|
|
|
* might end up creating a pg_constraint entry referencing a
|
2011-07-09 04:19:30 +02:00
|
|
|
* nonexistent table.
|
|
|
|
*/
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
if (OidIsValid(refRelOid))
|
|
|
|
{
|
|
|
|
LockRelationOid(refRelOid, AccessShareLock);
|
|
|
|
constrrelid = refRelOid;
|
|
|
|
}
|
|
|
|
else if (stmt->constrrel != NULL)
|
|
|
|
constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
|
|
|
|
false);
|
2011-07-09 04:19:30 +02:00
|
|
|
}
|
2002-08-18 13:20:05 +02:00
|
|
|
|
2009-01-22 21:16:10 +01:00
|
|
|
/* permission checks */
|
2010-01-17 23:56:23 +01:00
|
|
|
if (!isInternal)
|
2002-08-18 13:20:05 +02:00
|
|
|
{
|
2002-11-23 04:59:09 +01:00
|
|
|
aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
|
2009-01-22 21:16:10 +01:00
|
|
|
ACL_TRIGGER);
|
2002-08-18 13:20:05 +02:00
|
|
|
if (aclresult != ACLCHECK_OK)
|
2003-08-01 02:15:26 +02:00
|
|
|
aclcheck_error(aclresult, ACL_KIND_CLASS,
|
|
|
|
RelationGetRelationName(rel));
|
2007-02-14 02:58:58 +01:00
|
|
|
|
2009-01-22 21:16:10 +01:00
|
|
|
if (OidIsValid(constrrelid))
|
2002-08-18 13:20:05 +02:00
|
|
|
{
|
2002-11-23 04:59:09 +01:00
|
|
|
aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
|
2009-01-22 21:16:10 +01:00
|
|
|
ACL_TRIGGER);
|
2002-08-18 13:20:05 +02:00
|
|
|
if (aclresult != ACLCHECK_OK)
|
2003-08-01 02:15:26 +02:00
|
|
|
aclcheck_error(aclresult, ACL_KIND_CLASS,
|
|
|
|
get_rel_name(constrrelid));
|
2002-08-18 13:20:05 +02:00
|
|
|
}
|
|
|
|
}
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2007-02-14 02:58:58 +01:00
|
|
|
/* Compute tgtype */
|
1997-09-07 07:04:48 +02:00
|
|
|
TRIGGER_CLEAR_TYPE(tgtype);
|
|
|
|
if (stmt->row)
|
|
|
|
TRIGGER_SETT_ROW(tgtype);
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype |= stmt->timing;
|
2009-06-18 03:27:02 +02:00
|
|
|
tgtype |= stmt->events;
|
1997-10-28 16:11:45 +01:00
|
|
|
|
2009-06-18 03:27:02 +02:00
|
|
|
/* Disallow ROW-level TRUNCATE triggers */
|
|
|
|
if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("TRUNCATE FOR EACH ROW triggers are not supported")));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
/* INSTEAD triggers must be row-level, and can't have WHEN or columns */
|
|
|
|
if (TRIGGER_FOR_INSTEAD(tgtype))
|
|
|
|
{
|
|
|
|
if (!TRIGGER_FOR_ROW(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("INSTEAD OF triggers must be FOR EACH ROW")));
|
|
|
|
if (stmt->whenClause)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
2011-04-10 17:42:00 +02:00
|
|
|
errmsg("INSTEAD OF triggers cannot have WHEN conditions")));
|
2010-10-10 19:43:33 +02:00
|
|
|
if (stmt->columns != NIL)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("INSTEAD OF triggers cannot have column lists")));
|
|
|
|
}
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
/*
|
|
|
|
* We don't yet support naming ROW transition variables, but the parser
|
|
|
|
* recognizes the syntax so we can give a nicer message here.
|
|
|
|
*
|
|
|
|
* Per standard, REFERENCING TABLE names are only allowed on AFTER
|
|
|
|
* triggers. Per standard, REFERENCING ROW names are not allowed with FOR
|
|
|
|
* EACH STATEMENT. Per standard, each OLD/NEW, ROW/TABLE permutation is
|
|
|
|
* only allowed once. Per standard, OLD may not be specified when
|
|
|
|
* creating a trigger only for INSERT, and NEW may not be specified when
|
|
|
|
* creating a trigger only for DELETE.
|
|
|
|
*
|
|
|
|
* Notice that the standard allows an AFTER ... FOR EACH ROW trigger to
|
|
|
|
* reference both ROW and TABLE transition data.
|
|
|
|
*/
|
|
|
|
if (stmt->transitionRels != NIL)
|
|
|
|
{
|
|
|
|
List *varList = stmt->transitionRels;
|
|
|
|
ListCell *lc;
|
|
|
|
|
|
|
|
foreach(lc, varList)
|
|
|
|
{
|
Improve castNode notation by introducing list-extraction-specific variants.
This extends the castNode() notation introduced by commit 5bcab1114 to
provide, in one step, extraction of a list cell's pointer and coercion to
a concrete node type. For example, "lfirst_node(Foo, lc)" is the same
as "castNode(Foo, lfirst(lc))". Almost half of the uses of castNode
that have appeared so far include a list extraction call, so this is
pretty widely useful, and it saves a few more keystrokes compared to the
old way.
As with the previous patch, back-patch the addition of these macros to
pg_list.h, so that the notation will be available when back-patching.
Patch by me, after an idea of Andrew Gierth's.
Discussion: https://postgr.es/m/14197.1491841216@sss.pgh.pa.us
2017-04-10 19:51:29 +02:00
|
|
|
TriggerTransition *tt = lfirst_node(TriggerTransition, lc);
|
2016-11-04 16:49:50 +01:00
|
|
|
|
|
|
|
if (!(tt->isTable))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("ROW variable naming in the REFERENCING clause is not supported"),
|
|
|
|
errhint("Use OLD TABLE or NEW TABLE for naming transition tables.")));
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Because of the above test, we omit further ROW-related testing
|
|
|
|
* below. If we later allow naming OLD and NEW ROW variables,
|
|
|
|
* adjustments will be needed below.
|
|
|
|
*/
|
|
|
|
|
2017-04-01 06:17:18 +02:00
|
|
|
if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("\"%s\" is a partitioned table",
|
|
|
|
RelationGetRelationName(rel)),
|
|
|
|
errdetail("Triggers on partitioned tables cannot have transition tables.")));
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
if (stmt->timing != TRIGGER_TYPE_AFTER)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("transition table name can only be specified for an AFTER trigger")));
|
|
|
|
|
|
|
|
if (tt->isNew)
|
|
|
|
{
|
|
|
|
if (!(TRIGGER_FOR_INSERT(tgtype) ||
|
|
|
|
TRIGGER_FOR_UPDATE(tgtype)))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("NEW TABLE can only be specified for an INSERT or UPDATE trigger")));
|
|
|
|
|
|
|
|
if (newtablename != NULL)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("NEW TABLE cannot be specified multiple times")));
|
|
|
|
|
|
|
|
newtablename = tt->name;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
if (!(TRIGGER_FOR_DELETE(tgtype) ||
|
|
|
|
TRIGGER_FOR_UPDATE(tgtype)))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("OLD TABLE can only be specified for a DELETE or UPDATE trigger")));
|
|
|
|
|
|
|
|
if (oldtablename != NULL)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("OLD TABLE cannot be specified multiple times")));
|
|
|
|
|
|
|
|
oldtablename = tt->name;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (newtablename != NULL && oldtablename != NULL &&
|
|
|
|
strcmp(newtablename, oldtablename) == 0)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("OLD TABLE name and NEW TABLE name cannot be the same")));
|
|
|
|
}
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
/*
|
|
|
|
* Parse the WHEN clause, if any
|
|
|
|
*/
|
|
|
|
if (stmt->whenClause)
|
|
|
|
{
|
2010-02-26 03:01:40 +01:00
|
|
|
ParseState *pstate;
|
2009-11-20 21:38:12 +01:00
|
|
|
RangeTblEntry *rte;
|
2010-02-26 03:01:40 +01:00
|
|
|
List *varList;
|
|
|
|
ListCell *lc;
|
2009-11-20 21:38:12 +01:00
|
|
|
|
|
|
|
/* Set up a pstate to parse with */
|
|
|
|
pstate = make_parsestate(NULL);
|
|
|
|
pstate->p_sourcetext = queryString;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Set up RTEs for OLD and NEW references.
|
|
|
|
*
|
|
|
|
* 'OLD' must always have varno equal to 1 and 'NEW' equal to 2.
|
|
|
|
*/
|
|
|
|
rte = addRangeTableEntryForRelation(pstate, rel,
|
|
|
|
makeAlias("old", NIL),
|
|
|
|
false, false);
|
|
|
|
addRTEtoQuery(pstate, rte, false, true, true);
|
|
|
|
rte = addRangeTableEntryForRelation(pstate, rel,
|
|
|
|
makeAlias("new", NIL),
|
|
|
|
false, false);
|
|
|
|
addRTEtoQuery(pstate, rte, false, true, true);
|
|
|
|
|
|
|
|
/* Transform expression. Copy to be sure we don't modify original */
|
|
|
|
whenClause = transformWhereClause(pstate,
|
|
|
|
copyObject(stmt->whenClause),
|
Centralize the logic for detecting misplaced aggregates, window funcs, etc.
Formerly we relied on checking after-the-fact to see if an expression
contained aggregates, window functions, or sub-selects when it shouldn't.
This is grotty, easily forgotten (indeed, we had forgotten to teach
DefineIndex about rejecting window functions), and none too efficient
since it requires extra traversals of the parse tree. To improve matters,
define an enum type that classifies all SQL sub-expressions, store it in
ParseState to show what kind of expression we are currently parsing, and
make transformAggregateCall, transformWindowFuncCall, and transformSubLink
check the expression type and throw error if the type indicates the
construct is disallowed. This allows removal of a large number of ad-hoc
checks scattered around the code base. The enum type is sufficiently
fine-grained that we can still produce error messages of at least the
same specificity as before.
Bringing these error checks together revealed that we'd been none too
consistent about phrasing of the error messages, so standardize the wording
a bit.
Also, rewrite checking of aggregate arguments so that it requires only one
traversal of the arguments, rather than up to three as before.
In passing, clean up some more comments left over from add_missing_from
support, and annotate some tests that I think are dead code now that that's
gone. (I didn't risk actually removing said dead code, though.)
2012-08-10 17:35:33 +02:00
|
|
|
EXPR_KIND_TRIGGER_WHEN,
|
2009-11-20 21:38:12 +01:00
|
|
|
"WHEN");
|
2011-04-07 08:34:57 +02:00
|
|
|
/* we have to fix its collations too */
|
|
|
|
assign_expr_collations(pstate, whenClause);
|
2009-11-20 21:38:12 +01:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Check for disallowed references to OLD/NEW.
|
|
|
|
*
|
|
|
|
* NB: pull_var_clause is okay here only because we don't allow
|
|
|
|
* subselects in WHEN clauses; it would fail to examine the contents
|
|
|
|
* of subselects.
|
|
|
|
*/
|
2016-03-10 21:52:58 +01:00
|
|
|
varList = pull_var_clause(whenClause, 0);
|
2009-11-20 21:38:12 +01:00
|
|
|
foreach(lc, varList)
|
|
|
|
{
|
|
|
|
Var *var = (Var *) lfirst(lc);
|
|
|
|
|
|
|
|
switch (var->varno)
|
|
|
|
{
|
|
|
|
case PRS2_OLD_VARNO:
|
|
|
|
if (!TRIGGER_FOR_ROW(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("statement trigger's WHEN condition cannot reference column values"),
|
|
|
|
parser_errposition(pstate, var->location)));
|
|
|
|
if (TRIGGER_FOR_INSERT(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("INSERT trigger's WHEN condition cannot reference OLD values"),
|
|
|
|
parser_errposition(pstate, var->location)));
|
|
|
|
/* system columns are okay here */
|
|
|
|
break;
|
|
|
|
case PRS2_NEW_VARNO:
|
|
|
|
if (!TRIGGER_FOR_ROW(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("statement trigger's WHEN condition cannot reference column values"),
|
|
|
|
parser_errposition(pstate, var->location)));
|
|
|
|
if (TRIGGER_FOR_DELETE(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
|
|
|
errmsg("DELETE trigger's WHEN condition cannot reference NEW values"),
|
|
|
|
parser_errposition(pstate, var->location)));
|
|
|
|
if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype))
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("BEFORE trigger's WHEN condition cannot reference NEW system columns"),
|
|
|
|
parser_errposition(pstate, var->location)));
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
/* can't happen without add_missing_from, so just elog */
|
|
|
|
elog(ERROR, "trigger WHEN condition cannot contain references to other relations");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/* we'll need the rtable for recordDependencyOnExpr */
|
|
|
|
whenRtable = pstate->p_rtable;
|
|
|
|
|
|
|
|
qual = nodeToString(whenClause);
|
|
|
|
|
|
|
|
free_parsestate(pstate);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
whenClause = NULL;
|
|
|
|
whenRtable = NIL;
|
|
|
|
qual = NULL;
|
|
|
|
}
|
|
|
|
|
2007-11-04 02:16:19 +01:00
|
|
|
/*
|
|
|
|
* Find and validate the trigger function.
|
|
|
|
*/
|
|
|
|
funcoid = LookupFuncName(stmt->funcname, 0, fargtypes, false);
|
2012-02-23 21:38:56 +01:00
|
|
|
if (!isInternal)
|
|
|
|
{
|
|
|
|
aclresult = pg_proc_aclcheck(funcoid, GetUserId(), ACL_EXECUTE);
|
|
|
|
if (aclresult != ACLCHECK_OK)
|
|
|
|
aclcheck_error(aclresult, ACL_KIND_PROC,
|
|
|
|
NameListToString(stmt->funcname));
|
|
|
|
}
|
2007-11-04 02:16:19 +01:00
|
|
|
funcrettype = get_func_rettype(funcoid);
|
|
|
|
if (funcrettype != TRIGGEROID)
|
|
|
|
{
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* We allow OPAQUE just so we can load old dump files. When we see a
|
2007-11-04 02:16:19 +01:00
|
|
|
* trigger function declared OPAQUE, change it to TRIGGER.
|
|
|
|
*/
|
|
|
|
if (funcrettype == OPAQUEOID)
|
|
|
|
{
|
|
|
|
ereport(WARNING,
|
2017-01-18 20:08:20 +01:00
|
|
|
(errmsg("changing return type of function %s from %s to %s",
|
|
|
|
NameListToString(stmt->funcname),
|
|
|
|
"opaque", "trigger")));
|
2007-11-04 02:16:19 +01:00
|
|
|
SetFunctionReturnType(funcoid, TRIGGEROID);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
|
2016-04-01 18:35:48 +02:00
|
|
|
errmsg("function %s must return type %s",
|
2016-03-28 19:12:00 +02:00
|
|
|
NameListToString(stmt->funcname), "trigger")));
|
2007-11-04 02:16:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2007-11-16 00:23:44 +01:00
|
|
|
* If the command is a user-entered CREATE CONSTRAINT TRIGGER command that
|
|
|
|
* references one of the built-in RI_FKey trigger functions, assume it is
|
|
|
|
* from a dump of a pre-7.3 foreign key constraint, and take steps to
|
|
|
|
* convert this legacy representation into a regular foreign key
|
2014-05-06 18:12:18 +02:00
|
|
|
* constraint. Ugly, but necessary for loading old dump files.
|
2007-11-04 02:16:19 +01:00
|
|
|
*/
|
2010-01-17 23:56:23 +01:00
|
|
|
if (stmt->isconstraint && !isInternal &&
|
2007-11-04 02:16:19 +01:00
|
|
|
list_length(stmt->args) >= 6 &&
|
|
|
|
(list_length(stmt->args) % 2) == 0 &&
|
|
|
|
RI_FKey_trigger_type(funcoid) != RI_TRIGGER_NONE)
|
|
|
|
{
|
|
|
|
/* Keep lock on target rel until end of xact */
|
|
|
|
heap_close(rel, NoLock);
|
|
|
|
|
2007-11-05 20:00:25 +01:00
|
|
|
ConvertTriggerToFK(stmt, funcoid);
|
|
|
|
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
return InvalidObjectAddress;
|
2007-11-04 02:16:19 +01:00
|
|
|
}
|
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
/*
|
|
|
|
* If it's a user-entered CREATE CONSTRAINT TRIGGER command, make a
|
|
|
|
* corresponding pg_constraint entry.
|
|
|
|
*/
|
|
|
|
if (stmt->isconstraint && !OidIsValid(constraintOid))
|
|
|
|
{
|
|
|
|
/* Internal callers should have made their own constraints */
|
|
|
|
Assert(!isInternal);
|
|
|
|
constraintOid = CreateConstraintEntry(stmt->trigname,
|
|
|
|
RelationGetNamespace(rel),
|
|
|
|
CONSTRAINT_TRIGGER,
|
|
|
|
stmt->deferrable,
|
|
|
|
stmt->initdeferred,
|
2011-02-08 13:23:20 +01:00
|
|
|
true,
|
2010-01-17 23:56:23 +01:00
|
|
|
RelationGetRelid(rel),
|
2010-02-26 03:01:40 +01:00
|
|
|
NULL, /* no conkey */
|
2010-01-17 23:56:23 +01:00
|
|
|
0,
|
2010-02-26 03:01:40 +01:00
|
|
|
InvalidOid, /* no domain */
|
|
|
|
InvalidOid, /* no index */
|
|
|
|
InvalidOid, /* no foreign key */
|
2010-01-17 23:56:23 +01:00
|
|
|
NULL,
|
|
|
|
NULL,
|
|
|
|
NULL,
|
|
|
|
NULL,
|
|
|
|
0,
|
|
|
|
' ',
|
|
|
|
' ',
|
|
|
|
' ',
|
|
|
|
NULL, /* no exclusion */
|
|
|
|
NULL, /* no check constraint */
|
|
|
|
NULL,
|
|
|
|
NULL,
|
|
|
|
true, /* islocal */
|
2011-12-05 19:10:18 +01:00
|
|
|
0, /* inhcount */
|
2013-03-18 03:55:14 +01:00
|
|
|
true, /* isnoinherit */
|
2013-05-29 22:58:43 +02:00
|
|
|
isInternal); /* is_internal */
|
2010-01-17 23:56:23 +01:00
|
|
|
}
|
|
|
|
|
2007-11-04 02:16:19 +01:00
|
|
|
/*
|
|
|
|
* Generate the trigger's OID now, so that we can use it in the name if
|
|
|
|
* needed.
|
|
|
|
*/
|
|
|
|
tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
|
|
|
|
|
|
|
|
trigoid = GetNewOid(tgrel);
|
|
|
|
|
|
|
|
/*
|
2010-02-26 03:01:40 +01:00
|
|
|
* If trigger is internally generated, modify the provided trigger name to
|
2014-05-06 18:12:18 +02:00
|
|
|
* ensure uniqueness by appending the trigger OID. (Callers will usually
|
2010-02-26 03:01:40 +01:00
|
|
|
* supply a simple constant trigger name in these cases.)
|
2007-11-04 02:16:19 +01:00
|
|
|
*/
|
2010-01-17 23:56:23 +01:00
|
|
|
if (isInternal)
|
2007-11-04 02:16:19 +01:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
snprintf(internaltrigname, sizeof(internaltrigname),
|
|
|
|
"%s_%u", stmt->trigname, trigoid);
|
|
|
|
trigname = internaltrigname;
|
2007-11-04 02:16:19 +01:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
/* user-defined trigger; use the specified trigger name as-is */
|
2007-11-04 02:16:19 +01:00
|
|
|
trigname = stmt->trigname;
|
|
|
|
}
|
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
2009-06-11 16:49:15 +02:00
|
|
|
* Scan pg_trigger for existing triggers on relation. We do this only to
|
|
|
|
* give a nice error message if there's already a trigger of the same
|
2010-02-26 03:01:40 +01:00
|
|
|
* name. (The unique index on tgrelid/tgname would complain anyway.) We
|
|
|
|
* can skip this for internally generated triggers, since the name
|
2010-01-17 23:56:23 +01:00
|
|
|
* modification above should be sufficient.
|
2002-04-19 18:36:08 +02:00
|
|
|
*
|
2016-06-10 00:02:36 +02:00
|
|
|
* NOTE that this is cool only because we have ShareRowExclusiveLock on
|
|
|
|
* the relation, so the trigger set won't be changing underneath us.
|
2000-07-03 05:57:03 +02:00
|
|
|
*/
|
2010-01-17 23:56:23 +01:00
|
|
|
if (!isInternal)
|
1997-09-07 07:04:48 +02:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
ScanKeyInit(&key,
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(RelationGetRelid(rel)));
|
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 1, &key);
|
2010-01-17 23:56:23 +01:00
|
|
|
while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
|
|
|
|
{
|
|
|
|
Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
if (namestrcmp(&(pg_trigger->tgname), trigname) == 0)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_DUPLICATE_OBJECT),
|
2010-02-26 03:01:40 +01:00
|
|
|
errmsg("trigger \"%s\" for relation \"%s\" already exists",
|
Avoid repeated name lookups during table and index DDL.
If the name lookups come to different conclusions due to concurrent
activity, we might perform some parts of the DDL on a different table
than other parts. At least in the case of CREATE INDEX, this can be
used to cause the permissions checks to be performed against a
different table than the index creation, allowing for a privilege
escalation attack.
This changes the calling convention for DefineIndex, CreateTrigger,
transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible
(in 9.2 and newer), and AlterTable (in 9.1 and older). In addition,
CheckRelationOwnership is removed in 9.2 and newer and the calling
convention is changed in older branches. A field has also been added
to the Constraint node (FkConstraint in 8.4). Third-party code calling
these functions or using the Constraint node will require updating.
Report by Andres Freund. Patch by Robert Haas and Andres Freund,
reviewed by Tom Lane.
Security: CVE-2014-0062
2014-02-17 15:33:31 +01:00
|
|
|
trigname, RelationGetRelationName(rel))));
|
2010-01-17 23:56:23 +01:00
|
|
|
}
|
|
|
|
systable_endscan(tgscan);
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
|
|
|
* Build the new pg_trigger tuple.
|
|
|
|
*/
|
2008-11-02 02:45:28 +01:00
|
|
|
memset(nulls, false, sizeof(nulls));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
1998-08-19 04:04:17 +02:00
|
|
|
values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
|
2000-08-03 18:35:08 +02:00
|
|
|
values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein,
|
2005-10-15 04:49:52 +02:00
|
|
|
CStringGetDatum(trigname));
|
2000-07-03 05:57:03 +02:00
|
|
|
values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
|
1997-09-07 07:04:48 +02:00
|
|
|
values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
|
2007-03-20 00:38:32 +01:00
|
|
|
values[Anum_pg_trigger_tgenabled - 1] = CharGetDatum(TRIGGER_FIRES_ON_ORIGIN);
|
2010-01-17 23:56:23 +01:00
|
|
|
values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal);
|
2000-07-03 05:57:03 +02:00
|
|
|
values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
|
2009-07-28 04:56:31 +02:00
|
|
|
values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
|
2007-02-14 02:58:58 +01:00
|
|
|
values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
|
2000-07-03 05:57:03 +02:00
|
|
|
values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable);
|
|
|
|
values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
1997-09-07 07:04:48 +02:00
|
|
|
if (stmt->args)
|
|
|
|
{
|
2004-05-26 06:41:50 +02:00
|
|
|
ListCell *le;
|
1997-09-08 04:41:22 +02:00
|
|
|
char *args;
|
2004-05-26 06:41:50 +02:00
|
|
|
int16 nargs = list_length(stmt->args);
|
1997-09-08 04:41:22 +02:00
|
|
|
int len = 0;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
|
|
|
foreach(le, stmt->args)
|
|
|
|
{
|
2002-08-25 19:20:01 +02:00
|
|
|
char *ar = strVal(lfirst(le));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
len += strlen(ar) + 4;
|
1997-10-28 16:11:45 +01:00
|
|
|
for (; *ar; ar++)
|
1997-10-02 15:52:29 +02:00
|
|
|
{
|
|
|
|
if (*ar == '\\')
|
|
|
|
len++;
|
|
|
|
}
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
|
|
|
args = (char *) palloc(len + 1);
|
2000-08-12 01:45:35 +02:00
|
|
|
args[0] = '\0';
|
1997-09-07 07:04:48 +02:00
|
|
|
foreach(le, stmt->args)
|
1997-10-02 15:52:29 +02:00
|
|
|
{
|
2002-08-25 19:20:01 +02:00
|
|
|
char *s = strVal(lfirst(le));
|
1997-10-28 16:11:45 +01:00
|
|
|
char *d = args + strlen(args);
|
|
|
|
|
1997-10-02 15:52:29 +02:00
|
|
|
while (*s)
|
|
|
|
{
|
|
|
|
if (*s == '\\')
|
|
|
|
*d++ = '\\';
|
|
|
|
*d++ = *s++;
|
|
|
|
}
|
2000-08-12 01:45:35 +02:00
|
|
|
strcpy(d, "\\000");
|
1997-10-02 15:52:29 +02:00
|
|
|
}
|
1997-09-07 07:04:48 +02:00
|
|
|
values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
|
2000-07-29 05:26:51 +02:00
|
|
|
values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
|
2005-10-15 04:49:52 +02:00
|
|
|
CStringGetDatum(args));
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
|
2000-07-29 05:26:51 +02:00
|
|
|
values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
|
2005-10-15 04:49:52 +02:00
|
|
|
CStringGetDatum(""));
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
2007-11-04 02:16:19 +01:00
|
|
|
|
2009-10-15 00:14:25 +02:00
|
|
|
/* build column number array if it's a column-specific trigger */
|
|
|
|
ncolumns = list_length(stmt->columns);
|
|
|
|
if (ncolumns == 0)
|
|
|
|
columns = NULL;
|
|
|
|
else
|
|
|
|
{
|
|
|
|
ListCell *cell;
|
|
|
|
int i = 0;
|
|
|
|
|
2012-06-25 00:51:46 +02:00
|
|
|
columns = (int16 *) palloc(ncolumns * sizeof(int16));
|
2009-10-15 00:14:25 +02:00
|
|
|
foreach(cell, stmt->columns)
|
|
|
|
{
|
2010-02-26 03:01:40 +01:00
|
|
|
char *name = strVal(lfirst(cell));
|
2012-06-25 00:51:46 +02:00
|
|
|
int16 attnum;
|
2010-02-26 03:01:40 +01:00
|
|
|
int j;
|
2009-10-15 00:14:25 +02:00
|
|
|
|
2014-05-06 18:12:18 +02:00
|
|
|
/* Lookup column name. System columns are not allowed */
|
2009-10-15 00:14:25 +02:00
|
|
|
attnum = attnameAttNum(rel, name, false);
|
|
|
|
if (attnum == InvalidAttrNumber)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_UNDEFINED_COLUMN),
|
2010-02-26 03:01:40 +01:00
|
|
|
errmsg("column \"%s\" of relation \"%s\" does not exist",
|
|
|
|
name, RelationGetRelationName(rel))));
|
2009-10-15 00:14:25 +02:00
|
|
|
|
|
|
|
/* Check for duplicates */
|
|
|
|
for (j = i - 1; j >= 0; j--)
|
|
|
|
{
|
|
|
|
if (columns[j] == attnum)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_DUPLICATE_COLUMN),
|
|
|
|
errmsg("column \"%s\" specified more than once",
|
|
|
|
name)));
|
|
|
|
}
|
|
|
|
|
|
|
|
columns[i++] = attnum;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tgattr = buildint2vector(columns, ncolumns);
|
1997-09-07 07:04:48 +02:00
|
|
|
values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
/* set tgqual if trigger has WHEN clause */
|
|
|
|
if (qual)
|
|
|
|
values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
|
|
|
|
else
|
|
|
|
nulls[Anum_pg_trigger_tgqual - 1] = true;
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
if (oldtablename)
|
|
|
|
values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
|
|
|
|
CStringGetDatum(oldtablename));
|
|
|
|
else
|
|
|
|
nulls[Anum_pg_trigger_tgoldtable - 1] = true;
|
|
|
|
if (newtablename)
|
|
|
|
values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
|
|
|
|
CStringGetDatum(newtablename));
|
|
|
|
else
|
|
|
|
nulls[Anum_pg_trigger_tgnewtable - 1] = true;
|
|
|
|
|
2008-11-02 02:45:28 +01:00
|
|
|
tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
|
2000-07-03 05:57:03 +02:00
|
|
|
|
2002-07-20 21:55:38 +02:00
|
|
|
/* force tuple to have the desired OID */
|
|
|
|
HeapTupleSetOid(tuple, trigoid);
|
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
|
|
|
* Insert tuple into pg_trigger.
|
|
|
|
*/
|
2017-01-31 22:42:24 +01:00
|
|
|
CatalogTupleInsert(tgrel, tuple);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
1999-12-16 23:20:03 +01:00
|
|
|
heap_freetuple(tuple);
|
1999-09-18 21:08:25 +02:00
|
|
|
heap_close(tgrel, RowExclusiveLock);
|
1997-09-07 07:04:48 +02:00
|
|
|
|
|
|
|
pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1]));
|
|
|
|
pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1]));
|
2009-10-15 00:14:25 +02:00
|
|
|
pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1]));
|
2016-11-04 16:49:50 +01:00
|
|
|
if (oldtablename)
|
|
|
|
pfree(DatumGetPointer(values[Anum_pg_trigger_tgoldtable - 1]));
|
|
|
|
if (newtablename)
|
|
|
|
pfree(DatumGetPointer(values[Anum_pg_trigger_tgnewtable - 1]));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Update relation's pg_class entry. Crucial side-effect: other backends
|
|
|
|
* (and this one too!) are sent SI message to make them rebuild relcache
|
|
|
|
* entries.
|
2000-07-03 05:57:03 +02:00
|
|
|
*/
|
2005-04-14 22:03:27 +02:00
|
|
|
pgrel = heap_open(RelationRelationId, RowExclusiveLock);
|
2010-02-14 19:42:19 +01:00
|
|
|
tuple = SearchSysCacheCopy1(RELOID,
|
|
|
|
ObjectIdGetDatum(RelationGetRelid(rel)));
|
1998-08-19 04:04:17 +02:00
|
|
|
if (!HeapTupleIsValid(tuple))
|
2003-07-20 23:56:35 +02:00
|
|
|
elog(ERROR, "cache lookup failed for relation %u",
|
|
|
|
RelationGetRelid(rel));
|
1998-08-19 04:04:17 +02:00
|
|
|
|
2008-11-09 22:24:33 +01:00
|
|
|
((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
|
2002-07-12 20:43:19 +02:00
|
|
|
|
2017-01-31 22:42:24 +01:00
|
|
|
CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
1999-12-16 23:20:03 +01:00
|
|
|
heap_freetuple(tuple);
|
1999-09-18 21:08:25 +02:00
|
|
|
heap_close(pgrel, RowExclusiveLock);
|
2000-04-12 19:17:23 +02:00
|
|
|
|
2000-01-31 05:35:57 +01:00
|
|
|
/*
|
|
|
|
* We used to try to update the rel's relcache entry here, but that's
|
2005-10-15 04:49:52 +02:00
|
|
|
* fairly pointless since it will happen as a byproduct of the upcoming
|
|
|
|
* CommandCounterIncrement...
|
2000-01-31 05:35:57 +01:00
|
|
|
*/
|
2000-07-03 05:57:03 +02:00
|
|
|
|
2002-07-12 20:43:19 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Record dependencies for trigger. Always place a normal dependency on
|
2007-02-14 02:58:58 +01:00
|
|
|
* the function.
|
2002-07-12 20:43:19 +02:00
|
|
|
*/
|
2007-02-14 02:58:58 +01:00
|
|
|
myself.classId = TriggerRelationId;
|
|
|
|
myself.objectId = trigoid;
|
|
|
|
myself.objectSubId = 0;
|
|
|
|
|
2005-04-14 03:38:22 +02:00
|
|
|
referenced.classId = ProcedureRelationId;
|
2002-07-12 20:43:19 +02:00
|
|
|
referenced.objectId = funcoid;
|
|
|
|
referenced.objectSubId = 0;
|
|
|
|
recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
|
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
if (isInternal && OidIsValid(constraintOid))
|
2007-02-14 02:58:58 +01:00
|
|
|
{
|
|
|
|
/*
|
2010-01-17 23:56:23 +01:00
|
|
|
* Internally-generated trigger for a constraint, so make it an
|
|
|
|
* internal dependency of the constraint. We can skip depending on
|
|
|
|
* the relation(s), as there'll be an indirect dependency via the
|
|
|
|
* constraint.
|
2007-02-14 02:58:58 +01:00
|
|
|
*/
|
|
|
|
referenced.classId = ConstraintRelationId;
|
|
|
|
referenced.objectId = constraintOid;
|
|
|
|
referenced.objectSubId = 0;
|
|
|
|
recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
|
|
|
|
}
|
|
|
|
else
|
2002-07-12 20:43:19 +02:00
|
|
|
{
|
2007-02-14 02:58:58 +01:00
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* User CREATE TRIGGER, so place dependencies. We make trigger be
|
2007-02-14 02:58:58 +01:00
|
|
|
* auto-dropped if its relation is dropped or if the FK relation is
|
|
|
|
* dropped. (Auto drop is compatible with our pre-7.3 behavior.)
|
|
|
|
*/
|
2005-04-14 03:38:22 +02:00
|
|
|
referenced.classId = RelationRelationId;
|
2002-07-12 20:43:19 +02:00
|
|
|
referenced.objectId = RelationGetRelid(rel);
|
|
|
|
referenced.objectSubId = 0;
|
|
|
|
recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
|
2009-07-28 04:56:31 +02:00
|
|
|
if (OidIsValid(constrrelid))
|
2002-07-12 20:43:19 +02:00
|
|
|
{
|
2005-04-14 03:38:22 +02:00
|
|
|
referenced.classId = RelationRelationId;
|
2002-07-12 20:43:19 +02:00
|
|
|
referenced.objectId = constrrelid;
|
|
|
|
referenced.objectSubId = 0;
|
|
|
|
recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
|
|
|
|
}
|
2009-07-28 04:56:31 +02:00
|
|
|
/* Not possible to have an index dependency in this case */
|
|
|
|
Assert(!OidIsValid(indexOid));
|
2010-02-26 03:01:40 +01:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
/*
|
|
|
|
* If it's a user-specified constraint trigger, make the constraint
|
|
|
|
* internally dependent on the trigger instead of vice versa.
|
|
|
|
*/
|
|
|
|
if (OidIsValid(constraintOid))
|
|
|
|
{
|
|
|
|
referenced.classId = ConstraintRelationId;
|
|
|
|
referenced.objectId = constraintOid;
|
|
|
|
referenced.objectSubId = 0;
|
|
|
|
recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
|
|
|
|
}
|
2002-07-12 20:43:19 +02:00
|
|
|
}
|
|
|
|
|
2009-10-15 00:14:25 +02:00
|
|
|
/* If column-specific trigger, add normal dependencies on columns */
|
|
|
|
if (columns != NULL)
|
|
|
|
{
|
2010-02-26 03:01:40 +01:00
|
|
|
int i;
|
2009-10-15 00:14:25 +02:00
|
|
|
|
|
|
|
referenced.classId = RelationRelationId;
|
|
|
|
referenced.objectId = RelationGetRelid(rel);
|
|
|
|
for (i = 0; i < ncolumns; i++)
|
|
|
|
{
|
|
|
|
referenced.objectSubId = columns[i];
|
|
|
|
recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
/*
|
2010-02-26 03:01:40 +01:00
|
|
|
* If it has a WHEN clause, add dependencies on objects mentioned in the
|
|
|
|
* expression (eg, functions, as well as any columns used).
|
2009-11-20 21:38:12 +01:00
|
|
|
*/
|
|
|
|
if (whenClause != NULL)
|
|
|
|
recordDependencyOnExpr(&myself, whenClause, whenRtable,
|
|
|
|
DEPENDENCY_NORMAL);
|
|
|
|
|
2010-11-25 17:48:49 +01:00
|
|
|
/* Post creation hook for new trigger */
|
2013-03-18 03:55:14 +01:00
|
|
|
InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0,
|
|
|
|
isInternal);
|
2010-11-25 17:48:49 +01:00
|
|
|
|
1999-09-18 21:08:25 +02:00
|
|
|
/* Keep lock on target rel until end of xact */
|
|
|
|
heap_close(rel, NoLock);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
return myself;
|
1997-08-31 13:40:13 +02:00
|
|
|
}
|
|
|
|
|
2007-11-04 02:16:19 +01:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Convert legacy (pre-7.3) CREATE CONSTRAINT TRIGGER commands into
|
|
|
|
* full-fledged foreign key constraints.
|
|
|
|
*
|
|
|
|
* The conversion is complex because a pre-7.3 foreign key involved three
|
2014-05-06 18:12:18 +02:00
|
|
|
* separate triggers, which were reported separately in dumps. While the
|
2007-11-05 20:00:25 +01:00
|
|
|
* single trigger on the referencing table adds no new information, we need
|
|
|
|
* to know the trigger functions of both of the triggers on the referenced
|
|
|
|
* table to build the constraint declaration. Also, due to lack of proper
|
|
|
|
* dependency checking pre-7.3, it is possible that the source database had
|
|
|
|
* an incomplete set of triggers resulting in an only partially enforced
|
|
|
|
* FK constraint. (This would happen if one of the tables had been dropped
|
|
|
|
* and re-created, but only if the DB had been affected by a 7.0 pg_dump bug
|
2007-11-16 00:23:44 +01:00
|
|
|
* that caused loss of tgconstrrelid information.) We choose to translate to
|
2007-11-05 20:00:25 +01:00
|
|
|
* an FK constraint only when we've seen all three triggers of a set. This is
|
|
|
|
* implemented by storing unmatched items in a list in TopMemoryContext.
|
|
|
|
* We match triggers together by comparing the trigger arguments (which
|
|
|
|
* include constraint name, table and column names, so should be good enough).
|
2007-11-04 02:16:19 +01:00
|
|
|
*/
|
2007-11-16 00:23:44 +01:00
|
|
|
typedef struct
|
|
|
|
{
|
2007-11-04 02:16:19 +01:00
|
|
|
List *args; /* list of (T_String) Values or NIL */
|
2007-11-05 20:00:25 +01:00
|
|
|
Oid funcoids[3]; /* OIDs of trigger functions */
|
|
|
|
/* The three function OIDs are stored in the order update, delete, child */
|
2007-11-04 02:16:19 +01:00
|
|
|
} OldTriggerInfo;
|
|
|
|
|
|
|
|
static void
|
|
|
|
ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid)
|
|
|
|
{
|
|
|
|
static List *info_list = NIL;
|
|
|
|
|
2007-11-16 00:23:44 +01:00
|
|
|
static const char *const funcdescr[3] = {
|
2007-11-05 20:00:25 +01:00
|
|
|
gettext_noop("Found referenced table's UPDATE trigger."),
|
|
|
|
gettext_noop("Found referenced table's DELETE trigger."),
|
|
|
|
gettext_noop("Found referencing table's trigger.")
|
|
|
|
};
|
|
|
|
|
2007-11-04 22:25:55 +01:00
|
|
|
char *constr_name;
|
|
|
|
char *fk_table_name;
|
|
|
|
char *pk_table_name;
|
2012-06-18 02:16:07 +02:00
|
|
|
char fk_matchtype = FKCONSTR_MATCH_SIMPLE;
|
2007-11-04 22:25:55 +01:00
|
|
|
List *fk_attrs = NIL;
|
|
|
|
List *pk_attrs = NIL;
|
|
|
|
StringInfoData buf;
|
2007-11-05 20:00:25 +01:00
|
|
|
int funcnum;
|
2007-11-04 02:16:19 +01:00
|
|
|
OldTriggerInfo *info = NULL;
|
|
|
|
ListCell *l;
|
2007-11-04 22:25:55 +01:00
|
|
|
int i;
|
|
|
|
|
|
|
|
/* Parse out the trigger arguments */
|
|
|
|
constr_name = strVal(linitial(stmt->args));
|
|
|
|
fk_table_name = strVal(lsecond(stmt->args));
|
|
|
|
pk_table_name = strVal(lthird(stmt->args));
|
|
|
|
i = 0;
|
|
|
|
foreach(l, stmt->args)
|
|
|
|
{
|
2007-11-16 00:23:44 +01:00
|
|
|
Value *arg = (Value *) lfirst(l);
|
2007-11-04 22:25:55 +01:00
|
|
|
|
|
|
|
i++;
|
|
|
|
if (i < 4) /* skip constraint and table names */
|
|
|
|
continue;
|
|
|
|
if (i == 4) /* handle match type */
|
|
|
|
{
|
|
|
|
if (strcmp(strVal(arg), "FULL") == 0)
|
|
|
|
fk_matchtype = FKCONSTR_MATCH_FULL;
|
|
|
|
else
|
2012-06-18 02:16:07 +02:00
|
|
|
fk_matchtype = FKCONSTR_MATCH_SIMPLE;
|
2007-11-04 22:25:55 +01:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (i % 2)
|
|
|
|
fk_attrs = lappend(fk_attrs, arg);
|
|
|
|
else
|
|
|
|
pk_attrs = lappend(pk_attrs, arg);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Prepare description of constraint for use in messages */
|
|
|
|
initStringInfo(&buf);
|
|
|
|
appendStringInfo(&buf, "FOREIGN KEY %s(",
|
|
|
|
quote_identifier(fk_table_name));
|
|
|
|
i = 0;
|
|
|
|
foreach(l, fk_attrs)
|
|
|
|
{
|
2007-11-16 00:23:44 +01:00
|
|
|
Value *arg = (Value *) lfirst(l);
|
2007-11-04 22:25:55 +01:00
|
|
|
|
|
|
|
if (i++ > 0)
|
|
|
|
appendStringInfoChar(&buf, ',');
|
|
|
|
appendStringInfoString(&buf, quote_identifier(strVal(arg)));
|
|
|
|
}
|
|
|
|
appendStringInfo(&buf, ") REFERENCES %s(",
|
|
|
|
quote_identifier(pk_table_name));
|
|
|
|
i = 0;
|
|
|
|
foreach(l, pk_attrs)
|
|
|
|
{
|
2007-11-16 00:23:44 +01:00
|
|
|
Value *arg = (Value *) lfirst(l);
|
2007-11-04 22:25:55 +01:00
|
|
|
|
|
|
|
if (i++ > 0)
|
|
|
|
appendStringInfoChar(&buf, ',');
|
|
|
|
appendStringInfoString(&buf, quote_identifier(strVal(arg)));
|
|
|
|
}
|
|
|
|
appendStringInfoChar(&buf, ')');
|
2007-11-04 02:16:19 +01:00
|
|
|
|
|
|
|
/* Identify class of trigger --- update, delete, or referencing-table */
|
|
|
|
switch (funcoid)
|
|
|
|
{
|
|
|
|
case F_RI_FKEY_CASCADE_UPD:
|
|
|
|
case F_RI_FKEY_RESTRICT_UPD:
|
|
|
|
case F_RI_FKEY_SETNULL_UPD:
|
|
|
|
case F_RI_FKEY_SETDEFAULT_UPD:
|
|
|
|
case F_RI_FKEY_NOACTION_UPD:
|
2007-11-05 20:00:25 +01:00
|
|
|
funcnum = 0;
|
|
|
|
break;
|
|
|
|
|
|
|
|
case F_RI_FKEY_CASCADE_DEL:
|
|
|
|
case F_RI_FKEY_RESTRICT_DEL:
|
|
|
|
case F_RI_FKEY_SETNULL_DEL:
|
|
|
|
case F_RI_FKEY_SETDEFAULT_DEL:
|
|
|
|
case F_RI_FKEY_NOACTION_DEL:
|
|
|
|
funcnum = 1;
|
2007-11-04 02:16:19 +01:00
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
2007-11-05 20:00:25 +01:00
|
|
|
funcnum = 2;
|
|
|
|
break;
|
2007-11-04 02:16:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/* See if we have a match to this trigger */
|
|
|
|
foreach(l, info_list)
|
|
|
|
{
|
|
|
|
info = (OldTriggerInfo *) lfirst(l);
|
2007-11-05 20:00:25 +01:00
|
|
|
if (info->funcoids[funcnum] == InvalidOid &&
|
|
|
|
equal(info->args, stmt->args))
|
|
|
|
{
|
|
|
|
info->funcoids[funcnum] = funcoid;
|
2007-11-04 02:16:19 +01:00
|
|
|
break;
|
2007-11-05 20:00:25 +01:00
|
|
|
}
|
2007-11-04 02:16:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (l == NULL)
|
|
|
|
{
|
2007-11-05 20:00:25 +01:00
|
|
|
/* First trigger of set, so create a new list entry */
|
2007-11-04 02:16:19 +01:00
|
|
|
MemoryContext oldContext;
|
|
|
|
|
|
|
|
ereport(NOTICE,
|
2007-11-16 00:23:44 +01:00
|
|
|
(errmsg("ignoring incomplete trigger group for constraint \"%s\" %s",
|
|
|
|
constr_name, buf.data),
|
2011-07-16 20:21:12 +02:00
|
|
|
errdetail_internal("%s", _(funcdescr[funcnum]))));
|
2007-11-04 02:16:19 +01:00
|
|
|
oldContext = MemoryContextSwitchTo(TopMemoryContext);
|
2007-11-05 20:00:25 +01:00
|
|
|
info = (OldTriggerInfo *) palloc0(sizeof(OldTriggerInfo));
|
2007-11-04 02:16:19 +01:00
|
|
|
info->args = copyObject(stmt->args);
|
2007-11-05 20:00:25 +01:00
|
|
|
info->funcoids[funcnum] = funcoid;
|
2007-11-04 02:16:19 +01:00
|
|
|
info_list = lappend(info_list, info);
|
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
}
|
2007-11-05 20:00:25 +01:00
|
|
|
else if (info->funcoids[0] == InvalidOid ||
|
|
|
|
info->funcoids[1] == InvalidOid ||
|
|
|
|
info->funcoids[2] == InvalidOid)
|
|
|
|
{
|
|
|
|
/* Second trigger of set */
|
|
|
|
ereport(NOTICE,
|
2007-11-16 00:23:44 +01:00
|
|
|
(errmsg("ignoring incomplete trigger group for constraint \"%s\" %s",
|
|
|
|
constr_name, buf.data),
|
2011-07-16 20:21:12 +02:00
|
|
|
errdetail_internal("%s", _(funcdescr[funcnum]))));
|
2007-11-05 20:00:25 +01:00
|
|
|
}
|
2007-11-04 02:16:19 +01:00
|
|
|
else
|
|
|
|
{
|
2007-11-05 20:00:25 +01:00
|
|
|
/* OK, we have a set, so make the FK constraint ALTER TABLE cmd */
|
2007-11-04 02:16:19 +01:00
|
|
|
AlterTableStmt *atstmt = makeNode(AlterTableStmt);
|
|
|
|
AlterTableCmd *atcmd = makeNode(AlterTableCmd);
|
2009-07-30 04:45:38 +02:00
|
|
|
Constraint *fkcon = makeNode(Constraint);
|
Change representation of statement lists, and add statement location info.
This patch makes several changes that improve the consistency of
representation of lists of statements. It's always been the case
that the output of parse analysis is a list of Query nodes, whatever
the types of the individual statements in the list. This patch brings
similar consistency to the outputs of raw parsing and planning steps:
* The output of raw parsing is now always a list of RawStmt nodes;
the statement-type-dependent nodes are one level down from that.
* The output of pg_plan_queries() is now always a list of PlannedStmt
nodes, even for utility statements. In the case of a utility statement,
"planning" just consists of wrapping a CMD_UTILITY PlannedStmt around
the utility node. This list representation is now used in Portal and
CachedPlan plan lists, replacing the former convention of intermixing
PlannedStmts with bare utility-statement nodes.
Now, every list of statements has a consistent head-node type depending
on how far along it is in processing. This allows changing many places
that formerly used generic "Node *" pointers to use a more specific
pointer type, thus reducing the number of IsA() tests and casts needed,
as well as improving code clarity.
Also, the post-parse-analysis representation of DECLARE CURSOR is changed
so that it looks more like EXPLAIN, PREPARE, etc. That is, the contained
SELECT remains a child of the DeclareCursorStmt rather than getting flipped
around to be the other way. It's now true for both Query and PlannedStmt
that utilityStmt is non-null if and only if commandType is CMD_UTILITY.
That allows simplifying a lot of places that were testing both fields.
(I think some of those were just defensive programming, but in many places,
it was actually necessary to avoid confusing DECLARE CURSOR with SELECT.)
Because PlannedStmt carries a canSetTag field, we're also able to get rid
of some ad-hoc rules about how to reconstruct canSetTag for a bare utility
statement; specifically, the assumption that a utility is canSetTag if and
only if it's the only one in its list. While I see no near-term need for
relaxing that restriction, it's nice to get rid of the ad-hocery.
The API of ProcessUtility() is changed so that what it's passed is the
wrapper PlannedStmt not just the bare utility statement. This will affect
all users of ProcessUtility_hook, but the changes are pretty trivial; see
the affected contrib modules for examples of the minimum change needed.
(Most compilers should give pointer-type-mismatch warnings for uncorrected
code.)
There's also a change in the API of ExplainOneQuery_hook, to pass through
cursorOptions instead of expecting hook functions to know what to pick.
This is needed because of the DECLARE CURSOR changes, but really should
have been done in 9.6; it's unlikely that any extant hook functions
know about using CURSOR_OPT_PARALLEL_OK.
Finally, teach gram.y to save statement boundary locations in RawStmt
nodes, and pass those through to Query and PlannedStmt nodes. This allows
more intelligent handling of cases where a source query string contains
multiple statements. This patch doesn't actually do anything with the
information, but a follow-on patch will. (Passing this information through
cleanly is the true motivation for these changes; while I think this is all
good cleanup, it's unlikely we'd have bothered without this end goal.)
catversion bump because addition of location fields to struct Query
affects stored rules.
This patch is by me, but it owes a good deal to Fabien Coelho who did
a lot of preliminary work on the problem, and also reviewed the patch.
Discussion: https://postgr.es/m/alpine.DEB.2.20.1612200926310.29821@lancre
2017-01-14 22:02:35 +01:00
|
|
|
PlannedStmt *wrapper = makeNode(PlannedStmt);
|
2007-11-04 02:16:19 +01:00
|
|
|
|
|
|
|
ereport(NOTICE,
|
2007-11-04 22:25:55 +01:00
|
|
|
(errmsg("converting trigger group into constraint \"%s\" %s",
|
2007-11-05 20:00:25 +01:00
|
|
|
constr_name, buf.data),
|
2011-07-16 20:21:12 +02:00
|
|
|
errdetail_internal("%s", _(funcdescr[funcnum]))));
|
2009-07-30 04:45:38 +02:00
|
|
|
fkcon->contype = CONSTR_FOREIGN;
|
|
|
|
fkcon->location = -1;
|
2007-11-05 20:00:25 +01:00
|
|
|
if (funcnum == 2)
|
|
|
|
{
|
|
|
|
/* This trigger is on the FK table */
|
|
|
|
atstmt->relation = stmt->relation;
|
|
|
|
if (stmt->constrrel)
|
|
|
|
fkcon->pktable = stmt->constrrel;
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* Work around ancient pg_dump bug that omitted constrrel */
|
2008-09-01 22:42:46 +02:00
|
|
|
fkcon->pktable = makeRangeVar(NULL, pk_table_name, -1);
|
2007-11-05 20:00:25 +01:00
|
|
|
}
|
|
|
|
}
|
2007-11-04 22:25:55 +01:00
|
|
|
else
|
|
|
|
{
|
2007-11-05 20:00:25 +01:00
|
|
|
/* This trigger is on the PK table */
|
|
|
|
fkcon->pktable = stmt->relation;
|
|
|
|
if (stmt->constrrel)
|
|
|
|
atstmt->relation = stmt->constrrel;
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* Work around ancient pg_dump bug that omitted constrrel */
|
2008-09-01 22:42:46 +02:00
|
|
|
atstmt->relation = makeRangeVar(NULL, fk_table_name, -1);
|
2007-11-05 20:00:25 +01:00
|
|
|
}
|
2007-11-04 22:25:55 +01:00
|
|
|
}
|
2007-11-04 02:16:19 +01:00
|
|
|
atstmt->cmds = list_make1(atcmd);
|
|
|
|
atstmt->relkind = OBJECT_TABLE;
|
|
|
|
atcmd->subtype = AT_AddConstraint;
|
|
|
|
atcmd->def = (Node *) fkcon;
|
2007-11-04 22:25:55 +01:00
|
|
|
if (strcmp(constr_name, "<unnamed>") == 0)
|
2009-07-30 04:45:38 +02:00
|
|
|
fkcon->conname = NULL;
|
2007-11-04 02:16:19 +01:00
|
|
|
else
|
2009-07-30 04:45:38 +02:00
|
|
|
fkcon->conname = constr_name;
|
2007-11-04 22:25:55 +01:00
|
|
|
fkcon->fk_attrs = fk_attrs;
|
|
|
|
fkcon->pk_attrs = pk_attrs;
|
|
|
|
fkcon->fk_matchtype = fk_matchtype;
|
2007-11-05 20:00:25 +01:00
|
|
|
switch (info->funcoids[0])
|
2007-11-04 02:16:19 +01:00
|
|
|
{
|
|
|
|
case F_RI_FKEY_NOACTION_UPD:
|
|
|
|
fkcon->fk_upd_action = FKCONSTR_ACTION_NOACTION;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_CASCADE_UPD:
|
|
|
|
fkcon->fk_upd_action = FKCONSTR_ACTION_CASCADE;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_RESTRICT_UPD:
|
|
|
|
fkcon->fk_upd_action = FKCONSTR_ACTION_RESTRICT;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_SETNULL_UPD:
|
|
|
|
fkcon->fk_upd_action = FKCONSTR_ACTION_SETNULL;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_SETDEFAULT_UPD:
|
|
|
|
fkcon->fk_upd_action = FKCONSTR_ACTION_SETDEFAULT;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
/* can't get here because of earlier checks */
|
|
|
|
elog(ERROR, "confused about RI update function");
|
|
|
|
}
|
2007-11-05 20:00:25 +01:00
|
|
|
switch (info->funcoids[1])
|
2007-11-04 02:16:19 +01:00
|
|
|
{
|
|
|
|
case F_RI_FKEY_NOACTION_DEL:
|
|
|
|
fkcon->fk_del_action = FKCONSTR_ACTION_NOACTION;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_CASCADE_DEL:
|
|
|
|
fkcon->fk_del_action = FKCONSTR_ACTION_CASCADE;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_RESTRICT_DEL:
|
|
|
|
fkcon->fk_del_action = FKCONSTR_ACTION_RESTRICT;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_SETNULL_DEL:
|
|
|
|
fkcon->fk_del_action = FKCONSTR_ACTION_SETNULL;
|
|
|
|
break;
|
|
|
|
case F_RI_FKEY_SETDEFAULT_DEL:
|
|
|
|
fkcon->fk_del_action = FKCONSTR_ACTION_SETDEFAULT;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
/* can't get here because of earlier checks */
|
|
|
|
elog(ERROR, "confused about RI delete function");
|
|
|
|
}
|
|
|
|
fkcon->deferrable = stmt->deferrable;
|
|
|
|
fkcon->initdeferred = stmt->initdeferred;
|
2011-06-16 01:05:11 +02:00
|
|
|
fkcon->skip_validation = false;
|
|
|
|
fkcon->initially_valid = true;
|
2007-11-04 02:16:19 +01:00
|
|
|
|
Change representation of statement lists, and add statement location info.
This patch makes several changes that improve the consistency of
representation of lists of statements. It's always been the case
that the output of parse analysis is a list of Query nodes, whatever
the types of the individual statements in the list. This patch brings
similar consistency to the outputs of raw parsing and planning steps:
* The output of raw parsing is now always a list of RawStmt nodes;
the statement-type-dependent nodes are one level down from that.
* The output of pg_plan_queries() is now always a list of PlannedStmt
nodes, even for utility statements. In the case of a utility statement,
"planning" just consists of wrapping a CMD_UTILITY PlannedStmt around
the utility node. This list representation is now used in Portal and
CachedPlan plan lists, replacing the former convention of intermixing
PlannedStmts with bare utility-statement nodes.
Now, every list of statements has a consistent head-node type depending
on how far along it is in processing. This allows changing many places
that formerly used generic "Node *" pointers to use a more specific
pointer type, thus reducing the number of IsA() tests and casts needed,
as well as improving code clarity.
Also, the post-parse-analysis representation of DECLARE CURSOR is changed
so that it looks more like EXPLAIN, PREPARE, etc. That is, the contained
SELECT remains a child of the DeclareCursorStmt rather than getting flipped
around to be the other way. It's now true for both Query and PlannedStmt
that utilityStmt is non-null if and only if commandType is CMD_UTILITY.
That allows simplifying a lot of places that were testing both fields.
(I think some of those were just defensive programming, but in many places,
it was actually necessary to avoid confusing DECLARE CURSOR with SELECT.)
Because PlannedStmt carries a canSetTag field, we're also able to get rid
of some ad-hoc rules about how to reconstruct canSetTag for a bare utility
statement; specifically, the assumption that a utility is canSetTag if and
only if it's the only one in its list. While I see no near-term need for
relaxing that restriction, it's nice to get rid of the ad-hocery.
The API of ProcessUtility() is changed so that what it's passed is the
wrapper PlannedStmt not just the bare utility statement. This will affect
all users of ProcessUtility_hook, but the changes are pretty trivial; see
the affected contrib modules for examples of the minimum change needed.
(Most compilers should give pointer-type-mismatch warnings for uncorrected
code.)
There's also a change in the API of ExplainOneQuery_hook, to pass through
cursorOptions instead of expecting hook functions to know what to pick.
This is needed because of the DECLARE CURSOR changes, but really should
have been done in 9.6; it's unlikely that any extant hook functions
know about using CURSOR_OPT_PARALLEL_OK.
Finally, teach gram.y to save statement boundary locations in RawStmt
nodes, and pass those through to Query and PlannedStmt nodes. This allows
more intelligent handling of cases where a source query string contains
multiple statements. This patch doesn't actually do anything with the
information, but a follow-on patch will. (Passing this information through
cleanly is the true motivation for these changes; while I think this is all
good cleanup, it's unlikely we'd have bothered without this end goal.)
catversion bump because addition of location fields to struct Query
affects stored rules.
This patch is by me, but it owes a good deal to Fabien Coelho who did
a lot of preliminary work on the problem, and also reviewed the patch.
Discussion: https://postgr.es/m/alpine.DEB.2.20.1612200926310.29821@lancre
2017-01-14 22:02:35 +01:00
|
|
|
/* finally, wrap it in a dummy PlannedStmt */
|
|
|
|
wrapper->commandType = CMD_UTILITY;
|
|
|
|
wrapper->canSetTag = false;
|
|
|
|
wrapper->utilityStmt = (Node *) atstmt;
|
|
|
|
wrapper->stmt_location = -1;
|
|
|
|
wrapper->stmt_len = -1;
|
|
|
|
|
2007-11-04 22:25:55 +01:00
|
|
|
/* ... and execute it */
|
Change representation of statement lists, and add statement location info.
This patch makes several changes that improve the consistency of
representation of lists of statements. It's always been the case
that the output of parse analysis is a list of Query nodes, whatever
the types of the individual statements in the list. This patch brings
similar consistency to the outputs of raw parsing and planning steps:
* The output of raw parsing is now always a list of RawStmt nodes;
the statement-type-dependent nodes are one level down from that.
* The output of pg_plan_queries() is now always a list of PlannedStmt
nodes, even for utility statements. In the case of a utility statement,
"planning" just consists of wrapping a CMD_UTILITY PlannedStmt around
the utility node. This list representation is now used in Portal and
CachedPlan plan lists, replacing the former convention of intermixing
PlannedStmts with bare utility-statement nodes.
Now, every list of statements has a consistent head-node type depending
on how far along it is in processing. This allows changing many places
that formerly used generic "Node *" pointers to use a more specific
pointer type, thus reducing the number of IsA() tests and casts needed,
as well as improving code clarity.
Also, the post-parse-analysis representation of DECLARE CURSOR is changed
so that it looks more like EXPLAIN, PREPARE, etc. That is, the contained
SELECT remains a child of the DeclareCursorStmt rather than getting flipped
around to be the other way. It's now true for both Query and PlannedStmt
that utilityStmt is non-null if and only if commandType is CMD_UTILITY.
That allows simplifying a lot of places that were testing both fields.
(I think some of those were just defensive programming, but in many places,
it was actually necessary to avoid confusing DECLARE CURSOR with SELECT.)
Because PlannedStmt carries a canSetTag field, we're also able to get rid
of some ad-hoc rules about how to reconstruct canSetTag for a bare utility
statement; specifically, the assumption that a utility is canSetTag if and
only if it's the only one in its list. While I see no near-term need for
relaxing that restriction, it's nice to get rid of the ad-hocery.
The API of ProcessUtility() is changed so that what it's passed is the
wrapper PlannedStmt not just the bare utility statement. This will affect
all users of ProcessUtility_hook, but the changes are pretty trivial; see
the affected contrib modules for examples of the minimum change needed.
(Most compilers should give pointer-type-mismatch warnings for uncorrected
code.)
There's also a change in the API of ExplainOneQuery_hook, to pass through
cursorOptions instead of expecting hook functions to know what to pick.
This is needed because of the DECLARE CURSOR changes, but really should
have been done in 9.6; it's unlikely that any extant hook functions
know about using CURSOR_OPT_PARALLEL_OK.
Finally, teach gram.y to save statement boundary locations in RawStmt
nodes, and pass those through to Query and PlannedStmt nodes. This allows
more intelligent handling of cases where a source query string contains
multiple statements. This patch doesn't actually do anything with the
information, but a follow-on patch will. (Passing this information through
cleanly is the true motivation for these changes; while I think this is all
good cleanup, it's unlikely we'd have bothered without this end goal.)
catversion bump because addition of location fields to struct Query
affects stored rules.
This patch is by me, but it owes a good deal to Fabien Coelho who did
a lot of preliminary work on the problem, and also reviewed the patch.
Discussion: https://postgr.es/m/alpine.DEB.2.20.1612200926310.29821@lancre
2017-01-14 22:02:35 +01:00
|
|
|
ProcessUtility(wrapper,
|
Adjust things so that the query_string of a cached plan and the sourceText of
a portal are never NULL, but reliably provide the source text of the query.
It turns out that there was only one place that was really taking a short-cut,
which was the 'EXECUTE' utility statement. That doesn't seem like a
sufficiently critical performance hotspot to justify not offering a guarantee
of validity of the portal source text. Fix it to copy the source text over
from the cached plan. Add Asserts in the places that set up cached plans and
portals to reject null source strings, and simplify a bunch of places that
formerly needed to guard against nulls.
There may be a few places that cons up statements for execution without
having any source text at all; I found one such in ConvertTriggerToFK().
It seems sufficient to inject a phony source string in such a case,
for instance
ProcessUtility((Node *) atstmt,
"(generated ALTER TABLE ADD FOREIGN KEY command)",
NULL, false, None_Receiver, NULL);
We should take a second look at the usage of debug_query_string,
particularly the recently added current_query() SQL function.
ITAGAKI Takahiro and Tom Lane
2008-07-18 22:26:06 +02:00
|
|
|
"(generated ALTER TABLE ADD FOREIGN KEY command)",
|
2017-04-01 06:17:18 +02:00
|
|
|
PROCESS_UTILITY_SUBCOMMAND, NULL, NULL,
|
2013-04-28 06:18:45 +02:00
|
|
|
None_Receiver, NULL);
|
2007-11-04 02:16:19 +01:00
|
|
|
|
|
|
|
/* Remove the matched item from the list */
|
|
|
|
info_list = list_delete_ptr(info_list, info);
|
|
|
|
pfree(info);
|
|
|
|
/* We leak the copied args ... not worth worrying about */
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2002-07-12 20:43:19 +02:00
|
|
|
/*
|
|
|
|
* Guts of trigger deletion.
|
|
|
|
*/
|
|
|
|
void
|
|
|
|
RemoveTriggerById(Oid trigOid)
|
1997-08-31 13:40:13 +02:00
|
|
|
{
|
1997-09-08 04:41:22 +02:00
|
|
|
Relation tgrel;
|
2002-09-04 22:31:48 +02:00
|
|
|
SysScanDesc tgscan;
|
|
|
|
ScanKeyData skey[1];
|
2002-07-12 20:43:19 +02:00
|
|
|
HeapTuple tup;
|
|
|
|
Oid relid;
|
|
|
|
Relation rel;
|
|
|
|
|
2005-04-14 22:03:27 +02:00
|
|
|
tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Find the trigger to delete.
|
|
|
|
*/
|
2003-11-12 22:15:59 +01:00
|
|
|
ScanKeyInit(&skey[0],
|
|
|
|
ObjectIdAttributeNumber,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(trigOid));
|
2002-07-12 20:43:19 +02:00
|
|
|
|
2005-04-14 22:03:27 +02:00
|
|
|
tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 1, skey);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
|
|
|
tup = systable_getnext(tgscan);
|
|
|
|
if (!HeapTupleIsValid(tup))
|
2003-07-20 23:56:35 +02:00
|
|
|
elog(ERROR, "could not find tuple for trigger %u", trigOid);
|
2002-07-12 20:43:19 +02:00
|
|
|
|
|
|
|
/*
|
2011-07-07 19:14:46 +02:00
|
|
|
* Open and exclusive-lock the relation the trigger belongs to.
|
2002-07-12 20:43:19 +02:00
|
|
|
*/
|
|
|
|
relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
|
1998-09-01 06:40:42 +02:00
|
|
|
|
2011-07-07 19:14:46 +02:00
|
|
|
rel = heap_open(relid, AccessExclusiveLock);
|
2002-03-22 00:27:25 +01:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (rel->rd_rel->relkind != RELKIND_RELATION &&
|
2014-03-23 07:16:34 +01:00
|
|
|
rel->rd_rel->relkind != RELKIND_VIEW &&
|
Implement table partitioning.
Table partitioning is like table inheritance and reuses much of the
existing infrastructure, but there are some important differences.
The parent is called a partitioned table and is always empty; it may
not have indexes or non-inherited constraints, since those make no
sense for a relation with no data of its own. The children are called
partitions and contain all of the actual data. Each partition has an
implicit partitioning constraint. Multiple inheritance is not
allowed, and partitioning and inheritance can't be mixed. Partitions
can't have extra columns and may not allow nulls unless the parent
does. Tuples inserted into the parent are automatically routed to the
correct partition, so tuple-routing ON INSERT triggers are not needed.
Tuple routing isn't yet supported for partitions which are foreign
tables, and it doesn't handle updates that cross partition boundaries.
Currently, tables can be range-partitioned or list-partitioned. List
partitioning is limited to a single column, but range partitioning can
involve multiple columns. A partitioning "column" can be an
expression.
Because table partitioning is less general than table inheritance, it
is hoped that it will be easier to reason about properties of
partitions, and therefore that this will serve as a better foundation
for a variety of possible optimizations, including query planner
optimizations. The tuple routing based which this patch does based on
the implicit partitioning constraints is an example of this, but it
seems likely that many other useful optimizations are also possible.
Amit Langote, reviewed and tested by Robert Haas, Ashutosh Bapat,
Amit Kapila, Rajkumar Raghuwanshi, Corey Huinker, Jaime Casanova,
Rushabh Lathia, Erik Rijkers, among others. Minor revisions by me.
2016-12-07 19:17:43 +01:00
|
|
|
rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
|
|
|
|
rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
2014-03-23 07:16:34 +01:00
|
|
|
errmsg("\"%s\" is not a table, view, or foreign table",
|
2003-07-20 23:56:35 +02:00
|
|
|
RelationGetRelationName(rel))));
|
2002-03-22 00:27:25 +01:00
|
|
|
|
2002-04-12 22:38:31 +02:00
|
|
|
if (!allowSystemTableMods && IsSystemRelation(rel))
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
2003-08-01 02:15:26 +02:00
|
|
|
errmsg("permission denied: \"%s\" is a system catalog",
|
2003-07-20 23:56:35 +02:00
|
|
|
RelationGetRelationName(rel))));
|
2002-01-04 00:21:32 +01:00
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
2002-07-12 20:43:19 +02:00
|
|
|
* Delete the pg_trigger tuple.
|
2000-07-03 05:57:03 +02:00
|
|
|
*/
|
2017-02-01 22:13:30 +01:00
|
|
|
CatalogTupleDelete(tgrel, &tup->t_self);
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2002-02-19 21:11:20 +01:00
|
|
|
systable_endscan(tgscan);
|
|
|
|
heap_close(tgrel, RowExclusiveLock);
|
|
|
|
|
2000-07-03 05:57:03 +02:00
|
|
|
/*
|
2008-11-09 22:24:33 +01:00
|
|
|
* We do not bother to try to determine whether any other triggers remain,
|
2009-06-11 16:49:15 +02:00
|
|
|
* which would be needed in order to decide whether it's safe to clear the
|
|
|
|
* relation's relhastriggers. (In any case, there might be a concurrent
|
|
|
|
* process adding new triggers.) Instead, just force a relcache inval to
|
|
|
|
* make other backends (and this one too!) rebuild their relcache entries.
|
|
|
|
* There's no great harm in leaving relhastriggers true even if there are
|
|
|
|
* no triggers left.
|
2000-07-03 05:57:03 +02:00
|
|
|
*/
|
2008-11-09 22:24:33 +01:00
|
|
|
CacheInvalidateRelcache(rel);
|
2000-04-12 19:17:23 +02:00
|
|
|
|
2002-07-12 20:43:19 +02:00
|
|
|
/* Keep lock on trigger's rel until end of xact */
|
1999-09-18 21:08:25 +02:00
|
|
|
heap_close(rel, NoLock);
|
1997-08-31 13:40:13 +02:00
|
|
|
}
|
1997-09-01 09:59:06 +02:00
|
|
|
|
2010-08-05 17:25:36 +02:00
|
|
|
/*
|
|
|
|
* get_trigger_oid - Look up a trigger by name to find its OID.
|
|
|
|
*
|
|
|
|
* If missing_ok is false, throw an error if trigger not found. If
|
|
|
|
* true, just return InvalidOid.
|
|
|
|
*/
|
|
|
|
Oid
|
|
|
|
get_trigger_oid(Oid relid, const char *trigname, bool missing_ok)
|
|
|
|
{
|
|
|
|
Relation tgrel;
|
|
|
|
ScanKeyData skey[2];
|
|
|
|
SysScanDesc tgscan;
|
|
|
|
HeapTuple tup;
|
|
|
|
Oid oid;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Find the trigger, verify permissions, set up object address
|
|
|
|
*/
|
|
|
|
tgrel = heap_open(TriggerRelationId, AccessShareLock);
|
|
|
|
|
|
|
|
ScanKeyInit(&skey[0],
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(relid));
|
|
|
|
ScanKeyInit(&skey[1],
|
|
|
|
Anum_pg_trigger_tgname,
|
|
|
|
BTEqualStrategyNumber, F_NAMEEQ,
|
|
|
|
CStringGetDatum(trigname));
|
|
|
|
|
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 2, skey);
|
2010-08-05 17:25:36 +02:00
|
|
|
|
|
|
|
tup = systable_getnext(tgscan);
|
|
|
|
|
|
|
|
if (!HeapTupleIsValid(tup))
|
|
|
|
{
|
|
|
|
if (!missing_ok)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
|
|
|
errmsg("trigger \"%s\" for table \"%s\" does not exist",
|
|
|
|
trigname, get_rel_name(relid))));
|
|
|
|
oid = InvalidOid;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
oid = HeapTupleGetOid(tup);
|
|
|
|
}
|
|
|
|
|
|
|
|
systable_endscan(tgscan);
|
|
|
|
heap_close(tgrel, AccessShareLock);
|
|
|
|
return oid;
|
|
|
|
}
|
|
|
|
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
/*
|
|
|
|
* Perform permissions and integrity checks before acquiring a relation lock.
|
|
|
|
*/
|
|
|
|
static void
|
|
|
|
RangeVarCallbackForRenameTrigger(const RangeVar *rv, Oid relid, Oid oldrelid,
|
|
|
|
void *arg)
|
|
|
|
{
|
2012-06-10 21:20:04 +02:00
|
|
|
HeapTuple tuple;
|
|
|
|
Form_pg_class form;
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
|
|
|
|
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
|
|
|
|
if (!HeapTupleIsValid(tuple))
|
2012-06-10 21:20:04 +02:00
|
|
|
return; /* concurrently dropped */
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
form = (Form_pg_class) GETSTRUCT(tuple);
|
|
|
|
|
|
|
|
/* only tables and views can have triggers */
|
2014-03-23 07:16:34 +01:00
|
|
|
if (form->relkind != RELKIND_RELATION && form->relkind != RELKIND_VIEW &&
|
Implement table partitioning.
Table partitioning is like table inheritance and reuses much of the
existing infrastructure, but there are some important differences.
The parent is called a partitioned table and is always empty; it may
not have indexes or non-inherited constraints, since those make no
sense for a relation with no data of its own. The children are called
partitions and contain all of the actual data. Each partition has an
implicit partitioning constraint. Multiple inheritance is not
allowed, and partitioning and inheritance can't be mixed. Partitions
can't have extra columns and may not allow nulls unless the parent
does. Tuples inserted into the parent are automatically routed to the
correct partition, so tuple-routing ON INSERT triggers are not needed.
Tuple routing isn't yet supported for partitions which are foreign
tables, and it doesn't handle updates that cross partition boundaries.
Currently, tables can be range-partitioned or list-partitioned. List
partitioning is limited to a single column, but range partitioning can
involve multiple columns. A partitioning "column" can be an
expression.
Because table partitioning is less general than table inheritance, it
is hoped that it will be easier to reason about properties of
partitions, and therefore that this will serve as a better foundation
for a variety of possible optimizations, including query planner
optimizations. The tuple routing based which this patch does based on
the implicit partitioning constraints is an example of this, but it
seems likely that many other useful optimizations are also possible.
Amit Langote, reviewed and tested by Robert Haas, Ashutosh Bapat,
Amit Kapila, Rajkumar Raghuwanshi, Corey Huinker, Jaime Casanova,
Rushabh Lathia, Erik Rijkers, among others. Minor revisions by me.
2016-12-07 19:17:43 +01:00
|
|
|
form->relkind != RELKIND_FOREIGN_TABLE &&
|
|
|
|
form->relkind != RELKIND_PARTITIONED_TABLE)
|
2012-06-10 21:20:04 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
2014-03-23 07:16:34 +01:00
|
|
|
errmsg("\"%s\" is not a table, view, or foreign table",
|
|
|
|
rv->relname)));
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
|
|
|
|
/* you must own the table to rename one of its triggers */
|
2012-06-10 21:20:04 +02:00
|
|
|
if (!pg_class_ownercheck(relid, GetUserId()))
|
|
|
|
aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS, rv->relname);
|
Refine our definition of what constitutes a system relation.
Although user-defined relations can't be directly created in
pg_catalog, it's possible for them to end up there, because you can
create them in some other schema and then use ALTER TABLE .. SET SCHEMA
to move them there. Previously, such relations couldn't afterwards
be manipulated, because IsSystemRelation()/IsSystemClass() rejected
all attempts to modify objects in the pg_catalog schema, regardless
of their origin. With this patch, they now reject only those
objects in pg_catalog which were created at initdb-time, allowing
most operations on user-created tables in pg_catalog to proceed
normally.
This patch also adds new functions IsCatalogRelation() and
IsCatalogClass(), which is similar to IsSystemRelation() and
IsSystemClass() but with a slightly narrower definition: only TOAST
tables of system catalogs are included, rather than *all* TOAST tables.
This is currently used only for making decisions about when
invalidation messages need to be sent, but upcoming logical decoding
patches will find other uses for this information.
Andres Freund, with some modifications by me.
2013-11-29 02:57:20 +01:00
|
|
|
if (!allowSystemTableMods && IsSystemClass(relid, form))
|
2012-06-10 21:20:04 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
|
|
|
errmsg("permission denied: \"%s\" is a system catalog",
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
rv->relname)));
|
|
|
|
|
|
|
|
ReleaseSysCache(tuple);
|
|
|
|
}
|
|
|
|
|
2002-04-26 21:29:47 +02:00
|
|
|
/*
|
|
|
|
* renametrig - changes the name of a trigger on a relation
|
|
|
|
*
|
|
|
|
* trigger name is changed in trigger catalog.
|
|
|
|
* No record of the previous name is kept.
|
|
|
|
*
|
|
|
|
* get proper relrelation from relation catalog (if not arg)
|
|
|
|
* scan trigger catalog
|
|
|
|
* for name conflict (within rel)
|
|
|
|
* for original trigger (if not arg)
|
|
|
|
* modify tgname in trigger tuple
|
2002-04-30 03:24:57 +02:00
|
|
|
* update row in catalog
|
2002-04-26 21:29:47 +02:00
|
|
|
*/
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
ObjectAddress
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
renametrig(RenameStmt *stmt)
|
2002-04-26 21:29:47 +02:00
|
|
|
{
|
2012-12-24 00:25:03 +01:00
|
|
|
Oid tgoid;
|
2002-04-26 21:29:47 +02:00
|
|
|
Relation targetrel;
|
|
|
|
Relation tgrel;
|
|
|
|
HeapTuple tuple;
|
2002-09-04 22:31:48 +02:00
|
|
|
SysScanDesc tgscan;
|
2002-04-30 03:24:57 +02:00
|
|
|
ScanKeyData key[2];
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
Oid relid;
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
ObjectAddress address;
|
2002-04-26 21:29:47 +02:00
|
|
|
|
|
|
|
/*
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
* Look up name, check permissions, and acquire lock (which we will NOT
|
|
|
|
* release until end of transaction).
|
2002-04-26 21:29:47 +02:00
|
|
|
*/
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
|
|
|
|
false, false,
|
|
|
|
RangeVarCallbackForRenameTrigger,
|
|
|
|
NULL);
|
|
|
|
|
|
|
|
/* Have lock already, so just need to build relcache entry. */
|
|
|
|
targetrel = relation_open(relid, NoLock);
|
2002-04-26 21:29:47 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Scan pg_trigger twice for existing triggers on relation. We do this in
|
|
|
|
* order to ensure a trigger does not exist with newname (The unique index
|
|
|
|
* on tgrelid/tgname would complain anyway) and to ensure a trigger does
|
|
|
|
* exist with oldname.
|
2002-04-26 21:29:47 +02:00
|
|
|
*
|
|
|
|
* NOTE that this is cool only because we have AccessExclusiveLock on the
|
|
|
|
* relation, so the trigger set won't be changing underneath us.
|
|
|
|
*/
|
2005-04-14 22:03:27 +02:00
|
|
|
tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
|
2002-04-26 21:29:47 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* First pass -- look for name conflict
|
|
|
|
*/
|
2003-11-12 22:15:59 +01:00
|
|
|
ScanKeyInit(&key[0],
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(relid));
|
|
|
|
ScanKeyInit(&key[1],
|
|
|
|
Anum_pg_trigger_tgname,
|
|
|
|
BTEqualStrategyNumber, F_NAMEEQ,
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
PointerGetDatum(stmt->newname));
|
2005-04-14 22:03:27 +02:00
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 2, key);
|
2002-04-30 03:24:57 +02:00
|
|
|
if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_DUPLICATE_OBJECT),
|
2005-10-15 04:49:52 +02:00
|
|
|
errmsg("trigger \"%s\" for relation \"%s\" already exists",
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
stmt->newname, RelationGetRelationName(targetrel))));
|
2002-04-26 21:29:47 +02:00
|
|
|
systable_endscan(tgscan);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Second pass -- look for trigger existing with oldname and update
|
|
|
|
*/
|
2003-11-12 22:15:59 +01:00
|
|
|
ScanKeyInit(&key[0],
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(relid));
|
|
|
|
ScanKeyInit(&key[1],
|
|
|
|
Anum_pg_trigger_tgname,
|
|
|
|
BTEqualStrategyNumber, F_NAMEEQ,
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
PointerGetDatum(stmt->subname));
|
2005-04-14 22:03:27 +02:00
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 2, key);
|
2002-04-30 03:24:57 +02:00
|
|
|
if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
|
2002-04-26 21:29:47 +02:00
|
|
|
{
|
2012-12-24 00:25:03 +01:00
|
|
|
tgoid = HeapTupleGetOid(tuple);
|
2013-05-29 22:58:43 +02:00
|
|
|
|
2002-04-30 03:24:57 +02:00
|
|
|
/*
|
|
|
|
* Update pg_trigger tuple with new tgname.
|
|
|
|
*/
|
2002-09-04 22:31:48 +02:00
|
|
|
tuple = heap_copytuple(tuple); /* need a modifiable copy */
|
2002-04-26 21:29:47 +02:00
|
|
|
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
namestrcpy(&((Form_pg_trigger) GETSTRUCT(tuple))->tgname,
|
|
|
|
stmt->newname);
|
2002-04-26 21:29:47 +02:00
|
|
|
|
2017-01-31 22:42:24 +01:00
|
|
|
CatalogTupleUpdate(tgrel, &tuple->t_self, tuple);
|
2002-04-26 21:29:47 +02:00
|
|
|
|
2013-03-18 03:55:14 +01:00
|
|
|
InvokeObjectPostAlterHook(TriggerRelationId,
|
|
|
|
HeapTupleGetOid(tuple), 0);
|
|
|
|
|
2002-04-30 03:24:57 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Invalidate relation's relcache entry so that other backends (and
|
|
|
|
* this one too!) are sent SI message to make them rebuild relcache
|
|
|
|
* entries. (Ideally this should happen automatically...)
|
2002-04-30 03:24:57 +02:00
|
|
|
*/
|
2004-02-10 02:55:27 +01:00
|
|
|
CacheInvalidateRelcache(targetrel);
|
2002-04-30 03:24:57 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
2004-08-29 07:07:03 +02:00
|
|
|
errmsg("trigger \"%s\" for table \"%s\" does not exist",
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
stmt->subname, RelationGetRelationName(targetrel))));
|
2002-04-30 03:24:57 +02:00
|
|
|
}
|
|
|
|
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
ObjectAddressSet(address, TriggerRelationId, tgoid);
|
|
|
|
|
2002-04-30 03:24:57 +02:00
|
|
|
systable_endscan(tgscan);
|
|
|
|
|
|
|
|
heap_close(tgrel, RowExclusiveLock);
|
2002-04-26 21:29:47 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Close rel, but keep exclusive lock!
|
|
|
|
*/
|
Improve behavior of concurrent rename statements.
Previously, renaming a table, sequence, view, index, foreign table,
column, or trigger checked permissions before locking the object, which
meant that if permissions were revoked during the lock wait, we would
still allow the operation. Similarly, if the original object is dropped
and a new one with the same name is created, the operation will be allowed
if we had permissions on the old object; the permissions on the new
object don't matter. All this is now fixed.
Along the way, attempting to rename a trigger on a foreign table now gives
the same error message as trying to create one there in the first place
(i.e. that it's not a table or view) rather than simply stating that no
trigger by that name exists.
Patch by me; review by Noah Misch.
2011-12-16 00:51:46 +01:00
|
|
|
relation_close(targetrel, NoLock);
|
2012-12-24 00:25:03 +01:00
|
|
|
|
Change many routines to return ObjectAddress rather than OID
The changed routines are mostly those that can be directly called by
ProcessUtilitySlow; the intention is to make the affected object
information more precise, in support for future event trigger changes.
Originally it was envisioned that the OID of the affected object would
be enough, and in most cases that is correct, but upon actually
implementing the event trigger changes it turned out that ObjectAddress
is more widely useful.
Additionally, some command execution routines grew an output argument
that's an object address which provides further info about the executed
command. To wit:
* for ALTER DOMAIN / ADD CONSTRAINT, it corresponds to the address of
the new constraint
* for ALTER OBJECT / SET SCHEMA, it corresponds to the address of the
schema that originally contained the object.
* for ALTER EXTENSION {ADD, DROP} OBJECT, it corresponds to the address
of the object added to or dropped from the extension.
There's no user-visible change in this commit, and no functional change
either.
Discussion: 20150218213255.GC6717@tamriel.snowman.net
Reviewed-By: Stephen Frost, Andres Freund
2015-03-03 18:10:50 +01:00
|
|
|
return address;
|
2002-04-26 21:29:47 +02:00
|
|
|
}
|
|
|
|
|
2005-08-24 00:40:47 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* EnableDisableTrigger()
|
|
|
|
*
|
2009-01-22 20:16:31 +01:00
|
|
|
* Called by ALTER TABLE ENABLE/DISABLE [ REPLICA | ALWAYS ] TRIGGER
|
2007-03-20 00:38:32 +01:00
|
|
|
* to change 'tgenabled' field for the specified trigger(s)
|
2005-08-24 00:40:47 +02:00
|
|
|
*
|
|
|
|
* rel: relation to process (caller must hold suitable lock on it)
|
|
|
|
* tgname: trigger to process, or NULL to scan all triggers
|
2009-01-22 20:16:31 +01:00
|
|
|
* fires_when: new value for tgenabled field. In addition to generic
|
|
|
|
* enablement/disablement, this also defines when the trigger
|
|
|
|
* should be fired in session replication roles.
|
2005-08-24 00:40:47 +02:00
|
|
|
* skip_system: if true, skip "system" triggers (constraint triggers)
|
|
|
|
*
|
|
|
|
* Caller should have checked permissions for the table; here we also
|
|
|
|
* enforce that superuser privilege is required to alter the state of
|
|
|
|
* system triggers
|
|
|
|
*/
|
|
|
|
void
|
|
|
|
EnableDisableTrigger(Relation rel, const char *tgname,
|
2007-03-20 00:38:32 +01:00
|
|
|
char fires_when, bool skip_system)
|
2005-08-24 00:40:47 +02:00
|
|
|
{
|
2005-10-15 04:49:52 +02:00
|
|
|
Relation tgrel;
|
|
|
|
int nkeys;
|
2005-08-24 00:40:47 +02:00
|
|
|
ScanKeyData keys[2];
|
|
|
|
SysScanDesc tgscan;
|
2005-10-15 04:49:52 +02:00
|
|
|
HeapTuple tuple;
|
|
|
|
bool found;
|
|
|
|
bool changed;
|
2005-08-24 00:40:47 +02:00
|
|
|
|
|
|
|
/* Scan the relevant entries in pg_triggers */
|
|
|
|
tgrel = heap_open(TriggerRelationId, RowExclusiveLock);
|
|
|
|
|
|
|
|
ScanKeyInit(&keys[0],
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(RelationGetRelid(rel)));
|
|
|
|
if (tgname)
|
|
|
|
{
|
|
|
|
ScanKeyInit(&keys[1],
|
|
|
|
Anum_pg_trigger_tgname,
|
|
|
|
BTEqualStrategyNumber, F_NAMEEQ,
|
|
|
|
CStringGetDatum(tgname));
|
|
|
|
nkeys = 2;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
nkeys = 1;
|
|
|
|
|
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, nkeys, keys);
|
2005-08-24 00:40:47 +02:00
|
|
|
|
|
|
|
found = changed = false;
|
|
|
|
|
|
|
|
while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
|
|
|
|
{
|
|
|
|
Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
|
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
if (oldtrig->tgisinternal)
|
2005-08-24 00:40:47 +02:00
|
|
|
{
|
|
|
|
/* system trigger ... ok to process? */
|
|
|
|
if (skip_system)
|
|
|
|
continue;
|
|
|
|
if (!superuser())
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
|
2005-10-15 04:49:52 +02:00
|
|
|
errmsg("permission denied: \"%s\" is a system trigger",
|
|
|
|
NameStr(oldtrig->tgname))));
|
2005-08-24 00:40:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
found = true;
|
|
|
|
|
2007-03-20 00:38:32 +01:00
|
|
|
if (oldtrig->tgenabled != fires_when)
|
2005-08-24 00:40:47 +02:00
|
|
|
{
|
|
|
|
/* need to change this one ... make a copy to scribble on */
|
2005-10-15 04:49:52 +02:00
|
|
|
HeapTuple newtup = heap_copytuple(tuple);
|
2005-08-24 00:40:47 +02:00
|
|
|
Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
|
|
|
|
|
2007-03-20 00:38:32 +01:00
|
|
|
newtrig->tgenabled = fires_when;
|
2005-08-24 00:40:47 +02:00
|
|
|
|
2017-01-31 22:42:24 +01:00
|
|
|
CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
|
2005-08-24 00:40:47 +02:00
|
|
|
|
|
|
|
heap_freetuple(newtup);
|
|
|
|
|
|
|
|
changed = true;
|
|
|
|
}
|
2013-03-18 03:55:14 +01:00
|
|
|
|
|
|
|
InvokeObjectPostAlterHook(TriggerRelationId,
|
|
|
|
HeapTupleGetOid(tuple), 0);
|
2005-08-24 00:40:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
systable_endscan(tgscan);
|
|
|
|
|
|
|
|
heap_close(tgrel, RowExclusiveLock);
|
|
|
|
|
|
|
|
if (tgname && !found)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
|
|
|
errmsg("trigger \"%s\" for table \"%s\" does not exist",
|
|
|
|
tgname, RelationGetRelationName(rel))));
|
|
|
|
|
|
|
|
/*
|
|
|
|
* If we changed anything, broadcast a SI inval message to force each
|
|
|
|
* backend (including our own!) to rebuild relation's relcache entry.
|
|
|
|
* Otherwise they will fail to apply the change promptly.
|
|
|
|
*/
|
|
|
|
if (changed)
|
|
|
|
CacheInvalidateRelcache(rel);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2000-06-30 09:04:23 +02:00
|
|
|
/*
|
|
|
|
* Build trigger data to attach to the given relcache entry.
|
|
|
|
*
|
2002-10-14 18:51:30 +02:00
|
|
|
* Note that trigger data attached to a relcache entry must be stored in
|
|
|
|
* CacheMemoryContext to ensure it survives as long as the relcache entry.
|
|
|
|
* But we should be running in a less long-lived working context. To avoid
|
|
|
|
* leaking cache memory if this routine fails partway through, we build a
|
|
|
|
* temporary TriggerDesc in working memory and then copy the completed
|
|
|
|
* structure into cache memory.
|
2000-06-30 09:04:23 +02:00
|
|
|
*/
|
1997-09-01 09:59:06 +02:00
|
|
|
void
|
1997-09-07 07:04:48 +02:00
|
|
|
RelationBuildTriggers(Relation relation)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2000-06-30 09:04:23 +02:00
|
|
|
TriggerDesc *trigdesc;
|
2008-11-09 22:24:33 +01:00
|
|
|
int numtrigs;
|
|
|
|
int maxtrigs;
|
2002-04-19 18:36:08 +02:00
|
|
|
Trigger *triggers;
|
1997-09-08 04:41:22 +02:00
|
|
|
Relation tgrel;
|
|
|
|
ScanKeyData skey;
|
2002-09-04 22:31:48 +02:00
|
|
|
SysScanDesc tgscan;
|
2000-02-18 10:30:20 +01:00
|
|
|
HeapTuple htup;
|
2002-10-14 18:51:30 +02:00
|
|
|
MemoryContext oldContext;
|
2008-11-09 22:24:33 +01:00
|
|
|
int i;
|
2002-10-14 18:51:30 +02:00
|
|
|
|
2008-11-09 22:24:33 +01:00
|
|
|
/*
|
2009-06-11 16:49:15 +02:00
|
|
|
* Allocate a working array to hold the triggers (the array is extended if
|
|
|
|
* necessary)
|
2008-11-09 22:24:33 +01:00
|
|
|
*/
|
|
|
|
maxtrigs = 16;
|
|
|
|
triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
|
|
|
|
numtrigs = 0;
|
2002-04-19 18:36:08 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Note: since we scan the triggers using TriggerRelidNameIndexId, we will
|
|
|
|
* be reading the triggers in name order, except possibly during
|
2006-10-04 02:30:14 +02:00
|
|
|
* emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
|
|
|
|
* ensures that triggers will be fired in name order.
|
2002-04-19 18:36:08 +02:00
|
|
|
*/
|
2003-11-12 22:15:59 +01:00
|
|
|
ScanKeyInit(&skey,
|
|
|
|
Anum_pg_trigger_tgrelid,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(RelationGetRelid(relation)));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2005-04-14 22:03:27 +02:00
|
|
|
tgrel = heap_open(TriggerRelationId, AccessShareLock);
|
|
|
|
tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 1, &skey);
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2002-02-19 21:11:20 +01:00
|
|
|
while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
|
1997-09-07 07:04:48 +02:00
|
|
|
{
|
2002-02-19 21:11:20 +01:00
|
|
|
Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
|
|
|
|
Trigger *build;
|
2009-11-20 21:38:12 +01:00
|
|
|
Datum datum;
|
|
|
|
bool isnull;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2008-11-09 22:24:33 +01:00
|
|
|
if (numtrigs >= maxtrigs)
|
|
|
|
{
|
|
|
|
maxtrigs *= 2;
|
|
|
|
triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
|
|
|
|
}
|
|
|
|
build = &(triggers[numtrigs]);
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2002-07-20 07:16:59 +02:00
|
|
|
build->tgoid = HeapTupleGetOid(htup);
|
2002-10-14 18:51:30 +02:00
|
|
|
build->tgname = DatumGetCString(DirectFunctionCall1(nameout,
|
2005-10-15 04:49:52 +02:00
|
|
|
NameGetDatum(&pg_trigger->tgname)));
|
1997-09-07 07:04:48 +02:00
|
|
|
build->tgfoid = pg_trigger->tgfoid;
|
|
|
|
build->tgtype = pg_trigger->tgtype;
|
1999-09-29 18:06:40 +02:00
|
|
|
build->tgenabled = pg_trigger->tgenabled;
|
2010-01-17 23:56:23 +01:00
|
|
|
build->tgisinternal = pg_trigger->tgisinternal;
|
2002-04-02 00:36:13 +02:00
|
|
|
build->tgconstrrelid = pg_trigger->tgconstrrelid;
|
2009-07-28 04:56:31 +02:00
|
|
|
build->tgconstrindid = pg_trigger->tgconstrindid;
|
2007-02-14 02:58:58 +01:00
|
|
|
build->tgconstraint = pg_trigger->tgconstraint;
|
1999-09-29 18:06:40 +02:00
|
|
|
build->tgdeferrable = pg_trigger->tgdeferrable;
|
|
|
|
build->tginitdeferred = pg_trigger->tginitdeferred;
|
1997-09-07 07:04:48 +02:00
|
|
|
build->tgnargs = pg_trigger->tgnargs;
|
2005-03-29 02:17:27 +02:00
|
|
|
/* tgattr is first var-width field, so OK to access directly */
|
|
|
|
build->tgnattr = pg_trigger->tgattr.dim1;
|
|
|
|
if (build->tgnattr > 0)
|
|
|
|
{
|
2012-06-25 00:51:46 +02:00
|
|
|
build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
|
2005-03-29 02:17:27 +02:00
|
|
|
memcpy(build->tgattr, &(pg_trigger->tgattr.values),
|
2012-06-25 00:51:46 +02:00
|
|
|
build->tgnattr * sizeof(int16));
|
2005-03-29 02:17:27 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
build->tgattr = NULL;
|
1997-09-07 07:04:48 +02:00
|
|
|
if (build->tgnargs > 0)
|
|
|
|
{
|
2002-08-25 19:20:01 +02:00
|
|
|
bytea *val;
|
1997-09-08 04:41:22 +02:00
|
|
|
char *p;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2017-03-13 00:35:34 +01:00
|
|
|
val = DatumGetByteaPP(fastgetattr(htup,
|
|
|
|
Anum_pg_trigger_tgargs,
|
|
|
|
tgrel->rd_att, &isnull));
|
1997-09-07 07:04:48 +02:00
|
|
|
if (isnull)
|
2003-07-20 23:56:35 +02:00
|
|
|
elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
|
2000-01-31 05:35:57 +01:00
|
|
|
RelationGetRelationName(relation));
|
2017-03-13 00:35:34 +01:00
|
|
|
p = (char *) VARDATA_ANY(val);
|
2002-10-14 18:51:30 +02:00
|
|
|
build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
|
1997-09-07 07:04:48 +02:00
|
|
|
for (i = 0; i < build->tgnargs; i++)
|
|
|
|
{
|
2002-10-14 18:51:30 +02:00
|
|
|
build->tgargs[i] = pstrdup(p);
|
1997-09-07 07:04:48 +02:00
|
|
|
p += strlen(p) + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
build->tgargs = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
|
|
|
|
datum = fastgetattr(htup, Anum_pg_trigger_tgoldtable,
|
|
|
|
tgrel->rd_att, &isnull);
|
|
|
|
if (!isnull)
|
|
|
|
build->tgoldtable =
|
|
|
|
DatumGetCString(DirectFunctionCall1(nameout, datum));
|
|
|
|
else
|
|
|
|
build->tgoldtable = NULL;
|
|
|
|
|
|
|
|
datum = fastgetattr(htup, Anum_pg_trigger_tgnewtable,
|
|
|
|
tgrel->rd_att, &isnull);
|
|
|
|
if (!isnull)
|
|
|
|
build->tgnewtable =
|
|
|
|
DatumGetCString(DirectFunctionCall1(nameout, datum));
|
|
|
|
else
|
|
|
|
build->tgnewtable = NULL;
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
|
|
|
|
tgrel->rd_att, &isnull);
|
|
|
|
if (!isnull)
|
|
|
|
build->tgqual = TextDatumGetCString(datum);
|
|
|
|
else
|
|
|
|
build->tgqual = NULL;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2008-11-09 22:24:33 +01:00
|
|
|
numtrigs++;
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
|
|
|
|
2002-02-19 21:11:20 +01:00
|
|
|
systable_endscan(tgscan);
|
|
|
|
heap_close(tgrel, AccessShareLock);
|
|
|
|
|
2008-11-09 22:24:33 +01:00
|
|
|
/* There might not be any triggers */
|
|
|
|
if (numtrigs == 0)
|
|
|
|
{
|
|
|
|
pfree(triggers);
|
|
|
|
return;
|
|
|
|
}
|
1997-09-07 07:04:48 +02:00
|
|
|
|
|
|
|
/* Build trigdesc */
|
2002-11-13 01:39:48 +01:00
|
|
|
trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
|
1997-09-07 07:04:48 +02:00
|
|
|
trigdesc->triggers = triggers;
|
2008-11-09 22:24:33 +01:00
|
|
|
trigdesc->numtriggers = numtrigs;
|
|
|
|
for (i = 0; i < numtrigs; i++)
|
2010-10-10 19:43:33 +02:00
|
|
|
SetTriggerFlags(trigdesc, &(triggers[i]));
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2002-10-14 18:51:30 +02:00
|
|
|
/* Copy completed trigdesc into cache storage */
|
|
|
|
oldContext = MemoryContextSwitchTo(CacheMemoryContext);
|
|
|
|
relation->trigdesc = CopyTriggerDesc(trigdesc);
|
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
|
|
|
|
/* Release working memory */
|
|
|
|
FreeTriggerDesc(trigdesc);
|
1997-09-04 15:19:01 +02:00
|
|
|
}
|
|
|
|
|
2002-10-14 18:51:30 +02:00
|
|
|
/*
|
2010-10-10 19:43:33 +02:00
|
|
|
* Update the TriggerDesc's hint flags to include the specified trigger
|
2002-10-14 18:51:30 +02:00
|
|
|
*/
|
1997-09-04 15:19:01 +02:00
|
|
|
static void
|
2010-10-10 19:43:33 +02:00
|
|
|
SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger)
|
1997-09-04 15:19:01 +02:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
int16 tgtype = trigger->tgtype;
|
|
|
|
|
|
|
|
trigdesc->trig_insert_before_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
|
|
|
|
trigdesc->trig_insert_after_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
|
|
|
|
trigdesc->trig_insert_instead_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_INSERT);
|
|
|
|
trigdesc->trig_insert_before_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
|
|
|
|
trigdesc->trig_insert_after_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
|
|
|
|
trigdesc->trig_update_before_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
|
|
|
|
trigdesc->trig_update_after_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
|
|
|
|
trigdesc->trig_update_instead_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_UPDATE);
|
|
|
|
trigdesc->trig_update_before_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
|
|
|
|
trigdesc->trig_update_after_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
|
|
|
|
trigdesc->trig_delete_before_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
|
|
|
|
trigdesc->trig_delete_after_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
|
|
|
|
trigdesc->trig_delete_instead_row |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_DELETE);
|
|
|
|
trigdesc->trig_delete_before_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
|
|
|
|
trigdesc->trig_delete_after_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
|
|
|
|
/* there are no row-level truncate triggers */
|
|
|
|
trigdesc->trig_truncate_before_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_TRUNCATE);
|
|
|
|
trigdesc->trig_truncate_after_statement |=
|
|
|
|
TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_AFTER, TRIGGER_TYPE_TRUNCATE);
|
2016-11-04 16:49:50 +01:00
|
|
|
|
|
|
|
trigdesc->trig_insert_new_table |=
|
|
|
|
(TRIGGER_FOR_INSERT(tgtype) &&
|
|
|
|
TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
|
|
|
|
trigdesc->trig_update_old_table |=
|
|
|
|
(TRIGGER_FOR_UPDATE(tgtype) &&
|
|
|
|
TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
|
|
|
|
trigdesc->trig_update_new_table |=
|
|
|
|
(TRIGGER_FOR_UPDATE(tgtype) &&
|
|
|
|
TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
|
|
|
|
trigdesc->trig_delete_old_table |=
|
|
|
|
(TRIGGER_FOR_DELETE(tgtype) &&
|
|
|
|
TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
2002-10-14 18:51:30 +02:00
|
|
|
/*
|
|
|
|
* Copy a TriggerDesc data structure.
|
|
|
|
*
|
|
|
|
* The copy is allocated in the current memory context.
|
|
|
|
*/
|
|
|
|
TriggerDesc *
|
|
|
|
CopyTriggerDesc(TriggerDesc *trigdesc)
|
|
|
|
{
|
|
|
|
TriggerDesc *newdesc;
|
|
|
|
Trigger *trigger;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
if (trigdesc == NULL || trigdesc->numtriggers <= 0)
|
|
|
|
return NULL;
|
|
|
|
|
|
|
|
newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
|
|
|
|
memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
|
|
|
|
|
|
|
|
trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
|
|
|
|
memcpy(trigger, trigdesc->triggers,
|
|
|
|
trigdesc->numtriggers * sizeof(Trigger));
|
|
|
|
newdesc->triggers = trigger;
|
|
|
|
|
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
|
|
|
{
|
|
|
|
trigger->tgname = pstrdup(trigger->tgname);
|
2005-03-29 02:17:27 +02:00
|
|
|
if (trigger->tgnattr > 0)
|
|
|
|
{
|
2012-06-25 00:51:46 +02:00
|
|
|
int16 *newattr;
|
2005-03-29 02:17:27 +02:00
|
|
|
|
2012-06-25 00:51:46 +02:00
|
|
|
newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
|
2005-03-29 02:17:27 +02:00
|
|
|
memcpy(newattr, trigger->tgattr,
|
2012-06-25 00:51:46 +02:00
|
|
|
trigger->tgnattr * sizeof(int16));
|
2005-03-29 02:17:27 +02:00
|
|
|
trigger->tgattr = newattr;
|
|
|
|
}
|
2002-10-14 18:51:30 +02:00
|
|
|
if (trigger->tgnargs > 0)
|
|
|
|
{
|
2003-08-04 02:43:34 +02:00
|
|
|
char **newargs;
|
|
|
|
int16 j;
|
2002-10-14 18:51:30 +02:00
|
|
|
|
|
|
|
newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
|
|
|
|
for (j = 0; j < trigger->tgnargs; j++)
|
|
|
|
newargs[j] = pstrdup(trigger->tgargs[j]);
|
|
|
|
trigger->tgargs = newargs;
|
|
|
|
}
|
2009-11-20 21:38:12 +01:00
|
|
|
if (trigger->tgqual)
|
|
|
|
trigger->tgqual = pstrdup(trigger->tgqual);
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trigger->tgoldtable)
|
|
|
|
trigger->tgoldtable = pstrdup(trigger->tgoldtable);
|
|
|
|
if (trigger->tgnewtable)
|
|
|
|
trigger->tgnewtable = pstrdup(trigger->tgnewtable);
|
2002-10-14 18:51:30 +02:00
|
|
|
trigger++;
|
|
|
|
}
|
|
|
|
|
|
|
|
return newdesc;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Free a TriggerDesc data structure.
|
|
|
|
*/
|
2000-01-31 05:35:57 +01:00
|
|
|
void
|
|
|
|
FreeTriggerDesc(TriggerDesc *trigdesc)
|
|
|
|
{
|
|
|
|
Trigger *trigger;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
if (trigdesc == NULL)
|
|
|
|
return;
|
|
|
|
|
|
|
|
trigger = trigdesc->triggers;
|
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
|
|
|
{
|
|
|
|
pfree(trigger->tgname);
|
2005-03-29 02:17:27 +02:00
|
|
|
if (trigger->tgnattr > 0)
|
|
|
|
pfree(trigger->tgattr);
|
2000-01-31 05:35:57 +01:00
|
|
|
if (trigger->tgnargs > 0)
|
|
|
|
{
|
|
|
|
while (--(trigger->tgnargs) >= 0)
|
|
|
|
pfree(trigger->tgargs[trigger->tgnargs]);
|
|
|
|
pfree(trigger->tgargs);
|
|
|
|
}
|
2009-11-20 21:38:12 +01:00
|
|
|
if (trigger->tgqual)
|
|
|
|
pfree(trigger->tgqual);
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trigger->tgoldtable)
|
|
|
|
pfree(trigger->tgoldtable);
|
|
|
|
if (trigger->tgnewtable)
|
|
|
|
pfree(trigger->tgnewtable);
|
2000-01-31 05:35:57 +01:00
|
|
|
trigger++;
|
|
|
|
}
|
|
|
|
pfree(trigdesc->triggers);
|
|
|
|
pfree(trigdesc);
|
|
|
|
}
|
|
|
|
|
2002-10-14 18:51:30 +02:00
|
|
|
/*
|
|
|
|
* Compare two TriggerDesc structures for logical equality.
|
|
|
|
*/
|
|
|
|
#ifdef NOT_USED
|
2000-01-31 05:35:57 +01:00
|
|
|
bool
|
|
|
|
equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2)
|
|
|
|
{
|
2000-04-12 19:17:23 +02:00
|
|
|
int i,
|
|
|
|
j;
|
2000-01-31 05:35:57 +01:00
|
|
|
|
|
|
|
/*
|
2010-10-10 19:43:33 +02:00
|
|
|
* We need not examine the hint flags, just the trigger array itself; if
|
|
|
|
* we have the same triggers with the same types, the flags should match.
|
2002-04-19 18:36:08 +02:00
|
|
|
*
|
2005-11-22 19:17:34 +01:00
|
|
|
* As of 7.3 we assume trigger set ordering is significant in the
|
|
|
|
* comparison; so we just compare corresponding slots of the two sets.
|
2009-11-20 21:38:12 +01:00
|
|
|
*
|
|
|
|
* Note: comparing the stringToNode forms of the WHEN clauses means that
|
2010-02-26 03:01:40 +01:00
|
|
|
* parse column locations will affect the result. This is okay as long as
|
|
|
|
* this function is only used for detecting exact equality, as for example
|
|
|
|
* in checking for staleness of a cache entry.
|
2000-01-31 05:35:57 +01:00
|
|
|
*/
|
|
|
|
if (trigdesc1 != NULL)
|
|
|
|
{
|
|
|
|
if (trigdesc2 == NULL)
|
|
|
|
return false;
|
|
|
|
if (trigdesc1->numtriggers != trigdesc2->numtriggers)
|
|
|
|
return false;
|
|
|
|
for (i = 0; i < trigdesc1->numtriggers; i++)
|
|
|
|
{
|
2000-04-12 19:17:23 +02:00
|
|
|
Trigger *trig1 = trigdesc1->triggers + i;
|
2002-04-19 18:36:08 +02:00
|
|
|
Trigger *trig2 = trigdesc2->triggers + i;
|
|
|
|
|
|
|
|
if (trig1->tgoid != trig2->tgoid)
|
2000-01-31 05:35:57 +01:00
|
|
|
return false;
|
|
|
|
if (strcmp(trig1->tgname, trig2->tgname) != 0)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgfoid != trig2->tgfoid)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgtype != trig2->tgtype)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgenabled != trig2->tgenabled)
|
|
|
|
return false;
|
2010-01-17 23:56:23 +01:00
|
|
|
if (trig1->tgisinternal != trig2->tgisinternal)
|
2000-01-31 05:35:57 +01:00
|
|
|
return false;
|
2002-04-02 00:36:13 +02:00
|
|
|
if (trig1->tgconstrrelid != trig2->tgconstrrelid)
|
|
|
|
return false;
|
2009-07-28 04:56:31 +02:00
|
|
|
if (trig1->tgconstrindid != trig2->tgconstrindid)
|
|
|
|
return false;
|
2007-02-14 02:58:58 +01:00
|
|
|
if (trig1->tgconstraint != trig2->tgconstraint)
|
|
|
|
return false;
|
2000-01-31 05:35:57 +01:00
|
|
|
if (trig1->tgdeferrable != trig2->tgdeferrable)
|
|
|
|
return false;
|
|
|
|
if (trig1->tginitdeferred != trig2->tginitdeferred)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgnargs != trig2->tgnargs)
|
|
|
|
return false;
|
2005-03-29 02:17:27 +02:00
|
|
|
if (trig1->tgnattr != trig2->tgnattr)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgnattr > 0 &&
|
|
|
|
memcmp(trig1->tgattr, trig2->tgattr,
|
2012-06-25 00:51:46 +02:00
|
|
|
trig1->tgnattr * sizeof(int16)) != 0)
|
2000-01-31 05:35:57 +01:00
|
|
|
return false;
|
|
|
|
for (j = 0; j < trig1->tgnargs; j++)
|
|
|
|
if (strcmp(trig1->tgargs[j], trig2->tgargs[j]) != 0)
|
|
|
|
return false;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (trig1->tgqual == NULL && trig2->tgqual == NULL)
|
2010-02-26 03:01:40 +01:00
|
|
|
/* ok */ ;
|
2009-11-20 21:38:12 +01:00
|
|
|
else if (trig1->tgqual == NULL || trig2->tgqual == NULL)
|
|
|
|
return false;
|
|
|
|
else if (strcmp(trig1->tgqual, trig2->tgqual) != 0)
|
2010-02-26 03:01:40 +01:00
|
|
|
return false;
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trig1->tgoldtable == NULL && trig2->tgoldtable == NULL)
|
|
|
|
/* ok */ ;
|
|
|
|
else if (trig1->tgoldtable == NULL || trig2->tgoldtable == NULL)
|
|
|
|
return false;
|
|
|
|
else if (strcmp(trig1->tgoldtable, trig2->tgoldtable) != 0)
|
|
|
|
return false;
|
|
|
|
if (trig1->tgnewtable == NULL && trig2->tgnewtable == NULL)
|
|
|
|
/* ok */ ;
|
|
|
|
else if (trig1->tgnewtable == NULL || trig2->tgnewtable == NULL)
|
|
|
|
return false;
|
|
|
|
else if (strcmp(trig1->tgnewtable, trig2->tgnewtable) != 0)
|
|
|
|
return false;
|
2000-01-31 05:35:57 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else if (trigdesc2 != NULL)
|
|
|
|
return false;
|
|
|
|
return true;
|
|
|
|
}
|
2003-08-04 02:43:34 +02:00
|
|
|
#endif /* NOT_USED */
|
2000-01-31 05:35:57 +01:00
|
|
|
|
2001-06-01 04:41:36 +02:00
|
|
|
/*
|
|
|
|
* Call a trigger function.
|
|
|
|
*
|
|
|
|
* trigdata: trigger descriptor.
|
2005-03-25 22:58:00 +01:00
|
|
|
* tgindx: trigger's index in finfo and instr arrays.
|
|
|
|
* finfo: array of cached trigger function call information.
|
|
|
|
* instr: optional array of EXPLAIN ANALYZE instrumentation state.
|
2001-06-01 04:41:36 +02:00
|
|
|
* per_tuple_context: memory context to execute the function in.
|
|
|
|
*
|
|
|
|
* Returns the tuple (or NULL) as returned by the function.
|
|
|
|
*/
|
1997-10-28 16:11:45 +01:00
|
|
|
static HeapTuple
|
2001-06-01 04:41:36 +02:00
|
|
|
ExecCallTriggerFunc(TriggerData *trigdata,
|
2005-03-25 22:58:00 +01:00
|
|
|
int tgindx,
|
2001-06-01 04:41:36 +02:00
|
|
|
FmgrInfo *finfo,
|
2005-03-25 22:58:00 +01:00
|
|
|
Instrumentation *instr,
|
2001-01-22 01:50:07 +01:00
|
|
|
MemoryContext per_tuple_context)
|
1997-10-28 16:11:45 +01:00
|
|
|
{
|
2001-03-22 05:01:46 +01:00
|
|
|
FunctionCallInfoData fcinfo;
|
2008-05-15 02:17:41 +02:00
|
|
|
PgStat_FunctionCallUsage fcusage;
|
2001-03-22 05:01:46 +01:00
|
|
|
Datum result;
|
|
|
|
MemoryContext oldContext;
|
2000-05-29 03:59:17 +02:00
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
/*
|
|
|
|
* Protect against code paths that may fail to initialize transition table
|
|
|
|
* info.
|
|
|
|
*/
|
|
|
|
Assert(((TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
|
|
|
|
TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event) ||
|
|
|
|
TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) &&
|
|
|
|
TRIGGER_FIRED_AFTER(trigdata->tg_event) &&
|
|
|
|
!(trigdata->tg_event & AFTER_TRIGGER_DEFERRABLE) &&
|
|
|
|
!(trigdata->tg_event & AFTER_TRIGGER_INITDEFERRED)) ||
|
|
|
|
(trigdata->tg_oldtable == NULL && trigdata->tg_newtable == NULL));
|
|
|
|
|
2005-03-25 22:58:00 +01:00
|
|
|
finfo += tgindx;
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
/*
|
2001-10-25 07:50:21 +02:00
|
|
|
* We cache fmgr lookup info, to avoid making the lookup again on each
|
|
|
|
* call.
|
2000-05-29 03:59:17 +02:00
|
|
|
*/
|
2001-06-01 04:41:36 +02:00
|
|
|
if (finfo->fn_oid == InvalidOid)
|
|
|
|
fmgr_info(trigdata->tg_trigger->tgfoid, finfo);
|
|
|
|
|
|
|
|
Assert(finfo->fn_oid == trigdata->tg_trigger->tgfoid);
|
1997-10-28 16:11:45 +01:00
|
|
|
|
2005-03-25 22:58:00 +01:00
|
|
|
/*
|
|
|
|
* If doing EXPLAIN ANALYZE, start charging time to this trigger.
|
|
|
|
*/
|
|
|
|
if (instr)
|
|
|
|
InstrStartNode(instr + tgindx);
|
|
|
|
|
2001-01-22 01:50:07 +01:00
|
|
|
/*
|
2001-03-22 05:01:46 +01:00
|
|
|
* Do the function evaluation in the per-tuple memory context, so that
|
2005-10-15 04:49:52 +02:00
|
|
|
* leaked memory will be reclaimed once per tuple. Note in particular that
|
|
|
|
* any new tuple created by the trigger function will live till the end of
|
|
|
|
* the tuple cycle.
|
2001-01-22 01:50:07 +01:00
|
|
|
*/
|
|
|
|
oldContext = MemoryContextSwitchTo(per_tuple_context);
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
/*
|
|
|
|
* Call the function, passing no arguments but setting a context.
|
|
|
|
*/
|
2011-04-13 01:19:24 +02:00
|
|
|
InitFunctionCallInfoData(fcinfo, finfo, 0,
|
|
|
|
InvalidOid, (Node *) trigdata, NULL);
|
2000-05-29 03:59:17 +02:00
|
|
|
|
2008-05-15 02:17:41 +02:00
|
|
|
pgstat_init_function_usage(&fcinfo, &fcusage);
|
|
|
|
|
2012-01-25 17:15:29 +01:00
|
|
|
MyTriggerDepth++;
|
|
|
|
PG_TRY();
|
|
|
|
{
|
|
|
|
result = FunctionCallInvoke(&fcinfo);
|
|
|
|
}
|
|
|
|
PG_CATCH();
|
|
|
|
{
|
|
|
|
MyTriggerDepth--;
|
|
|
|
PG_RE_THROW();
|
|
|
|
}
|
|
|
|
PG_END_TRY();
|
|
|
|
MyTriggerDepth--;
|
2000-05-29 03:59:17 +02:00
|
|
|
|
2008-05-15 02:17:41 +02:00
|
|
|
pgstat_end_function_usage(&fcusage, true);
|
|
|
|
|
2001-01-22 01:50:07 +01:00
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Trigger protocol allows function to return a null pointer, but NOT to
|
|
|
|
* set the isnull result flag.
|
2000-05-29 03:59:17 +02:00
|
|
|
*/
|
|
|
|
if (fcinfo.isnull)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
|
2003-09-25 08:58:07 +02:00
|
|
|
errmsg("trigger function %u returned null value",
|
2003-07-20 23:56:35 +02:00
|
|
|
fcinfo.flinfo->fn_oid)));
|
2000-05-29 03:59:17 +02:00
|
|
|
|
2005-03-25 22:58:00 +01:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
|
|
|
|
* one "tuple returned" (really the number of firings).
|
2005-03-25 22:58:00 +01:00
|
|
|
*/
|
|
|
|
if (instr)
|
2006-05-30 16:01:58 +02:00
|
|
|
InstrStopNode(instr + tgindx, 1);
|
2005-03-25 22:58:00 +01:00
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
return (HeapTuple) DatumGetPointer(result);
|
1997-10-28 16:11:45 +01:00
|
|
|
}
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
void
|
|
|
|
ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
2003-08-04 02:43:34 +02:00
|
|
|
TriggerDesc *trigdesc;
|
|
|
|
int i;
|
2002-11-23 04:59:09 +01:00
|
|
|
TriggerData LocTriggerData;
|
|
|
|
|
|
|
|
trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
|
|
|
if (trigdesc == NULL)
|
|
|
|
return;
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!trigdesc->trig_insert_before_statement)
|
2002-11-23 04:59:09 +01:00
|
|
|
return;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_BEFORE;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_trigtuple = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
2002-11-23 04:59:09 +01:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2002-11-23 04:59:09 +01:00
|
|
|
HeapTuple newtuple;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_INSERT))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, NULL, NULL))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2002-11-23 04:59:09 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
|
|
|
|
|
|
|
if (newtuple)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
|
2005-10-15 04:49:52 +02:00
|
|
|
errmsg("BEFORE STATEMENT trigger cannot return a value")));
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (trigdesc && trigdesc->trig_insert_after_statement)
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_INSERT,
|
2009-10-15 00:14:25 +02:00
|
|
|
false, NULL, NULL, NIL, NULL);
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *
|
2001-06-01 04:41:36 +02:00
|
|
|
ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *slot)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple slottuple = ExecMaterializeSlot(slot);
|
|
|
|
HeapTuple newtuple = slottuple;
|
1997-09-11 09:24:37 +02:00
|
|
|
HeapTuple oldtuple;
|
2001-03-22 05:01:46 +01:00
|
|
|
TriggerData LocTriggerData;
|
1997-09-08 04:41:22 +02:00
|
|
|
int i;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.type = T_TriggerData;
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_BEFORE;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
1997-09-07 07:04:48 +02:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2001-06-01 04:41:36 +02:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_INSERT))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, NULL, newtuple))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_trigtuple = oldtuple = newtuple;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2001-01-22 01:50:07 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
2011-02-22 03:18:04 +01:00
|
|
|
if (oldtuple != newtuple && oldtuple != slottuple)
|
2001-01-22 01:50:07 +01:00
|
|
|
heap_freetuple(oldtuple);
|
1997-09-07 07:04:48 +02:00
|
|
|
if (newtuple == NULL)
|
2011-02-22 03:18:04 +01:00
|
|
|
return NULL; /* "do nothing" */
|
1997-09-07 07:04:48 +02:00
|
|
|
}
|
2011-02-22 03:18:04 +01:00
|
|
|
|
|
|
|
if (newtuple != slottuple)
|
|
|
|
{
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Return the modified tuple using the es_trig_tuple_slot. We assume
|
2011-02-22 03:18:04 +01:00
|
|
|
* the tuple was allocated in per-tuple memory context, and therefore
|
|
|
|
* will go away by itself. The tuple table slot should not try to
|
|
|
|
* clear it.
|
|
|
|
*/
|
|
|
|
TupleTableSlot *newslot = estate->es_trig_tuple_slot;
|
|
|
|
TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
|
|
|
|
|
|
|
|
if (newslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(newslot, tupdesc);
|
|
|
|
ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
|
|
|
|
slot = newslot;
|
|
|
|
}
|
|
|
|
return slot;
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2001-06-01 04:41:36 +02:00
|
|
|
ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo,
|
2009-07-29 22:56:21 +02:00
|
|
|
HeapTuple trigtuple, List *recheckIndexes)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trigdesc &&
|
|
|
|
(trigdesc->trig_insert_after_row || trigdesc->trig_insert_new_table))
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_INSERT,
|
2009-10-15 00:14:25 +02:00
|
|
|
true, NULL, trigtuple, recheckIndexes, NULL);
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *
|
2010-10-10 19:43:33 +02:00
|
|
|
ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *slot)
|
2010-10-10 19:43:33 +02:00
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple slottuple = ExecMaterializeSlot(slot);
|
|
|
|
HeapTuple newtuple = slottuple;
|
2010-10-10 19:43:33 +02:00
|
|
|
HeapTuple oldtuple;
|
|
|
|
TriggerData LocTriggerData;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
|
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_INSTEAD;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2010-10-10 19:43:33 +02:00
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
|
|
|
{
|
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
|
|
|
|
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD,
|
|
|
|
TRIGGER_TYPE_INSERT))
|
|
|
|
continue;
|
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, NULL, newtuple))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
LocTriggerData.tg_trigtuple = oldtuple = newtuple;
|
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
|
|
|
i,
|
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
|
|
|
GetPerTupleMemoryContext(estate));
|
2011-02-22 03:18:04 +01:00
|
|
|
if (oldtuple != newtuple && oldtuple != slottuple)
|
2010-10-10 19:43:33 +02:00
|
|
|
heap_freetuple(oldtuple);
|
|
|
|
if (newtuple == NULL)
|
2011-02-22 03:18:04 +01:00
|
|
|
return NULL; /* "do nothing" */
|
|
|
|
}
|
|
|
|
|
|
|
|
if (newtuple != slottuple)
|
|
|
|
{
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Return the modified tuple using the es_trig_tuple_slot. We assume
|
2011-02-22 03:18:04 +01:00
|
|
|
* the tuple was allocated in per-tuple memory context, and therefore
|
|
|
|
* will go away by itself. The tuple table slot should not try to
|
|
|
|
* clear it.
|
|
|
|
*/
|
|
|
|
TupleTableSlot *newslot = estate->es_trig_tuple_slot;
|
|
|
|
TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
|
|
|
|
|
|
|
|
if (newslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(newslot, tupdesc);
|
|
|
|
ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
|
|
|
|
slot = newslot;
|
2010-10-10 19:43:33 +02:00
|
|
|
}
|
2011-02-22 03:18:04 +01:00
|
|
|
return slot;
|
2010-10-10 19:43:33 +02:00
|
|
|
}
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
void
|
|
|
|
ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
2003-08-04 02:43:34 +02:00
|
|
|
TriggerDesc *trigdesc;
|
|
|
|
int i;
|
2002-11-23 04:59:09 +01:00
|
|
|
TriggerData LocTriggerData;
|
|
|
|
|
|
|
|
trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
|
|
|
if (trigdesc == NULL)
|
|
|
|
return;
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!trigdesc->trig_delete_before_statement)
|
2002-11-23 04:59:09 +01:00
|
|
|
return;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_BEFORE;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_trigtuple = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
2002-11-23 04:59:09 +01:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2002-11-23 04:59:09 +01:00
|
|
|
HeapTuple newtuple;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_DELETE))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, NULL, NULL))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2002-11-23 04:59:09 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
|
|
|
|
|
|
|
if (newtuple)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
|
2005-10-15 04:49:52 +02:00
|
|
|
errmsg("BEFORE STATEMENT trigger cannot return a value")));
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (trigdesc && trigdesc->trig_delete_after_statement)
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_DELETE,
|
2009-10-15 00:14:25 +02:00
|
|
|
false, NULL, NULL, NIL, NULL);
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
bool
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
ExecBRDeleteTriggers(EState *estate, EPQState *epqstate,
|
2009-10-10 03:43:50 +02:00
|
|
|
ResultRelInfo *relinfo,
|
2014-03-23 07:16:34 +01:00
|
|
|
ItemPointer tupleid,
|
|
|
|
HeapTuple fdw_trigtuple)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2005-08-24 19:38:35 +02:00
|
|
|
bool result = true;
|
2000-05-29 03:59:17 +02:00
|
|
|
TriggerData LocTriggerData;
|
1999-05-25 18:15:34 +02:00
|
|
|
HeapTuple trigtuple;
|
2005-08-24 19:38:35 +02:00
|
|
|
HeapTuple newtuple;
|
1999-01-29 12:56:01 +01:00
|
|
|
TupleTableSlot *newSlot;
|
1999-05-25 18:15:34 +02:00
|
|
|
int i;
|
1998-12-15 13:47:01 +01:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
|
|
|
|
if (fdw_trigtuple == NULL)
|
|
|
|
{
|
|
|
|
trigtuple = GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
|
|
|
|
LockTupleExclusive, &newSlot);
|
|
|
|
if (trigtuple == NULL)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
trigtuple = fdw_trigtuple;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.type = T_TriggerData;
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_BEFORE;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
1997-09-11 09:24:37 +02:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2001-06-01 04:41:36 +02:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_DELETE))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, trigtuple, NULL))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_trigtuple = trigtuple;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2001-01-22 01:50:07 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
1997-09-11 09:24:37 +02:00
|
|
|
if (newtuple == NULL)
|
2005-08-24 19:38:35 +02:00
|
|
|
{
|
|
|
|
result = false; /* tell caller to suppress delete */
|
1997-09-11 09:24:37 +02:00
|
|
|
break;
|
2005-08-24 19:38:35 +02:00
|
|
|
}
|
1999-02-01 21:25:55 +01:00
|
|
|
if (newtuple != trigtuple)
|
1999-12-16 23:20:03 +01:00
|
|
|
heap_freetuple(newtuple);
|
1997-09-11 09:24:37 +02:00
|
|
|
}
|
2014-03-23 07:16:34 +01:00
|
|
|
if (trigtuple != fdw_trigtuple)
|
|
|
|
heap_freetuple(trigtuple);
|
1997-09-11 09:24:37 +02:00
|
|
|
|
2005-08-24 19:38:35 +02:00
|
|
|
return result;
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2001-06-01 04:41:36 +02:00
|
|
|
ExecARDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
|
2014-03-23 07:16:34 +01:00
|
|
|
ItemPointer tupleid,
|
|
|
|
HeapTuple fdw_trigtuple)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trigdesc &&
|
|
|
|
(trigdesc->trig_delete_after_row || trigdesc->trig_delete_old_table))
|
2001-01-27 06:16:58 +01:00
|
|
|
{
|
2014-03-23 07:16:34 +01:00
|
|
|
HeapTuple trigtuple;
|
|
|
|
|
|
|
|
Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
|
|
|
|
if (fdw_trigtuple == NULL)
|
|
|
|
trigtuple = GetTupleForTrigger(estate,
|
|
|
|
NULL,
|
|
|
|
relinfo,
|
|
|
|
tupleid,
|
|
|
|
LockTupleExclusive,
|
|
|
|
NULL);
|
|
|
|
else
|
|
|
|
trigtuple = fdw_trigtuple;
|
2001-01-27 06:16:58 +01:00
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_DELETE,
|
2009-10-15 00:14:25 +02:00
|
|
|
true, trigtuple, NULL, NIL, NULL);
|
2014-03-23 07:16:34 +01:00
|
|
|
if (trigtuple != fdw_trigtuple)
|
|
|
|
heap_freetuple(trigtuple);
|
2001-01-27 06:16:58 +01:00
|
|
|
}
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
bool
|
|
|
|
ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
|
|
|
|
HeapTuple trigtuple)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
TriggerData LocTriggerData;
|
|
|
|
HeapTuple rettuple;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
|
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_INSTEAD;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2010-10-10 19:43:33 +02:00
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
|
|
|
{
|
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
|
|
|
|
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD,
|
|
|
|
TRIGGER_TYPE_DELETE))
|
|
|
|
continue;
|
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, trigtuple, NULL))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
LocTriggerData.tg_trigtuple = trigtuple;
|
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
rettuple = ExecCallTriggerFunc(&LocTriggerData,
|
|
|
|
i,
|
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
|
|
|
GetPerTupleMemoryContext(estate));
|
|
|
|
if (rettuple == NULL)
|
|
|
|
return false; /* Delete was suppressed */
|
|
|
|
if (rettuple != trigtuple)
|
|
|
|
heap_freetuple(rettuple);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
void
|
|
|
|
ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
2003-08-04 02:43:34 +02:00
|
|
|
TriggerDesc *trigdesc;
|
|
|
|
int i;
|
2002-11-23 04:59:09 +01:00
|
|
|
TriggerData LocTriggerData;
|
2015-05-08 00:20:46 +02:00
|
|
|
Bitmapset *updatedCols;
|
2002-11-23 04:59:09 +01:00
|
|
|
|
|
|
|
trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
|
|
|
if (trigdesc == NULL)
|
|
|
|
return;
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!trigdesc->trig_update_before_statement)
|
2002-11-23 04:59:09 +01:00
|
|
|
return;
|
|
|
|
|
2015-05-08 00:20:46 +02:00
|
|
|
updatedCols = GetUpdatedColumns(relinfo, estate);
|
2009-10-15 00:14:25 +02:00
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_BEFORE;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_trigtuple = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
2002-11-23 04:59:09 +01:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2002-11-23 04:59:09 +01:00
|
|
|
HeapTuple newtuple;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_UPDATE))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
2015-05-08 00:20:46 +02:00
|
|
|
updatedCols, NULL, NULL))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2002-11-23 04:59:09 +01:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2002-11-23 04:59:09 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
|
|
|
|
|
|
|
if (newtuple)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
|
2005-10-15 04:49:52 +02:00
|
|
|
errmsg("BEFORE STATEMENT trigger cannot return a value")));
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (trigdesc && trigdesc->trig_update_after_statement)
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_UPDATE,
|
2009-10-15 00:14:25 +02:00
|
|
|
false, NULL, NULL, NIL,
|
2015-05-08 00:20:46 +02:00
|
|
|
GetUpdatedColumns(relinfo, estate));
|
2002-11-23 04:59:09 +01:00
|
|
|
}
|
|
|
|
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
ExecBRUpdateTriggers(EState *estate, EPQState *epqstate,
|
2009-10-10 03:43:50 +02:00
|
|
|
ResultRelInfo *relinfo,
|
2014-03-23 07:16:34 +01:00
|
|
|
ItemPointer tupleid,
|
|
|
|
HeapTuple fdw_trigtuple,
|
|
|
|
TupleTableSlot *slot)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple slottuple = ExecMaterializeSlot(slot);
|
|
|
|
HeapTuple newtuple = slottuple;
|
2000-05-29 03:59:17 +02:00
|
|
|
TriggerData LocTriggerData;
|
1999-05-25 18:15:34 +02:00
|
|
|
HeapTuple trigtuple;
|
|
|
|
HeapTuple oldtuple;
|
1999-01-29 12:56:01 +01:00
|
|
|
TupleTableSlot *newSlot;
|
1999-05-25 18:15:34 +02:00
|
|
|
int i;
|
2015-05-08 00:20:46 +02:00
|
|
|
Bitmapset *updatedCols;
|
Improve concurrency of foreign key locking
This patch introduces two additional lock modes for tuples: "SELECT FOR
KEY SHARE" and "SELECT FOR NO KEY UPDATE". These don't block each
other, in contrast with already existing "SELECT FOR SHARE" and "SELECT
FOR UPDATE". UPDATE commands that do not modify the values stored in
the columns that are part of the key of the tuple now grab a SELECT FOR
NO KEY UPDATE lock on the tuple, allowing them to proceed concurrently
with tuple locks of the FOR KEY SHARE variety.
Foreign key triggers now use FOR KEY SHARE instead of FOR SHARE; this
means the concurrency improvement applies to them, which is the whole
point of this patch.
The added tuple lock semantics require some rejiggering of the multixact
module, so that the locking level that each transaction is holding can
be stored alongside its Xid. Also, multixacts now need to persist
across server restarts and crashes, because they can now represent not
only tuple locks, but also tuple updates. This means we need more
careful tracking of lifetime of pg_multixact SLRU files; since they now
persist longer, we require more infrastructure to figure out when they
can be removed. pg_upgrade also needs to be careful to copy
pg_multixact files over from the old server to the new, or at least part
of multixact.c state, depending on the versions of the old and new
servers.
Tuple time qualification rules (HeapTupleSatisfies routines) need to be
careful not to consider tuples with the "is multi" infomask bit set as
being only locked; they might need to look up MultiXact values (i.e.
possibly do pg_multixact I/O) to find out the Xid that updated a tuple,
whereas they previously were assured to only use information readily
available from the tuple header. This is considered acceptable, because
the extra I/O would involve cases that would previously cause some
commands to block waiting for concurrent transactions to finish.
Another important change is the fact that locking tuples that have
previously been updated causes the future versions to be marked as
locked, too; this is essential for correctness of foreign key checks.
This causes additional WAL-logging, also (there was previously a single
WAL record for a locked tuple; now there are as many as updated copies
of the tuple there exist.)
With all this in place, contention related to tuples being checked by
foreign key rules should be much reduced.
As a bonus, the old behavior that a subtransaction grabbing a stronger
tuple lock than the parent (sub)transaction held on a given tuple and
later aborting caused the weaker lock to be lost, has been fixed.
Many new spec files were added for isolation tester framework, to ensure
overall behavior is sane. There's probably room for several more tests.
There were several reviewers of this patch; in particular, Noah Misch
and Andres Freund spent considerable time in it. Original idea for the
patch came from Simon Riggs, after a problem report by Joel Jacobson.
Most code is from me, with contributions from Marti Raudsepp, Alexander
Shulgin, Noah Misch and Andres Freund.
This patch was discussed in several pgsql-hackers threads; the most
important start at the following message-ids:
AANLkTimo9XVcEzfiBR-ut3KVNDkjm2Vxh+t8kAmWjPuv@mail.gmail.com
1290721684-sup-3951@alvh.no-ip.org
1294953201-sup-2099@alvh.no-ip.org
1320343602-sup-2290@alvh.no-ip.org
1339690386-sup-8927@alvh.no-ip.org
4FE5FF020200002500048A3D@gw.wicourts.gov
4FEAB90A0200002500048B7D@gw.wicourts.gov
2013-01-23 16:04:59 +01:00
|
|
|
LockTupleMode lockmode;
|
|
|
|
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
/* Determine lock mode to use */
|
|
|
|
lockmode = ExecUpdateLockMode(estate, relinfo);
|
1998-12-15 13:47:01 +01:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
|
|
|
|
if (fdw_trigtuple == NULL)
|
|
|
|
{
|
|
|
|
/* get a copy of the on-disk tuple we are planning to update */
|
|
|
|
trigtuple = GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
|
|
|
|
lockmode, &newSlot);
|
|
|
|
if (trigtuple == NULL)
|
|
|
|
return NULL; /* cancel the update action */
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
trigtuple = fdw_trigtuple;
|
|
|
|
newSlot = NULL;
|
|
|
|
}
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1999-01-29 12:56:01 +01:00
|
|
|
/*
|
2011-02-22 03:18:04 +01:00
|
|
|
* In READ COMMITTED isolation level it's possible that target tuple was
|
2009-10-10 03:43:50 +02:00
|
|
|
* changed due to concurrent update. In that case we have a raw subplan
|
2011-02-22 03:18:04 +01:00
|
|
|
* output tuple in newSlot, and need to run it through the junk filter to
|
|
|
|
* produce an insertable tuple.
|
|
|
|
*
|
|
|
|
* Caution: more than likely, the passed-in slot is the same as the
|
|
|
|
* junkfilter's output slot, so we are clobbering the original value of
|
|
|
|
* slottuple by doing the filtering. This is OK since neither we nor our
|
|
|
|
* caller have any more interest in the prior contents of that slot.
|
1999-01-29 12:56:01 +01:00
|
|
|
*/
|
|
|
|
if (newSlot != NULL)
|
2011-02-22 03:18:04 +01:00
|
|
|
{
|
|
|
|
slot = ExecFilterJunk(relinfo->ri_junkFilter, newSlot);
|
|
|
|
slottuple = ExecMaterializeSlot(slot);
|
|
|
|
newtuple = slottuple;
|
|
|
|
}
|
1999-01-29 12:56:01 +01:00
|
|
|
|
2009-10-15 00:14:25 +02:00
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.type = T_TriggerData;
|
2003-01-08 23:28:32 +01:00
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
|
2003-08-04 02:43:34 +02:00
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_BEFORE;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
updatedCols = GetUpdatedColumns(relinfo, estate);
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
1997-09-11 09:24:37 +02:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2001-06-01 04:41:36 +02:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_UPDATE))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
2015-05-08 00:20:46 +02:00
|
|
|
updatedCols, trigtuple, newtuple))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_trigtuple = trigtuple;
|
|
|
|
LocTriggerData.tg_newtuple = oldtuple = newtuple;
|
2004-10-30 22:53:06 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2001-06-01 04:41:36 +02:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2005-03-25 22:58:00 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
2001-01-22 01:50:07 +01:00
|
|
|
GetPerTupleMemoryContext(estate));
|
2011-02-22 03:18:04 +01:00
|
|
|
if (oldtuple != newtuple && oldtuple != slottuple)
|
2001-01-22 01:50:07 +01:00
|
|
|
heap_freetuple(oldtuple);
|
1997-09-11 09:24:37 +02:00
|
|
|
if (newtuple == NULL)
|
2011-02-22 03:18:04 +01:00
|
|
|
{
|
2014-03-23 07:16:34 +01:00
|
|
|
if (trigtuple != fdw_trigtuple)
|
|
|
|
heap_freetuple(trigtuple);
|
2011-02-22 03:18:04 +01:00
|
|
|
return NULL; /* "do nothing" */
|
|
|
|
}
|
1997-09-11 09:24:37 +02:00
|
|
|
}
|
2014-03-23 07:16:34 +01:00
|
|
|
if (trigtuple != fdw_trigtuple)
|
|
|
|
heap_freetuple(trigtuple);
|
2011-02-22 03:18:04 +01:00
|
|
|
|
|
|
|
if (newtuple != slottuple)
|
|
|
|
{
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Return the modified tuple using the es_trig_tuple_slot. We assume
|
2011-02-22 03:18:04 +01:00
|
|
|
* the tuple was allocated in per-tuple memory context, and therefore
|
|
|
|
* will go away by itself. The tuple table slot should not try to
|
|
|
|
* clear it.
|
|
|
|
*/
|
|
|
|
TupleTableSlot *newslot = estate->es_trig_tuple_slot;
|
|
|
|
TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
|
|
|
|
|
|
|
|
if (newslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(newslot, tupdesc);
|
|
|
|
ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
|
|
|
|
slot = newslot;
|
|
|
|
}
|
|
|
|
return slot;
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2001-06-01 04:41:36 +02:00
|
|
|
ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
|
2014-03-23 07:16:34 +01:00
|
|
|
ItemPointer tupleid,
|
|
|
|
HeapTuple fdw_trigtuple,
|
|
|
|
HeapTuple newtuple,
|
2009-07-29 22:56:21 +02:00
|
|
|
List *recheckIndexes)
|
1997-09-01 09:59:06 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
1997-09-07 07:04:48 +02:00
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
if (trigdesc && (trigdesc->trig_update_after_row ||
|
|
|
|
trigdesc->trig_update_old_table || trigdesc->trig_update_new_table))
|
2001-01-27 06:16:58 +01:00
|
|
|
{
|
2014-03-23 07:16:34 +01:00
|
|
|
HeapTuple trigtuple;
|
|
|
|
|
|
|
|
Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
|
|
|
|
if (fdw_trigtuple == NULL)
|
|
|
|
trigtuple = GetTupleForTrigger(estate,
|
|
|
|
NULL,
|
|
|
|
relinfo,
|
|
|
|
tupleid,
|
|
|
|
LockTupleExclusive,
|
|
|
|
NULL);
|
|
|
|
else
|
|
|
|
trigtuple = fdw_trigtuple;
|
2001-01-27 06:16:58 +01:00
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_UPDATE,
|
2009-10-15 00:14:25 +02:00
|
|
|
true, trigtuple, newtuple, recheckIndexes,
|
2015-05-08 00:20:46 +02:00
|
|
|
GetUpdatedColumns(relinfo, estate));
|
2014-03-23 07:16:34 +01:00
|
|
|
if (trigtuple != fdw_trigtuple)
|
|
|
|
heap_freetuple(trigtuple);
|
2001-01-27 06:16:58 +01:00
|
|
|
}
|
1997-09-01 09:59:06 +02:00
|
|
|
}
|
1997-09-11 09:24:37 +02:00
|
|
|
|
2011-02-22 03:18:04 +01:00
|
|
|
TupleTableSlot *
|
2010-10-10 19:43:33 +02:00
|
|
|
ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple trigtuple, TupleTableSlot *slot)
|
2010-10-10 19:43:33 +02:00
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple slottuple = ExecMaterializeSlot(slot);
|
|
|
|
HeapTuple newtuple = slottuple;
|
2010-10-10 19:43:33 +02:00
|
|
|
TriggerData LocTriggerData;
|
2011-02-22 03:18:04 +01:00
|
|
|
HeapTuple oldtuple;
|
2010-10-10 19:43:33 +02:00
|
|
|
int i;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
|
|
|
|
TRIGGER_EVENT_ROW |
|
|
|
|
TRIGGER_EVENT_INSTEAD;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
|
|
|
{
|
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
|
|
|
|
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_ROW,
|
|
|
|
TRIGGER_TYPE_INSTEAD,
|
|
|
|
TRIGGER_TYPE_UPDATE))
|
|
|
|
continue;
|
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
2011-02-22 03:18:04 +01:00
|
|
|
NULL, trigtuple, newtuple))
|
2010-10-10 19:43:33 +02:00
|
|
|
continue;
|
|
|
|
|
2011-02-22 03:18:04 +01:00
|
|
|
LocTriggerData.tg_trigtuple = trigtuple;
|
|
|
|
LocTriggerData.tg_newtuple = oldtuple = newtuple;
|
2010-10-10 19:43:33 +02:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_trigger = trigger;
|
2011-02-22 03:18:04 +01:00
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
|
|
|
GetPerTupleMemoryContext(estate));
|
2011-02-22 03:18:04 +01:00
|
|
|
if (oldtuple != newtuple && oldtuple != slottuple)
|
|
|
|
heap_freetuple(oldtuple);
|
2010-10-10 19:43:33 +02:00
|
|
|
if (newtuple == NULL)
|
2011-02-22 03:18:04 +01:00
|
|
|
return NULL; /* "do nothing" */
|
|
|
|
}
|
|
|
|
|
|
|
|
if (newtuple != slottuple)
|
|
|
|
{
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Return the modified tuple using the es_trig_tuple_slot. We assume
|
2011-02-22 03:18:04 +01:00
|
|
|
* the tuple was allocated in per-tuple memory context, and therefore
|
|
|
|
* will go away by itself. The tuple table slot should not try to
|
|
|
|
* clear it.
|
|
|
|
*/
|
|
|
|
TupleTableSlot *newslot = estate->es_trig_tuple_slot;
|
|
|
|
TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
|
|
|
|
|
|
|
|
if (newslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(newslot, tupdesc);
|
|
|
|
ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
|
|
|
|
slot = newslot;
|
2010-10-10 19:43:33 +02:00
|
|
|
}
|
2011-02-22 03:18:04 +01:00
|
|
|
return slot;
|
2010-10-10 19:43:33 +02:00
|
|
|
}
|
|
|
|
|
2008-03-28 01:21:56 +01:00
|
|
|
void
|
|
|
|
ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc;
|
|
|
|
int i;
|
|
|
|
TriggerData LocTriggerData;
|
|
|
|
|
|
|
|
trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
|
|
|
if (trigdesc == NULL)
|
|
|
|
return;
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!trigdesc->trig_truncate_before_statement)
|
2008-03-28 01:21:56 +01:00
|
|
|
return;
|
|
|
|
|
|
|
|
LocTriggerData.type = T_TriggerData;
|
|
|
|
LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
|
|
|
|
TRIGGER_EVENT_BEFORE;
|
|
|
|
LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
|
|
|
|
LocTriggerData.tg_trigtuple = NULL;
|
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
2008-03-28 01:21:56 +01:00
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
2008-03-28 01:21:56 +01:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2008-03-28 01:21:56 +01:00
|
|
|
HeapTuple newtuple;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
TRIGGER_TYPE_STATEMENT,
|
|
|
|
TRIGGER_TYPE_BEFORE,
|
|
|
|
TRIGGER_TYPE_TRUNCATE))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
|
|
|
|
NULL, NULL, NULL))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
|
|
|
|
2008-03-28 01:21:56 +01:00
|
|
|
LocTriggerData.tg_trigger = trigger;
|
|
|
|
newtuple = ExecCallTriggerFunc(&LocTriggerData,
|
2010-10-10 19:43:33 +02:00
|
|
|
i,
|
2008-03-28 01:21:56 +01:00
|
|
|
relinfo->ri_TrigFunctions,
|
|
|
|
relinfo->ri_TrigInstrument,
|
|
|
|
GetPerTupleMemoryContext(estate));
|
|
|
|
|
|
|
|
if (newtuple)
|
|
|
|
ereport(ERROR,
|
2009-06-11 16:49:15 +02:00
|
|
|
(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
|
|
|
|
errmsg("BEFORE STATEMENT trigger cannot return a value")));
|
2008-03-28 01:21:56 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
|
|
|
|
{
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (trigdesc && trigdesc->trig_truncate_after_statement)
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(estate, relinfo, TRIGGER_EVENT_TRUNCATE,
|
2009-10-15 00:14:25 +02:00
|
|
|
false, NULL, NULL, NIL, NULL);
|
2008-03-28 01:21:56 +01:00
|
|
|
}
|
|
|
|
|
1999-01-29 10:23:17 +01:00
|
|
|
|
1997-09-11 09:24:37 +02:00
|
|
|
static HeapTuple
|
2009-10-10 03:43:50 +02:00
|
|
|
GetTupleForTrigger(EState *estate,
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
EPQState *epqstate,
|
2009-10-10 03:43:50 +02:00
|
|
|
ResultRelInfo *relinfo,
|
2007-11-30 22:22:54 +01:00
|
|
|
ItemPointer tid,
|
Improve concurrency of foreign key locking
This patch introduces two additional lock modes for tuples: "SELECT FOR
KEY SHARE" and "SELECT FOR NO KEY UPDATE". These don't block each
other, in contrast with already existing "SELECT FOR SHARE" and "SELECT
FOR UPDATE". UPDATE commands that do not modify the values stored in
the columns that are part of the key of the tuple now grab a SELECT FOR
NO KEY UPDATE lock on the tuple, allowing them to proceed concurrently
with tuple locks of the FOR KEY SHARE variety.
Foreign key triggers now use FOR KEY SHARE instead of FOR SHARE; this
means the concurrency improvement applies to them, which is the whole
point of this patch.
The added tuple lock semantics require some rejiggering of the multixact
module, so that the locking level that each transaction is holding can
be stored alongside its Xid. Also, multixacts now need to persist
across server restarts and crashes, because they can now represent not
only tuple locks, but also tuple updates. This means we need more
careful tracking of lifetime of pg_multixact SLRU files; since they now
persist longer, we require more infrastructure to figure out when they
can be removed. pg_upgrade also needs to be careful to copy
pg_multixact files over from the old server to the new, or at least part
of multixact.c state, depending on the versions of the old and new
servers.
Tuple time qualification rules (HeapTupleSatisfies routines) need to be
careful not to consider tuples with the "is multi" infomask bit set as
being only locked; they might need to look up MultiXact values (i.e.
possibly do pg_multixact I/O) to find out the Xid that updated a tuple,
whereas they previously were assured to only use information readily
available from the tuple header. This is considered acceptable, because
the extra I/O would involve cases that would previously cause some
commands to block waiting for concurrent transactions to finish.
Another important change is the fact that locking tuples that have
previously been updated causes the future versions to be marked as
locked, too; this is essential for correctness of foreign key checks.
This causes additional WAL-logging, also (there was previously a single
WAL record for a locked tuple; now there are as many as updated copies
of the tuple there exist.)
With all this in place, contention related to tuples being checked by
foreign key rules should be much reduced.
As a bonus, the old behavior that a subtransaction grabbing a stronger
tuple lock than the parent (sub)transaction held on a given tuple and
later aborting caused the weaker lock to be lost, has been fixed.
Many new spec files were added for isolation tester framework, to ensure
overall behavior is sane. There's probably room for several more tests.
There were several reviewers of this patch; in particular, Noah Misch
and Andres Freund spent considerable time in it. Original idea for the
patch came from Simon Riggs, after a problem report by Joel Jacobson.
Most code is from me, with contributions from Marti Raudsepp, Alexander
Shulgin, Noah Misch and Andres Freund.
This patch was discussed in several pgsql-hackers threads; the most
important start at the following message-ids:
AANLkTimo9XVcEzfiBR-ut3KVNDkjm2Vxh+t8kAmWjPuv@mail.gmail.com
1290721684-sup-3951@alvh.no-ip.org
1294953201-sup-2099@alvh.no-ip.org
1320343602-sup-2290@alvh.no-ip.org
1339690386-sup-8927@alvh.no-ip.org
4FE5FF020200002500048A3D@gw.wicourts.gov
4FEAB90A0200002500048B7D@gw.wicourts.gov
2013-01-23 16:04:59 +01:00
|
|
|
LockTupleMode lockmode,
|
2003-03-27 15:33:11 +01:00
|
|
|
TupleTableSlot **newSlot)
|
1997-09-11 09:24:37 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
Relation relation = relinfo->ri_RelationDesc;
|
1999-05-25 18:15:34 +02:00
|
|
|
HeapTupleData tuple;
|
|
|
|
HeapTuple result;
|
|
|
|
Buffer buffer;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1999-01-29 12:56:01 +01:00
|
|
|
if (newSlot != NULL)
|
1998-12-15 13:47:01 +01:00
|
|
|
{
|
2005-10-15 04:49:52 +02:00
|
|
|
HTSU_Result test;
|
2012-10-26 21:55:36 +02:00
|
|
|
HeapUpdateFailureData hufd;
|
2005-08-20 02:40:32 +02:00
|
|
|
|
|
|
|
*newSlot = NULL;
|
1998-12-15 13:47:01 +01:00
|
|
|
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
/* caller must pass an epqstate if EvalPlanQual is possible */
|
|
|
|
Assert(epqstate != NULL);
|
2009-10-10 03:43:50 +02:00
|
|
|
|
1998-12-15 13:47:01 +01:00
|
|
|
/*
|
2005-04-28 23:47:18 +02:00
|
|
|
* lock tuple for update
|
1998-12-15 13:47:01 +01:00
|
|
|
*/
|
1999-01-29 10:23:17 +01:00
|
|
|
ltrmark:;
|
2005-08-20 02:40:32 +02:00
|
|
|
tuple.t_self = *tid;
|
2012-10-26 21:55:36 +02:00
|
|
|
test = heap_lock_tuple(relation, &tuple,
|
2007-11-30 22:22:54 +01:00
|
|
|
estate->es_output_cid,
|
2014-10-07 22:23:34 +02:00
|
|
|
lockmode, LockWaitBlock,
|
Improve concurrency of foreign key locking
This patch introduces two additional lock modes for tuples: "SELECT FOR
KEY SHARE" and "SELECT FOR NO KEY UPDATE". These don't block each
other, in contrast with already existing "SELECT FOR SHARE" and "SELECT
FOR UPDATE". UPDATE commands that do not modify the values stored in
the columns that are part of the key of the tuple now grab a SELECT FOR
NO KEY UPDATE lock on the tuple, allowing them to proceed concurrently
with tuple locks of the FOR KEY SHARE variety.
Foreign key triggers now use FOR KEY SHARE instead of FOR SHARE; this
means the concurrency improvement applies to them, which is the whole
point of this patch.
The added tuple lock semantics require some rejiggering of the multixact
module, so that the locking level that each transaction is holding can
be stored alongside its Xid. Also, multixacts now need to persist
across server restarts and crashes, because they can now represent not
only tuple locks, but also tuple updates. This means we need more
careful tracking of lifetime of pg_multixact SLRU files; since they now
persist longer, we require more infrastructure to figure out when they
can be removed. pg_upgrade also needs to be careful to copy
pg_multixact files over from the old server to the new, or at least part
of multixact.c state, depending on the versions of the old and new
servers.
Tuple time qualification rules (HeapTupleSatisfies routines) need to be
careful not to consider tuples with the "is multi" infomask bit set as
being only locked; they might need to look up MultiXact values (i.e.
possibly do pg_multixact I/O) to find out the Xid that updated a tuple,
whereas they previously were assured to only use information readily
available from the tuple header. This is considered acceptable, because
the extra I/O would involve cases that would previously cause some
commands to block waiting for concurrent transactions to finish.
Another important change is the fact that locking tuples that have
previously been updated causes the future versions to be marked as
locked, too; this is essential for correctness of foreign key checks.
This causes additional WAL-logging, also (there was previously a single
WAL record for a locked tuple; now there are as many as updated copies
of the tuple there exist.)
With all this in place, contention related to tuples being checked by
foreign key rules should be much reduced.
As a bonus, the old behavior that a subtransaction grabbing a stronger
tuple lock than the parent (sub)transaction held on a given tuple and
later aborting caused the weaker lock to be lost, has been fixed.
Many new spec files were added for isolation tester framework, to ensure
overall behavior is sane. There's probably room for several more tests.
There were several reviewers of this patch; in particular, Noah Misch
and Andres Freund spent considerable time in it. Original idea for the
patch came from Simon Riggs, after a problem report by Joel Jacobson.
Most code is from me, with contributions from Marti Raudsepp, Alexander
Shulgin, Noah Misch and Andres Freund.
This patch was discussed in several pgsql-hackers threads; the most
important start at the following message-ids:
AANLkTimo9XVcEzfiBR-ut3KVNDkjm2Vxh+t8kAmWjPuv@mail.gmail.com
1290721684-sup-3951@alvh.no-ip.org
1294953201-sup-2099@alvh.no-ip.org
1320343602-sup-2290@alvh.no-ip.org
1339690386-sup-8927@alvh.no-ip.org
4FE5FF020200002500048A3D@gw.wicourts.gov
4FEAB90A0200002500048B7D@gw.wicourts.gov
2013-01-23 16:04:59 +01:00
|
|
|
false, &buffer, &hufd);
|
1998-12-15 13:47:01 +01:00
|
|
|
switch (test)
|
|
|
|
{
|
|
|
|
case HeapTupleSelfUpdated:
|
2013-05-29 22:58:43 +02:00
|
|
|
|
2012-10-26 21:55:36 +02:00
|
|
|
/*
|
|
|
|
* The target tuple was already updated or deleted by the
|
|
|
|
* current command, or by a later command in the current
|
|
|
|
* transaction. We ignore the tuple in the former case, and
|
|
|
|
* throw error in the latter case, for the same reasons
|
|
|
|
* enumerated in ExecUpdate and ExecDelete in
|
|
|
|
* nodeModifyTable.c.
|
|
|
|
*/
|
|
|
|
if (hufd.cmax != estate->es_output_cid)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
|
|
|
|
errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
|
|
|
|
errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
|
|
|
|
|
2002-09-24 00:57:44 +02:00
|
|
|
/* treat it as deleted; do not process */
|
1998-12-15 13:47:01 +01:00
|
|
|
ReleaseBuffer(buffer);
|
2002-11-23 04:59:09 +01:00
|
|
|
return NULL;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1998-12-15 13:47:01 +01:00
|
|
|
case HeapTupleMayBeUpdated:
|
|
|
|
break;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1998-12-15 13:47:01 +01:00
|
|
|
case HeapTupleUpdated:
|
|
|
|
ReleaseBuffer(buffer);
|
2010-09-11 20:38:58 +02:00
|
|
|
if (IsolationUsesXactSnapshot())
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
|
2003-07-28 02:09:16 +02:00
|
|
|
errmsg("could not serialize access due to concurrent update")));
|
2012-10-26 21:55:36 +02:00
|
|
|
if (!ItemPointerEquals(&hufd.ctid, &tuple.t_self))
|
1999-01-29 10:23:17 +01:00
|
|
|
{
|
2005-08-20 02:40:32 +02:00
|
|
|
/* it was updated, so look at the updated version */
|
|
|
|
TupleTableSlot *epqslot;
|
|
|
|
|
|
|
|
epqslot = EvalPlanQual(estate,
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
epqstate,
|
|
|
|
relation,
|
2005-08-20 02:40:32 +02:00
|
|
|
relinfo->ri_RangeTableIndex,
|
Improve concurrency of foreign key locking
This patch introduces two additional lock modes for tuples: "SELECT FOR
KEY SHARE" and "SELECT FOR NO KEY UPDATE". These don't block each
other, in contrast with already existing "SELECT FOR SHARE" and "SELECT
FOR UPDATE". UPDATE commands that do not modify the values stored in
the columns that are part of the key of the tuple now grab a SELECT FOR
NO KEY UPDATE lock on the tuple, allowing them to proceed concurrently
with tuple locks of the FOR KEY SHARE variety.
Foreign key triggers now use FOR KEY SHARE instead of FOR SHARE; this
means the concurrency improvement applies to them, which is the whole
point of this patch.
The added tuple lock semantics require some rejiggering of the multixact
module, so that the locking level that each transaction is holding can
be stored alongside its Xid. Also, multixacts now need to persist
across server restarts and crashes, because they can now represent not
only tuple locks, but also tuple updates. This means we need more
careful tracking of lifetime of pg_multixact SLRU files; since they now
persist longer, we require more infrastructure to figure out when they
can be removed. pg_upgrade also needs to be careful to copy
pg_multixact files over from the old server to the new, or at least part
of multixact.c state, depending on the versions of the old and new
servers.
Tuple time qualification rules (HeapTupleSatisfies routines) need to be
careful not to consider tuples with the "is multi" infomask bit set as
being only locked; they might need to look up MultiXact values (i.e.
possibly do pg_multixact I/O) to find out the Xid that updated a tuple,
whereas they previously were assured to only use information readily
available from the tuple header. This is considered acceptable, because
the extra I/O would involve cases that would previously cause some
commands to block waiting for concurrent transactions to finish.
Another important change is the fact that locking tuples that have
previously been updated causes the future versions to be marked as
locked, too; this is essential for correctness of foreign key checks.
This causes additional WAL-logging, also (there was previously a single
WAL record for a locked tuple; now there are as many as updated copies
of the tuple there exist.)
With all this in place, contention related to tuples being checked by
foreign key rules should be much reduced.
As a bonus, the old behavior that a subtransaction grabbing a stronger
tuple lock than the parent (sub)transaction held on a given tuple and
later aborting caused the weaker lock to be lost, has been fixed.
Many new spec files were added for isolation tester framework, to ensure
overall behavior is sane. There's probably room for several more tests.
There were several reviewers of this patch; in particular, Noah Misch
and Andres Freund spent considerable time in it. Original idea for the
patch came from Simon Riggs, after a problem report by Joel Jacobson.
Most code is from me, with contributions from Marti Raudsepp, Alexander
Shulgin, Noah Misch and Andres Freund.
This patch was discussed in several pgsql-hackers threads; the most
important start at the following message-ids:
AANLkTimo9XVcEzfiBR-ut3KVNDkjm2Vxh+t8kAmWjPuv@mail.gmail.com
1290721684-sup-3951@alvh.no-ip.org
1294953201-sup-2099@alvh.no-ip.org
1320343602-sup-2290@alvh.no-ip.org
1339690386-sup-8927@alvh.no-ip.org
4FE5FF020200002500048A3D@gw.wicourts.gov
4FEAB90A0200002500048B7D@gw.wicourts.gov
2013-01-23 16:04:59 +01:00
|
|
|
lockmode,
|
2012-10-26 21:55:36 +02:00
|
|
|
&hufd.ctid,
|
|
|
|
hufd.xmax);
|
2005-08-20 02:40:32 +02:00
|
|
|
if (!TupIsNull(epqslot))
|
1999-01-29 10:23:17 +01:00
|
|
|
{
|
2012-10-26 21:55:36 +02:00
|
|
|
*tid = hufd.ctid;
|
1999-01-29 12:56:01 +01:00
|
|
|
*newSlot = epqslot;
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
|
|
|
|
/*
|
|
|
|
* EvalPlanQual already locked the tuple, but we
|
2010-02-26 03:01:40 +01:00
|
|
|
* re-call heap_lock_tuple anyway as an easy way of
|
|
|
|
* re-fetching the correct tuple. Speed is hardly a
|
|
|
|
* criterion in this path anyhow.
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
*/
|
1999-01-29 10:23:17 +01:00
|
|
|
goto ltrmark;
|
|
|
|
}
|
|
|
|
}
|
1999-05-25 18:15:34 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* if tuple was deleted or PlanQual failed for updated tuple -
|
Re-implement EvalPlanQual processing to improve its performance and eliminate
a lot of strange behaviors that occurred in join cases. We now identify the
"current" row for every joined relation in UPDATE, DELETE, and SELECT FOR
UPDATE/SHARE queries. If an EvalPlanQual recheck is necessary, we jam the
appropriate row into each scan node in the rechecking plan, forcing it to emit
only that one row. The former behavior could rescan the whole of each joined
relation for each recheck, which was terrible for performance, and what's much
worse could result in duplicated output tuples.
Also, the original implementation of EvalPlanQual could not re-use the recheck
execution tree --- it had to go through a full executor init and shutdown for
every row to be tested. To avoid this overhead, I've associated a special
runtime Param with each LockRows or ModifyTable plan node, and arranged to
make every scan node below such a node depend on that Param. Thus, by
signaling a change in that Param, the EPQ machinery can just rescan the
already-built test plan.
This patch also adds a prohibition on set-returning functions in the
targetlist of SELECT FOR UPDATE/SHARE. This is needed to avoid the
duplicate-output-tuple problem. It seems fairly reasonable since the
other restrictions on SELECT FOR UPDATE are meant to ensure that there
is a unique correspondence between source tuples and result tuples,
which an output SRF destroys as much as anything else does.
2009-10-26 03:26:45 +01:00
|
|
|
* we must not process this tuple!
|
1999-01-29 10:23:17 +01:00
|
|
|
*/
|
2002-11-23 04:59:09 +01:00
|
|
|
return NULL;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
Add support for INSERT ... ON CONFLICT DO NOTHING/UPDATE.
The newly added ON CONFLICT clause allows to specify an alternative to
raising a unique or exclusion constraint violation error when inserting.
ON CONFLICT refers to constraints that can either be specified using a
inference clause (by specifying the columns of a unique constraint) or
by naming a unique or exclusion constraint. DO NOTHING avoids the
constraint violation, without touching the pre-existing row. DO UPDATE
SET ... [WHERE ...] updates the pre-existing tuple, and has access to
both the tuple proposed for insertion and the existing tuple; the
optional WHERE clause can be used to prevent an update from being
executed. The UPDATE SET and WHERE clauses have access to the tuple
proposed for insertion using the "magic" EXCLUDED alias, and to the
pre-existing tuple using the table name or its alias.
This feature is often referred to as upsert.
This is implemented using a new infrastructure called "speculative
insertion". It is an optimistic variant of regular insertion that first
does a pre-check for existing tuples and then attempts an insert. If a
violating tuple was inserted concurrently, the speculatively inserted
tuple is deleted and a new attempt is made. If the pre-check finds a
matching tuple the alternative DO NOTHING or DO UPDATE action is taken.
If the insertion succeeds without detecting a conflict, the tuple is
deemed inserted.
To handle the possible ambiguity between the excluded alias and a table
named excluded, and for convenience with long relation names, INSERT
INTO now can alias its target table.
Bumps catversion as stored rules change.
Author: Peter Geoghegan, with significant contributions from Heikki
Linnakangas and Andres Freund. Testing infrastructure by Jeff Janes.
Reviewed-By: Heikki Linnakangas, Andres Freund, Robert Haas, Simon Riggs,
Dean Rasheed, Stephen Frost and many others.
2015-05-08 05:31:36 +02:00
|
|
|
case HeapTupleInvisible:
|
|
|
|
elog(ERROR, "attempted to lock invisible tuple");
|
|
|
|
|
1998-12-15 13:47:01 +01:00
|
|
|
default:
|
|
|
|
ReleaseBuffer(buffer);
|
2005-08-20 02:40:32 +02:00
|
|
|
elog(ERROR, "unrecognized heap_lock_tuple status: %u", test);
|
2003-07-20 23:56:35 +02:00
|
|
|
return NULL; /* keep compiler quiet */
|
1998-12-15 13:47:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-07-13 22:45:47 +02:00
|
|
|
Page page;
|
1999-05-25 18:15:34 +02:00
|
|
|
ItemId lp;
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1998-12-15 13:47:01 +01:00
|
|
|
buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
|
1997-09-11 09:24:37 +02:00
|
|
|
|
2012-11-30 19:55:55 +01:00
|
|
|
/*
|
|
|
|
* Although we already know this tuple is valid, we must lock the
|
|
|
|
* buffer to ensure that no one has a buffer cleanup lock; otherwise
|
|
|
|
* they might move the tuple while we try to copy it. But we can
|
|
|
|
* release the lock before actually doing the heap_copytuple call,
|
|
|
|
* since holding pin is sufficient to prevent anyone from getting a
|
|
|
|
* cleanup lock they don't already hold.
|
|
|
|
*/
|
|
|
|
LockBuffer(buffer, BUFFER_LOCK_SHARE);
|
|
|
|
|
2016-04-20 15:31:19 +02:00
|
|
|
page = BufferGetPage(buffer);
|
2008-07-13 22:45:47 +02:00
|
|
|
lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
|
1998-12-15 13:47:01 +01:00
|
|
|
|
2007-09-13 00:10:26 +02:00
|
|
|
Assert(ItemIdIsNormal(lp));
|
1998-12-15 13:47:01 +01:00
|
|
|
|
2008-07-13 22:45:47 +02:00
|
|
|
tuple.t_data = (HeapTupleHeader) PageGetItem(page, lp);
|
1998-12-15 13:47:01 +01:00
|
|
|
tuple.t_len = ItemIdGetLength(lp);
|
|
|
|
tuple.t_self = *tid;
|
2005-08-20 02:40:32 +02:00
|
|
|
tuple.t_tableOid = RelationGetRelid(relation);
|
2012-11-30 19:55:55 +01:00
|
|
|
|
|
|
|
LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
|
1997-09-11 09:24:37 +02:00
|
|
|
}
|
|
|
|
|
1998-11-27 20:52:36 +01:00
|
|
|
result = heap_copytuple(&tuple);
|
1998-12-15 13:47:01 +01:00
|
|
|
ReleaseBuffer(buffer);
|
1997-09-11 09:24:37 +02:00
|
|
|
|
1998-11-27 20:52:36 +01:00
|
|
|
return result;
|
1997-09-11 09:24:37 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2009-10-15 00:14:25 +02:00
|
|
|
/*
|
|
|
|
* Is trigger enabled to fire?
|
|
|
|
*/
|
|
|
|
static bool
|
2009-11-20 21:38:12 +01:00
|
|
|
TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
|
|
|
|
Trigger *trigger, TriggerEvent event,
|
|
|
|
Bitmapset *modifiedCols,
|
|
|
|
HeapTuple oldtup, HeapTuple newtup)
|
2009-10-15 00:14:25 +02:00
|
|
|
{
|
|
|
|
/* Check replication-role-dependent enable state */
|
|
|
|
if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
|
|
|
|
{
|
|
|
|
if (trigger->tgenabled == TRIGGER_FIRES_ON_ORIGIN ||
|
|
|
|
trigger->tgenabled == TRIGGER_DISABLED)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
else /* ORIGIN or LOCAL role */
|
|
|
|
{
|
|
|
|
if (trigger->tgenabled == TRIGGER_FIRES_ON_REPLICA ||
|
|
|
|
trigger->tgenabled == TRIGGER_DISABLED)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Check for column-specific trigger (only possible for UPDATE, and in
|
|
|
|
* fact we *must* ignore tgattr for other event types)
|
|
|
|
*/
|
|
|
|
if (trigger->tgnattr > 0 && TRIGGER_FIRED_BY_UPDATE(event))
|
|
|
|
{
|
|
|
|
int i;
|
|
|
|
bool modified;
|
|
|
|
|
|
|
|
modified = false;
|
|
|
|
for (i = 0; i < trigger->tgnattr; i++)
|
|
|
|
{
|
|
|
|
if (bms_is_member(trigger->tgattr[i] - FirstLowInvalidHeapAttributeNumber,
|
|
|
|
modifiedCols))
|
|
|
|
{
|
|
|
|
modified = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!modified)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2009-11-20 21:38:12 +01:00
|
|
|
/* Check for WHEN clause */
|
|
|
|
if (trigger->tgqual)
|
|
|
|
{
|
|
|
|
TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
|
Faster expression evaluation and targetlist projection.
This replaces the old, recursive tree-walk based evaluation, with
non-recursive, opcode dispatch based, expression evaluation.
Projection is now implemented as part of expression evaluation.
This both leads to significant performance improvements, and makes
future just-in-time compilation of expressions easier.
The speed gains primarily come from:
- non-recursive implementation reduces stack usage / overhead
- simple sub-expressions are implemented with a single jump, without
function calls
- sharing some state between different sub-expressions
- reduced amount of indirect/hard to predict memory accesses by laying
out operation metadata sequentially; including the avoidance of
nearly all of the previously used linked lists
- more code has been moved to expression initialization, avoiding
constant re-checks at evaluation time
Future just-in-time compilation (JIT) has become easier, as
demonstrated by released patches intended to be merged in a later
release, for primarily two reasons: Firstly, due to a stricter split
between expression initialization and evaluation, less code has to be
handled by the JIT. Secondly, due to the non-recursive nature of the
generated "instructions", less performance-critical code-paths can
easily be shared between interpreted and compiled evaluation.
The new framework allows for significant future optimizations. E.g.:
- basic infrastructure for to later reduce the per executor-startup
overhead of expression evaluation, by caching state in prepared
statements. That'd be helpful in OLTPish scenarios where
initialization overhead is measurable.
- optimizing the generated "code". A number of proposals for potential
work has already been made.
- optimizing the interpreter. Similarly a number of proposals have
been made here too.
The move of logic into the expression initialization step leads to some
backward-incompatible changes:
- Function permission checks are now done during expression
initialization, whereas previously they were done during
execution. In edge cases this can lead to errors being raised that
previously wouldn't have been, e.g. a NULL array being coerced to a
different array type previously didn't perform checks.
- The set of domain constraints to be checked, is now evaluated once
during expression initialization, previously it was re-built
every time a domain check was evaluated. For normal queries this
doesn't change much, but e.g. for plpgsql functions, which caches
ExprStates, the old set could stick around longer. The behavior
around might still change.
Author: Andres Freund, with significant changes by Tom Lane,
changes by Heikki Linnakangas
Reviewed-By: Tom Lane, Heikki Linnakangas
Discussion: https://postgr.es/m/20161206034955.bh33paeralxbtluv@alap3.anarazel.de
2017-03-14 23:45:36 +01:00
|
|
|
ExprState **predicate;
|
2009-11-20 21:38:12 +01:00
|
|
|
ExprContext *econtext;
|
|
|
|
TupleTableSlot *oldslot = NULL;
|
|
|
|
TupleTableSlot *newslot = NULL;
|
|
|
|
MemoryContext oldContext;
|
|
|
|
int i;
|
|
|
|
|
|
|
|
Assert(estate != NULL);
|
|
|
|
|
|
|
|
/*
|
2010-02-26 03:01:40 +01:00
|
|
|
* trigger is an element of relinfo->ri_TrigDesc->triggers[]; find the
|
|
|
|
* matching element of relinfo->ri_TrigWhenExprs[]
|
2009-11-20 21:38:12 +01:00
|
|
|
*/
|
|
|
|
i = trigger - relinfo->ri_TrigDesc->triggers;
|
|
|
|
predicate = &relinfo->ri_TrigWhenExprs[i];
|
|
|
|
|
|
|
|
/*
|
|
|
|
* If first time through for this WHEN expression, build expression
|
|
|
|
* nodetrees for it. Keep them in the per-query memory context so
|
|
|
|
* they'll survive throughout the query.
|
|
|
|
*/
|
Faster expression evaluation and targetlist projection.
This replaces the old, recursive tree-walk based evaluation, with
non-recursive, opcode dispatch based, expression evaluation.
Projection is now implemented as part of expression evaluation.
This both leads to significant performance improvements, and makes
future just-in-time compilation of expressions easier.
The speed gains primarily come from:
- non-recursive implementation reduces stack usage / overhead
- simple sub-expressions are implemented with a single jump, without
function calls
- sharing some state between different sub-expressions
- reduced amount of indirect/hard to predict memory accesses by laying
out operation metadata sequentially; including the avoidance of
nearly all of the previously used linked lists
- more code has been moved to expression initialization, avoiding
constant re-checks at evaluation time
Future just-in-time compilation (JIT) has become easier, as
demonstrated by released patches intended to be merged in a later
release, for primarily two reasons: Firstly, due to a stricter split
between expression initialization and evaluation, less code has to be
handled by the JIT. Secondly, due to the non-recursive nature of the
generated "instructions", less performance-critical code-paths can
easily be shared between interpreted and compiled evaluation.
The new framework allows for significant future optimizations. E.g.:
- basic infrastructure for to later reduce the per executor-startup
overhead of expression evaluation, by caching state in prepared
statements. That'd be helpful in OLTPish scenarios where
initialization overhead is measurable.
- optimizing the generated "code". A number of proposals for potential
work has already been made.
- optimizing the interpreter. Similarly a number of proposals have
been made here too.
The move of logic into the expression initialization step leads to some
backward-incompatible changes:
- Function permission checks are now done during expression
initialization, whereas previously they were done during
execution. In edge cases this can lead to errors being raised that
previously wouldn't have been, e.g. a NULL array being coerced to a
different array type previously didn't perform checks.
- The set of domain constraints to be checked, is now evaluated once
during expression initialization, previously it was re-built
every time a domain check was evaluated. For normal queries this
doesn't change much, but e.g. for plpgsql functions, which caches
ExprStates, the old set could stick around longer. The behavior
around might still change.
Author: Andres Freund, with significant changes by Tom Lane,
changes by Heikki Linnakangas
Reviewed-By: Tom Lane, Heikki Linnakangas
Discussion: https://postgr.es/m/20161206034955.bh33paeralxbtluv@alap3.anarazel.de
2017-03-14 23:45:36 +01:00
|
|
|
if (*predicate == NULL)
|
2009-11-20 21:38:12 +01:00
|
|
|
{
|
2010-02-26 03:01:40 +01:00
|
|
|
Node *tgqual;
|
2009-11-20 21:38:12 +01:00
|
|
|
|
|
|
|
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
|
|
|
|
tgqual = stringToNode(trigger->tgqual);
|
2011-10-11 20:20:06 +02:00
|
|
|
/* Change references to OLD and NEW to INNER_VAR and OUTER_VAR */
|
|
|
|
ChangeVarNodes(tgqual, PRS2_OLD_VARNO, INNER_VAR, 0);
|
|
|
|
ChangeVarNodes(tgqual, PRS2_NEW_VARNO, OUTER_VAR, 0);
|
Faster expression evaluation and targetlist projection.
This replaces the old, recursive tree-walk based evaluation, with
non-recursive, opcode dispatch based, expression evaluation.
Projection is now implemented as part of expression evaluation.
This both leads to significant performance improvements, and makes
future just-in-time compilation of expressions easier.
The speed gains primarily come from:
- non-recursive implementation reduces stack usage / overhead
- simple sub-expressions are implemented with a single jump, without
function calls
- sharing some state between different sub-expressions
- reduced amount of indirect/hard to predict memory accesses by laying
out operation metadata sequentially; including the avoidance of
nearly all of the previously used linked lists
- more code has been moved to expression initialization, avoiding
constant re-checks at evaluation time
Future just-in-time compilation (JIT) has become easier, as
demonstrated by released patches intended to be merged in a later
release, for primarily two reasons: Firstly, due to a stricter split
between expression initialization and evaluation, less code has to be
handled by the JIT. Secondly, due to the non-recursive nature of the
generated "instructions", less performance-critical code-paths can
easily be shared between interpreted and compiled evaluation.
The new framework allows for significant future optimizations. E.g.:
- basic infrastructure for to later reduce the per executor-startup
overhead of expression evaluation, by caching state in prepared
statements. That'd be helpful in OLTPish scenarios where
initialization overhead is measurable.
- optimizing the generated "code". A number of proposals for potential
work has already been made.
- optimizing the interpreter. Similarly a number of proposals have
been made here too.
The move of logic into the expression initialization step leads to some
backward-incompatible changes:
- Function permission checks are now done during expression
initialization, whereas previously they were done during
execution. In edge cases this can lead to errors being raised that
previously wouldn't have been, e.g. a NULL array being coerced to a
different array type previously didn't perform checks.
- The set of domain constraints to be checked, is now evaluated once
during expression initialization, previously it was re-built
every time a domain check was evaluated. For normal queries this
doesn't change much, but e.g. for plpgsql functions, which caches
ExprStates, the old set could stick around longer. The behavior
around might still change.
Author: Andres Freund, with significant changes by Tom Lane,
changes by Heikki Linnakangas
Reviewed-By: Tom Lane, Heikki Linnakangas
Discussion: https://postgr.es/m/20161206034955.bh33paeralxbtluv@alap3.anarazel.de
2017-03-14 23:45:36 +01:00
|
|
|
/* ExecPrepareQual wants implicit-AND form */
|
2009-11-20 21:38:12 +01:00
|
|
|
tgqual = (Node *) make_ands_implicit((Expr *) tgqual);
|
Faster expression evaluation and targetlist projection.
This replaces the old, recursive tree-walk based evaluation, with
non-recursive, opcode dispatch based, expression evaluation.
Projection is now implemented as part of expression evaluation.
This both leads to significant performance improvements, and makes
future just-in-time compilation of expressions easier.
The speed gains primarily come from:
- non-recursive implementation reduces stack usage / overhead
- simple sub-expressions are implemented with a single jump, without
function calls
- sharing some state between different sub-expressions
- reduced amount of indirect/hard to predict memory accesses by laying
out operation metadata sequentially; including the avoidance of
nearly all of the previously used linked lists
- more code has been moved to expression initialization, avoiding
constant re-checks at evaluation time
Future just-in-time compilation (JIT) has become easier, as
demonstrated by released patches intended to be merged in a later
release, for primarily two reasons: Firstly, due to a stricter split
between expression initialization and evaluation, less code has to be
handled by the JIT. Secondly, due to the non-recursive nature of the
generated "instructions", less performance-critical code-paths can
easily be shared between interpreted and compiled evaluation.
The new framework allows for significant future optimizations. E.g.:
- basic infrastructure for to later reduce the per executor-startup
overhead of expression evaluation, by caching state in prepared
statements. That'd be helpful in OLTPish scenarios where
initialization overhead is measurable.
- optimizing the generated "code". A number of proposals for potential
work has already been made.
- optimizing the interpreter. Similarly a number of proposals have
been made here too.
The move of logic into the expression initialization step leads to some
backward-incompatible changes:
- Function permission checks are now done during expression
initialization, whereas previously they were done during
execution. In edge cases this can lead to errors being raised that
previously wouldn't have been, e.g. a NULL array being coerced to a
different array type previously didn't perform checks.
- The set of domain constraints to be checked, is now evaluated once
during expression initialization, previously it was re-built
every time a domain check was evaluated. For normal queries this
doesn't change much, but e.g. for plpgsql functions, which caches
ExprStates, the old set could stick around longer. The behavior
around might still change.
Author: Andres Freund, with significant changes by Tom Lane,
changes by Heikki Linnakangas
Reviewed-By: Tom Lane, Heikki Linnakangas
Discussion: https://postgr.es/m/20161206034955.bh33paeralxbtluv@alap3.anarazel.de
2017-03-14 23:45:36 +01:00
|
|
|
*predicate = ExecPrepareQual((List *) tgqual, estate);
|
2009-11-20 21:38:12 +01:00
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* We will use the EState's per-tuple context for evaluating WHEN
|
|
|
|
* expressions (creating it if it's not already there).
|
|
|
|
*/
|
|
|
|
econtext = GetPerTupleExprContext(estate);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Put OLD and NEW tuples into tupleslots for expression evaluation.
|
|
|
|
* These slots can be shared across the whole estate, but be careful
|
|
|
|
* that they have the current resultrel's tupdesc.
|
|
|
|
*/
|
|
|
|
if (HeapTupleIsValid(oldtup))
|
|
|
|
{
|
|
|
|
if (estate->es_trig_oldtup_slot == NULL)
|
|
|
|
{
|
|
|
|
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
|
|
|
|
estate->es_trig_oldtup_slot = ExecInitExtraTupleSlot(estate);
|
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
}
|
|
|
|
oldslot = estate->es_trig_oldtup_slot;
|
|
|
|
if (oldslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(oldslot, tupdesc);
|
|
|
|
ExecStoreTuple(oldtup, oldslot, InvalidBuffer, false);
|
|
|
|
}
|
|
|
|
if (HeapTupleIsValid(newtup))
|
|
|
|
{
|
2011-08-22 00:15:55 +02:00
|
|
|
if (estate->es_trig_newtup_slot == NULL)
|
2009-11-20 21:38:12 +01:00
|
|
|
{
|
|
|
|
oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
|
2011-08-22 00:15:55 +02:00
|
|
|
estate->es_trig_newtup_slot = ExecInitExtraTupleSlot(estate);
|
2009-11-20 21:38:12 +01:00
|
|
|
MemoryContextSwitchTo(oldContext);
|
|
|
|
}
|
2011-08-22 00:15:55 +02:00
|
|
|
newslot = estate->es_trig_newtup_slot;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (newslot->tts_tupleDescriptor != tupdesc)
|
|
|
|
ExecSetSlotDescriptor(newslot, tupdesc);
|
|
|
|
ExecStoreTuple(newtup, newslot, InvalidBuffer, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Finally evaluate the expression, making the old and/or new tuples
|
2011-10-11 20:20:06 +02:00
|
|
|
* available as INNER_VAR/OUTER_VAR respectively.
|
2009-11-20 21:38:12 +01:00
|
|
|
*/
|
|
|
|
econtext->ecxt_innertuple = oldslot;
|
|
|
|
econtext->ecxt_outertuple = newslot;
|
Faster expression evaluation and targetlist projection.
This replaces the old, recursive tree-walk based evaluation, with
non-recursive, opcode dispatch based, expression evaluation.
Projection is now implemented as part of expression evaluation.
This both leads to significant performance improvements, and makes
future just-in-time compilation of expressions easier.
The speed gains primarily come from:
- non-recursive implementation reduces stack usage / overhead
- simple sub-expressions are implemented with a single jump, without
function calls
- sharing some state between different sub-expressions
- reduced amount of indirect/hard to predict memory accesses by laying
out operation metadata sequentially; including the avoidance of
nearly all of the previously used linked lists
- more code has been moved to expression initialization, avoiding
constant re-checks at evaluation time
Future just-in-time compilation (JIT) has become easier, as
demonstrated by released patches intended to be merged in a later
release, for primarily two reasons: Firstly, due to a stricter split
between expression initialization and evaluation, less code has to be
handled by the JIT. Secondly, due to the non-recursive nature of the
generated "instructions", less performance-critical code-paths can
easily be shared between interpreted and compiled evaluation.
The new framework allows for significant future optimizations. E.g.:
- basic infrastructure for to later reduce the per executor-startup
overhead of expression evaluation, by caching state in prepared
statements. That'd be helpful in OLTPish scenarios where
initialization overhead is measurable.
- optimizing the generated "code". A number of proposals for potential
work has already been made.
- optimizing the interpreter. Similarly a number of proposals have
been made here too.
The move of logic into the expression initialization step leads to some
backward-incompatible changes:
- Function permission checks are now done during expression
initialization, whereas previously they were done during
execution. In edge cases this can lead to errors being raised that
previously wouldn't have been, e.g. a NULL array being coerced to a
different array type previously didn't perform checks.
- The set of domain constraints to be checked, is now evaluated once
during expression initialization, previously it was re-built
every time a domain check was evaluated. For normal queries this
doesn't change much, but e.g. for plpgsql functions, which caches
ExprStates, the old set could stick around longer. The behavior
around might still change.
Author: Andres Freund, with significant changes by Tom Lane,
changes by Heikki Linnakangas
Reviewed-By: Tom Lane, Heikki Linnakangas
Discussion: https://postgr.es/m/20161206034955.bh33paeralxbtluv@alap3.anarazel.de
2017-03-14 23:45:36 +01:00
|
|
|
if (!ExecQual(*predicate, econtext))
|
2009-11-20 21:38:12 +01:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2009-10-15 00:14:25 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
1999-09-29 18:06:40 +02:00
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* After-trigger stuff
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
2004-09-10 20:40:09 +02:00
|
|
|
* The AfterTriggersData struct holds data about pending AFTER trigger events
|
|
|
|
* during the current transaction tree. (BEFORE triggers are fired
|
|
|
|
* immediately so we don't need any persistent state about them.) The struct
|
|
|
|
* and most of its subsidiary data are kept in TopTransactionContext; however
|
2008-10-25 01:42:35 +02:00
|
|
|
* the individual event records are kept in a separate sub-context. This is
|
|
|
|
* done mainly so that it's easy to tell from a memory context dump how much
|
|
|
|
* space is being eaten by trigger events.
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Because the list of pending events can grow large, we go to some
|
|
|
|
* considerable effort to minimize per-event memory consumption. The event
|
|
|
|
* records are grouped into chunks and common data for similar events in the
|
|
|
|
* same chunk is only stored once.
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
|
|
|
* XXX We need to be able to save the per-event data in a file if it grows too
|
|
|
|
* large.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/* Per-trigger SET CONSTRAINT status */
|
|
|
|
typedef struct SetConstraintTriggerData
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
Oid sct_tgoid;
|
|
|
|
bool sct_tgisdeferred;
|
|
|
|
} SetConstraintTriggerData;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
typedef struct SetConstraintTriggerData *SetConstraintTrigger;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* SET CONSTRAINT intra-transaction status.
|
2001-11-16 17:31:16 +01:00
|
|
|
*
|
2004-07-01 02:52:04 +02:00
|
|
|
* We make this a single palloc'd object so it can be copied and freed easily.
|
2003-08-04 02:43:34 +02:00
|
|
|
*
|
2004-07-01 02:52:04 +02:00
|
|
|
* all_isset and all_isdeferred are used to keep track
|
|
|
|
* of SET CONSTRAINTS ALL {DEFERRED, IMMEDIATE}.
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2004-07-01 02:52:04 +02:00
|
|
|
* trigstates[] stores per-trigger tgisdeferred settings.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
typedef struct SetConstraintStateData
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-08-29 07:07:03 +02:00
|
|
|
bool all_isset;
|
|
|
|
bool all_isdeferred;
|
|
|
|
int numstates; /* number of trigstates[] entries in use */
|
|
|
|
int numalloc; /* allocated size of trigstates[] */
|
2015-02-20 23:32:01 +01:00
|
|
|
SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER];
|
2004-09-10 20:40:09 +02:00
|
|
|
} SetConstraintStateData;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
typedef SetConstraintStateData *SetConstraintState;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
|
|
|
* Per-trigger-event data
|
|
|
|
*
|
2008-10-25 01:42:35 +02:00
|
|
|
* The actual per-event data, AfterTriggerEventData, includes DONE/IN_PROGRESS
|
2014-03-23 07:16:34 +01:00
|
|
|
* status bits and up to two tuple CTIDs. Each event record also has an
|
|
|
|
* associated AfterTriggerSharedData that is shared across all instances of
|
|
|
|
* similar events within a "chunk".
|
2008-10-25 01:42:35 +02:00
|
|
|
*
|
2014-03-23 07:16:34 +01:00
|
|
|
* For row-level triggers, we arrange not to waste storage on unneeded ctid
|
|
|
|
* fields. Updates of regular tables use two; inserts and deletes of regular
|
|
|
|
* tables use one; foreign tables always use zero and save the tuple(s) to a
|
|
|
|
* tuplestore. AFTER_TRIGGER_FDW_FETCH directs AfterTriggerExecute() to
|
|
|
|
* retrieve a fresh tuple or pair of tuples from that tuplestore, while
|
|
|
|
* AFTER_TRIGGER_FDW_REUSE directs it to use the most-recently-retrieved
|
|
|
|
* tuple(s). This permits storing tuples once regardless of the number of
|
|
|
|
* row-level triggers on a foreign table.
|
|
|
|
*
|
|
|
|
* Statement-level triggers always bear AFTER_TRIGGER_1CTID, though they
|
|
|
|
* require no ctid field. We lack the flag bit space to neatly represent that
|
|
|
|
* distinct case, and it seems unlikely to be worth much trouble.
|
2008-10-25 01:42:35 +02:00
|
|
|
*
|
|
|
|
* Note: ats_firing_id is initially zero and is set to something else when
|
|
|
|
* AFTER_TRIGGER_IN_PROGRESS is set. It indicates which trigger firing
|
|
|
|
* cycle the trigger will be fired in (or was fired in, if DONE is set).
|
|
|
|
* Although this is mutable state, we can keep it in AfterTriggerSharedData
|
|
|
|
* because all instances of the same type of event in a given event list will
|
|
|
|
* be fired at the same time, if they were queued between the same firing
|
2014-05-06 18:12:18 +02:00
|
|
|
* cycles. So we need only ensure that ats_firing_id is zero when attaching
|
2008-10-25 01:42:35 +02:00
|
|
|
* a new event to an existing AfterTriggerSharedData record.
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
typedef uint32 TriggerFlags;
|
|
|
|
|
2009-06-11 16:49:15 +02:00
|
|
|
#define AFTER_TRIGGER_OFFSET 0x0FFFFFFF /* must be low-order
|
|
|
|
* bits */
|
2014-03-23 07:16:34 +01:00
|
|
|
#define AFTER_TRIGGER_DONE 0x10000000
|
|
|
|
#define AFTER_TRIGGER_IN_PROGRESS 0x20000000
|
|
|
|
/* bits describing the size and tuple sources of this event */
|
|
|
|
#define AFTER_TRIGGER_FDW_REUSE 0x00000000
|
|
|
|
#define AFTER_TRIGGER_FDW_FETCH 0x80000000
|
|
|
|
#define AFTER_TRIGGER_1CTID 0x40000000
|
|
|
|
#define AFTER_TRIGGER_2CTID 0xC0000000
|
|
|
|
#define AFTER_TRIGGER_TUP_BITS 0xC0000000
|
2008-10-25 01:42:35 +02:00
|
|
|
|
|
|
|
typedef struct AfterTriggerSharedData *AfterTriggerShared;
|
|
|
|
|
|
|
|
typedef struct AfterTriggerSharedData
|
|
|
|
{
|
|
|
|
TriggerEvent ats_event; /* event type indicator, see trigger.h */
|
|
|
|
Oid ats_tgoid; /* the trigger's ID */
|
|
|
|
Oid ats_relid; /* the relation it's on */
|
|
|
|
CommandId ats_firing_id; /* ID for firing cycle */
|
|
|
|
} AfterTriggerSharedData;
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
typedef struct AfterTriggerEventData *AfterTriggerEvent;
|
2003-06-25 01:25:44 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
typedef struct AfterTriggerEventData
|
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
TriggerFlags ate_flags; /* status bits and offset to shared data */
|
|
|
|
ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
|
|
|
|
ItemPointerData ate_ctid2; /* new updated tuple */
|
2004-09-10 20:40:09 +02:00
|
|
|
} AfterTriggerEventData;
|
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
/* AfterTriggerEventData, minus ate_ctid2 */
|
2008-10-25 01:42:35 +02:00
|
|
|
typedef struct AfterTriggerEventDataOneCtid
|
|
|
|
{
|
|
|
|
TriggerFlags ate_flags; /* status bits and offset to shared data */
|
|
|
|
ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
|
2011-04-10 17:42:00 +02:00
|
|
|
} AfterTriggerEventDataOneCtid;
|
2008-10-25 01:42:35 +02:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
/* AfterTriggerEventData, minus ate_ctid1 and ate_ctid2 */
|
|
|
|
typedef struct AfterTriggerEventDataZeroCtids
|
|
|
|
{
|
|
|
|
TriggerFlags ate_flags; /* status bits and offset to shared data */
|
2014-05-06 18:12:18 +02:00
|
|
|
} AfterTriggerEventDataZeroCtids;
|
2014-03-23 07:16:34 +01:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
#define SizeofTriggerEvent(evt) \
|
2014-03-23 07:16:34 +01:00
|
|
|
(((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ? \
|
|
|
|
sizeof(AfterTriggerEventData) : \
|
|
|
|
((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_1CTID ? \
|
|
|
|
sizeof(AfterTriggerEventDataOneCtid) : \
|
|
|
|
sizeof(AfterTriggerEventDataZeroCtids))
|
2008-10-25 01:42:35 +02:00
|
|
|
|
|
|
|
#define GetTriggerSharedData(evt) \
|
|
|
|
((AfterTriggerShared) ((char *) (evt) + ((evt)->ate_flags & AFTER_TRIGGER_OFFSET)))
|
|
|
|
|
|
|
|
/*
|
|
|
|
* To avoid palloc overhead, we keep trigger events in arrays in successively-
|
|
|
|
* larger chunks (a slightly more sophisticated version of an expansible
|
2014-05-06 18:12:18 +02:00
|
|
|
* array). The space between CHUNK_DATA_START and freeptr is occupied by
|
2008-10-25 01:42:35 +02:00
|
|
|
* AfterTriggerEventData records; the space between endfree and endptr is
|
|
|
|
* occupied by AfterTriggerSharedData records.
|
|
|
|
*/
|
|
|
|
typedef struct AfterTriggerEventChunk
|
|
|
|
{
|
2009-06-11 16:49:15 +02:00
|
|
|
struct AfterTriggerEventChunk *next; /* list link */
|
2008-10-25 01:42:35 +02:00
|
|
|
char *freeptr; /* start of free space in chunk */
|
|
|
|
char *endfree; /* end of free space in chunk */
|
|
|
|
char *endptr; /* end of chunk */
|
|
|
|
/* event data follows here */
|
|
|
|
} AfterTriggerEventChunk;
|
|
|
|
|
|
|
|
#define CHUNK_DATA_START(cptr) ((char *) (cptr) + MAXALIGN(sizeof(AfterTriggerEventChunk)))
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/* A list of events */
|
|
|
|
typedef struct AfterTriggerEventList
|
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEventChunk *head;
|
|
|
|
AfterTriggerEventChunk *tail;
|
|
|
|
char *tailfree; /* freeptr of tail chunk */
|
2004-09-10 20:40:09 +02:00
|
|
|
} AfterTriggerEventList;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/* Macros to help in iterating over a list of events */
|
|
|
|
#define for_each_chunk(cptr, evtlist) \
|
|
|
|
for (cptr = (evtlist).head; cptr != NULL; cptr = cptr->next)
|
|
|
|
#define for_each_event(eptr, cptr) \
|
|
|
|
for (eptr = (AfterTriggerEvent) CHUNK_DATA_START(cptr); \
|
|
|
|
(char *) eptr < (cptr)->freeptr; \
|
|
|
|
eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
|
|
|
|
/* Use this if no special per-chunk processing is needed */
|
|
|
|
#define for_each_event_chunk(eptr, cptr, evtlist) \
|
|
|
|
for_each_chunk(cptr, evtlist) for_each_event(eptr, cptr)
|
|
|
|
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
|
|
|
* All per-transaction data for the AFTER TRIGGERS module.
|
|
|
|
*
|
|
|
|
* AfterTriggersData has the following fields:
|
|
|
|
*
|
|
|
|
* firing_counter is incremented for each call of afterTriggerInvokeEvents.
|
|
|
|
* We mark firable events with the current firing cycle's ID so that we can
|
2014-05-06 18:12:18 +02:00
|
|
|
* tell which ones to work on. This ensures sane behavior if a trigger
|
2004-09-10 20:40:09 +02:00
|
|
|
* function chooses to do SET CONSTRAINTS: the inner SET CONSTRAINTS will
|
|
|
|
* only fire those events that weren't already scheduled for firing.
|
|
|
|
*
|
|
|
|
* state keeps track of the transaction-local effects of SET CONSTRAINTS.
|
|
|
|
* This is saved and restored across failed subtransactions.
|
|
|
|
*
|
|
|
|
* events is the current list of deferred events. This is global across
|
2014-05-06 18:12:18 +02:00
|
|
|
* all subtransactions of the current transaction. In a subtransaction
|
2004-09-10 20:40:09 +02:00
|
|
|
* abort, we know that the events added by the subtransaction are at the
|
2006-11-23 02:14:59 +01:00
|
|
|
* end of the list, so it is relatively easy to discard them. The event
|
2008-10-25 01:42:35 +02:00
|
|
|
* list chunks themselves are stored in event_cxt.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
|
|
|
* query_depth is the current depth of nested AfterTriggerBeginQuery calls
|
|
|
|
* (-1 when the stack is empty).
|
|
|
|
*
|
|
|
|
* query_stack[query_depth] is a list of AFTER trigger events queued by the
|
|
|
|
* current query (and the query_stack entries below it are lists of trigger
|
|
|
|
* events queued by calling queries). None of these are valid until the
|
|
|
|
* matching AfterTriggerEndQuery call occurs. At that point we fire
|
|
|
|
* immediate-mode triggers, and append any deferred events to the main events
|
|
|
|
* list.
|
|
|
|
*
|
2014-03-23 07:16:34 +01:00
|
|
|
* fdw_tuplestores[query_depth] is a tuplestore containing the foreign tuples
|
|
|
|
* needed for the current query.
|
|
|
|
*
|
2016-11-04 16:49:50 +01:00
|
|
|
* old_tuplestores[query_depth] and new_tuplestores[query_depth] hold the
|
|
|
|
* transition relations for the current query.
|
|
|
|
*
|
|
|
|
* maxquerydepth is just the allocated length of query_stack and the
|
|
|
|
* tuplestores.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
|
|
|
* state_stack is a stack of pointers to saved copies of the SET CONSTRAINTS
|
|
|
|
* state data; each subtransaction level that modifies that state first
|
|
|
|
* saves a copy, which we use to restore the state if we abort.
|
|
|
|
*
|
|
|
|
* events_stack is a stack of copies of the events head/tail pointers,
|
|
|
|
* which we use to restore those values during subtransaction abort.
|
|
|
|
*
|
|
|
|
* depth_stack is a stack of copies of subtransaction-start-time query_depth,
|
|
|
|
* which we similarly use to clean up at subtransaction abort.
|
|
|
|
*
|
|
|
|
* firing_stack is a stack of copies of subtransaction-start-time
|
2014-05-06 18:12:18 +02:00
|
|
|
* firing_counter. We use this to recognize which deferred triggers were
|
2004-09-10 20:40:09 +02:00
|
|
|
* fired (or marked for firing) within an aborted subtransaction.
|
|
|
|
*
|
|
|
|
* We use GetCurrentTransactionNestLevel() to determine the correct array
|
|
|
|
* index in these stacks. maxtransdepth is the number of allocated entries in
|
2014-05-06 18:12:18 +02:00
|
|
|
* each stack. (By not keeping our own stack pointer, we can avoid trouble
|
2004-09-10 20:40:09 +02:00
|
|
|
* in cases where errors during subxact abort cause multiple invocations
|
|
|
|
* of AfterTriggerEndSubXact() at the same nesting depth.)
|
|
|
|
*/
|
|
|
|
typedef struct AfterTriggersData
|
|
|
|
{
|
2005-10-15 04:49:52 +02:00
|
|
|
CommandId firing_counter; /* next firing ID to assign */
|
|
|
|
SetConstraintState state; /* the active S C state */
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerEventList events; /* deferred-event list */
|
2005-10-15 04:49:52 +02:00
|
|
|
int query_depth; /* current query list index */
|
|
|
|
AfterTriggerEventList *query_stack; /* events pending from each query */
|
2016-11-04 16:49:50 +01:00
|
|
|
Tuplestorestate **fdw_tuplestores; /* foreign tuples for one row from each query */
|
|
|
|
Tuplestorestate **old_tuplestores; /* all old tuples from each query */
|
|
|
|
Tuplestorestate **new_tuplestores; /* all new tuples from each query */
|
2005-10-15 04:49:52 +02:00
|
|
|
int maxquerydepth; /* allocated len of above array */
|
2008-10-25 01:42:35 +02:00
|
|
|
MemoryContext event_cxt; /* memory context for events, if any */
|
2004-09-10 20:40:09 +02:00
|
|
|
|
|
|
|
/* these fields are just for resetting at subtrans abort: */
|
|
|
|
|
|
|
|
SetConstraintState *state_stack; /* stacked S C states */
|
2005-10-15 04:49:52 +02:00
|
|
|
AfterTriggerEventList *events_stack; /* stacked list pointers */
|
|
|
|
int *depth_stack; /* stacked query_depths */
|
|
|
|
CommandId *firing_stack; /* stacked firing_counters */
|
|
|
|
int maxtransdepth; /* allocated len of above arrays */
|
2004-09-10 20:40:09 +02:00
|
|
|
} AfterTriggersData;
|
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
static AfterTriggersData afterTriggers;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
|
|
|
static void AfterTriggerExecute(AfterTriggerEvent event,
|
2005-10-15 04:49:52 +02:00
|
|
|
Relation rel, TriggerDesc *trigdesc,
|
|
|
|
FmgrInfo *finfo,
|
|
|
|
Instrumentation *instr,
|
2014-03-23 07:16:34 +01:00
|
|
|
MemoryContext per_tuple_context,
|
|
|
|
TupleTableSlot *trig_tuple_slot1,
|
|
|
|
TupleTableSlot *trig_tuple_slot2);
|
2004-09-10 20:40:09 +02:00
|
|
|
static SetConstraintState SetConstraintStateCreate(int numalloc);
|
|
|
|
static SetConstraintState SetConstraintStateCopy(SetConstraintState state);
|
|
|
|
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state,
|
2005-10-15 04:49:52 +02:00
|
|
|
Oid tgoid, bool tgisdeferred);
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
/*
|
2016-11-04 16:49:50 +01:00
|
|
|
* Gets a current query transition tuplestore and initializes it if necessary.
|
|
|
|
* This can be holding a single transition row tuple (in the case of an FDW)
|
|
|
|
* or a transition table (for an AFTER trigger).
|
2014-03-23 07:16:34 +01:00
|
|
|
*/
|
|
|
|
static Tuplestorestate *
|
2016-11-04 16:49:50 +01:00
|
|
|
GetTriggerTransitionTuplestore(Tuplestorestate **tss)
|
2014-03-23 07:16:34 +01:00
|
|
|
{
|
|
|
|
Tuplestorestate *ret;
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
ret = tss[afterTriggers.query_depth];
|
2014-03-23 07:16:34 +01:00
|
|
|
if (ret == NULL)
|
|
|
|
{
|
|
|
|
MemoryContext oldcxt;
|
|
|
|
ResourceOwner saveResourceOwner;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Make the tuplestore valid until end of transaction. This is the
|
|
|
|
* allocation lifespan of the associated events list, but we really
|
|
|
|
* only need it until AfterTriggerEndQuery().
|
|
|
|
*/
|
|
|
|
oldcxt = MemoryContextSwitchTo(TopTransactionContext);
|
|
|
|
saveResourceOwner = CurrentResourceOwner;
|
|
|
|
PG_TRY();
|
|
|
|
{
|
|
|
|
CurrentResourceOwner = TopTransactionResourceOwner;
|
|
|
|
ret = tuplestore_begin_heap(false, false, work_mem);
|
|
|
|
}
|
|
|
|
PG_CATCH();
|
|
|
|
{
|
|
|
|
CurrentResourceOwner = saveResourceOwner;
|
|
|
|
PG_RE_THROW();
|
|
|
|
}
|
|
|
|
PG_END_TRY();
|
|
|
|
CurrentResourceOwner = saveResourceOwner;
|
|
|
|
MemoryContextSwitchTo(oldcxt);
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
tss[afterTriggers.query_depth] = ret;
|
2014-03-23 07:16:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
1999-09-29 18:06:40 +02:00
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* afterTriggerCheckState()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Returns true if the trigger event is actually in state DEFERRED.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
static bool
|
2008-10-25 01:42:35 +02:00
|
|
|
afterTriggerCheckState(AfterTriggerShared evtshared)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
Oid tgoid = evtshared->ats_tgoid;
|
2014-10-23 18:33:02 +02:00
|
|
|
SetConstraintState state = afterTriggers.state;
|
2004-08-29 07:07:03 +02:00
|
|
|
int i;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2004-07-01 02:52:04 +02:00
|
|
|
* For not-deferrable triggers (i.e. normal AFTER ROW triggers and
|
|
|
|
* constraints declared NOT DEFERRABLE), the state is always false.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if ((evtshared->ats_event & AFTER_TRIGGER_DEFERRABLE) == 0)
|
1999-09-29 18:06:40 +02:00
|
|
|
return false;
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2014-10-23 18:33:02 +02:00
|
|
|
* If constraint state exists, SET CONSTRAINTS might have been executed
|
|
|
|
* either for this trigger or for all triggers.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
if (state != NULL)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
/* Check for SET CONSTRAINTS for this specific trigger. */
|
|
|
|
for (i = 0; i < state->numstates; i++)
|
|
|
|
{
|
|
|
|
if (state->trigstates[i].sct_tgoid == tgoid)
|
|
|
|
return state->trigstates[i].sct_tgisdeferred;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* Check for SET CONSTRAINTS ALL. */
|
|
|
|
if (state->all_isset)
|
|
|
|
return state->all_isdeferred;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2004-09-09 01:47:58 +02:00
|
|
|
* Otherwise return the default state for the trigger.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
return ((evtshared->ats_event & AFTER_TRIGGER_INITDEFERRED) != 0);
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* afterTriggerAddEvent()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Add a new trigger event to the specified queue.
|
|
|
|
* The passed-in event data is copied.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
2000-01-10 18:14:46 +01:00
|
|
|
static void
|
2008-10-25 01:42:35 +02:00
|
|
|
afterTriggerAddEvent(AfterTriggerEventList *events,
|
|
|
|
AfterTriggerEvent event, AfterTriggerShared evtshared)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
Size eventsize = SizeofTriggerEvent(event);
|
|
|
|
Size needed = eventsize + sizeof(AfterTriggerSharedData);
|
|
|
|
AfterTriggerEventChunk *chunk;
|
|
|
|
AfterTriggerShared newshared;
|
|
|
|
AfterTriggerEvent newevent;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* If empty list or not enough room in the tail chunk, make a new chunk.
|
|
|
|
* We assume here that a new shared record will always be needed.
|
|
|
|
*/
|
|
|
|
chunk = events->tail;
|
|
|
|
if (chunk == NULL ||
|
|
|
|
chunk->endfree - chunk->freeptr < needed)
|
|
|
|
{
|
|
|
|
Size chunksize;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/* Create event context if we didn't already */
|
2014-10-23 18:33:02 +02:00
|
|
|
if (afterTriggers.event_cxt == NULL)
|
|
|
|
afterTriggers.event_cxt =
|
2008-10-25 01:42:35 +02:00
|
|
|
AllocSetContextCreate(TopTransactionContext,
|
|
|
|
"AfterTriggerEvents",
|
Add macros to make AllocSetContextCreate() calls simpler and safer.
I found that half a dozen (nearly 5%) of our AllocSetContextCreate calls
had typos in the context-sizing parameters. While none of these led to
especially significant problems, they did create minor inefficiencies,
and it's now clear that expecting people to copy-and-paste those calls
accurately is not a great idea. Let's reduce the risk of future errors
by introducing single macros that encapsulate the common use-cases.
Three such macros are enough to cover all but two special-purpose contexts;
those two calls can be left as-is, I think.
While this patch doesn't in itself improve matters for third-party
extensions, it doesn't break anything for them either, and they can
gradually adopt the simplified notation over time.
In passing, change TopMemoryContext to use the default allocation
parameters. Formerly it could only be extended 8K at a time. That was
probably reasonable when this code was written; but nowadays we create
many more contexts than we did then, so that it's not unusual to have a
couple hundred K in TopMemoryContext, even without considering various
dubious code that sticks other things there. There seems no good reason
not to let it use growing blocks like most other contexts.
Back-patch to 9.6, mostly because that's still close enough to HEAD that
it's easy to do so, and keeping the branches in sync can be expected to
avoid some future back-patching pain. The bugs fixed by these changes
don't seem to be significant enough to justify fixing them further back.
Discussion: <21072.1472321324@sss.pgh.pa.us>
2016-08-27 23:50:38 +02:00
|
|
|
ALLOCSET_DEFAULT_SIZES);
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* Chunk size starts at 1KB and is allowed to increase up to 1MB.
|
|
|
|
* These numbers are fairly arbitrary, though there is a hard limit at
|
|
|
|
* AFTER_TRIGGER_OFFSET; else we couldn't link event records to their
|
|
|
|
* shared records using the available space in ate_flags. Another
|
|
|
|
* constraint is that if the chunk size gets too huge, the search loop
|
|
|
|
* below would get slow given a (not too common) usage pattern with
|
|
|
|
* many distinct event types in a chunk. Therefore, we double the
|
|
|
|
* preceding chunk size only if there weren't too many shared records
|
|
|
|
* in the preceding chunk; otherwise we halve it. This gives us some
|
|
|
|
* ability to adapt to the actual usage pattern of the current query
|
|
|
|
* while still having large chunk sizes in typical usage. All chunk
|
|
|
|
* sizes used should be MAXALIGN multiples, to ensure that the shared
|
|
|
|
* records will be aligned safely.
|
|
|
|
*/
|
|
|
|
#define MIN_CHUNK_SIZE 1024
|
|
|
|
#define MAX_CHUNK_SIZE (1024*1024)
|
|
|
|
|
|
|
|
#if MAX_CHUNK_SIZE > (AFTER_TRIGGER_OFFSET+1)
|
|
|
|
#error MAX_CHUNK_SIZE must not exceed AFTER_TRIGGER_OFFSET
|
|
|
|
#endif
|
|
|
|
|
|
|
|
if (chunk == NULL)
|
|
|
|
chunksize = MIN_CHUNK_SIZE;
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* preceding chunk size... */
|
|
|
|
chunksize = chunk->endptr - (char *) chunk;
|
|
|
|
/* check number of shared records in preceding chunk */
|
|
|
|
if ((chunk->endptr - chunk->endfree) <=
|
|
|
|
(100 * sizeof(AfterTriggerSharedData)))
|
2009-06-11 16:49:15 +02:00
|
|
|
chunksize *= 2; /* okay, double it */
|
2008-10-25 01:42:35 +02:00
|
|
|
else
|
2009-06-11 16:49:15 +02:00
|
|
|
chunksize /= 2; /* too many shared records */
|
2008-10-25 01:42:35 +02:00
|
|
|
chunksize = Min(chunksize, MAX_CHUNK_SIZE);
|
|
|
|
}
|
2014-10-23 18:33:02 +02:00
|
|
|
chunk = MemoryContextAlloc(afterTriggers.event_cxt, chunksize);
|
2008-10-25 01:42:35 +02:00
|
|
|
chunk->next = NULL;
|
|
|
|
chunk->freeptr = CHUNK_DATA_START(chunk);
|
|
|
|
chunk->endptr = chunk->endfree = (char *) chunk + chunksize;
|
|
|
|
Assert(chunk->endfree - chunk->freeptr >= needed);
|
|
|
|
|
|
|
|
if (events->head == NULL)
|
|
|
|
events->head = chunk;
|
|
|
|
else
|
|
|
|
events->tail->next = chunk;
|
|
|
|
events->tail = chunk;
|
2010-08-19 17:46:18 +02:00
|
|
|
/* events->tailfree is now out of sync, but we'll fix it below */
|
2008-10-25 01:42:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2009-06-11 16:49:15 +02:00
|
|
|
* Try to locate a matching shared-data record already in the chunk. If
|
|
|
|
* none, make a new one.
|
2008-10-25 01:42:35 +02:00
|
|
|
*/
|
|
|
|
for (newshared = ((AfterTriggerShared) chunk->endptr) - 1;
|
|
|
|
(char *) newshared >= chunk->endfree;
|
|
|
|
newshared--)
|
|
|
|
{
|
|
|
|
if (newshared->ats_tgoid == evtshared->ats_tgoid &&
|
|
|
|
newshared->ats_relid == evtshared->ats_relid &&
|
|
|
|
newshared->ats_event == evtshared->ats_event &&
|
|
|
|
newshared->ats_firing_id == 0)
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
if ((char *) newshared < chunk->endfree)
|
2001-03-13 00:02:00 +01:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
*newshared = *evtshared;
|
2009-06-11 16:49:15 +02:00
|
|
|
newshared->ats_firing_id = 0; /* just to be sure */
|
2008-10-25 01:42:35 +02:00
|
|
|
chunk->endfree = (char *) newshared;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Insert the data */
|
|
|
|
newevent = (AfterTriggerEvent) chunk->freeptr;
|
|
|
|
memcpy(newevent, event, eventsize);
|
|
|
|
/* ... and link the new event to its shared record */
|
|
|
|
newevent->ate_flags &= ~AFTER_TRIGGER_OFFSET;
|
|
|
|
newevent->ate_flags |= (char *) newshared - (char *) newevent;
|
|
|
|
|
|
|
|
chunk->freeptr += eventsize;
|
|
|
|
events->tailfree = chunk->freeptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* ----------
|
|
|
|
* afterTriggerFreeEventList()
|
|
|
|
*
|
|
|
|
* Free all the event storage in the given list.
|
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
static void
|
|
|
|
afterTriggerFreeEventList(AfterTriggerEventList *events)
|
|
|
|
{
|
|
|
|
AfterTriggerEventChunk *chunk;
|
|
|
|
AfterTriggerEventChunk *next_chunk;
|
|
|
|
|
|
|
|
for (chunk = events->head; chunk != NULL; chunk = next_chunk)
|
|
|
|
{
|
|
|
|
next_chunk = chunk->next;
|
|
|
|
pfree(chunk);
|
|
|
|
}
|
|
|
|
events->head = NULL;
|
|
|
|
events->tail = NULL;
|
|
|
|
events->tailfree = NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* ----------
|
|
|
|
* afterTriggerRestoreEventList()
|
|
|
|
*
|
|
|
|
* Restore an event list to its prior length, removing all the events
|
|
|
|
* added since it had the value old_events.
|
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
static void
|
|
|
|
afterTriggerRestoreEventList(AfterTriggerEventList *events,
|
|
|
|
const AfterTriggerEventList *old_events)
|
|
|
|
{
|
|
|
|
AfterTriggerEventChunk *chunk;
|
|
|
|
AfterTriggerEventChunk *next_chunk;
|
|
|
|
|
|
|
|
if (old_events->tail == NULL)
|
|
|
|
{
|
|
|
|
/* restoring to a completely empty state, so free everything */
|
|
|
|
afterTriggerFreeEventList(events);
|
2001-03-13 00:02:00 +01:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
*events = *old_events;
|
|
|
|
/* free any chunks after the last one we want to keep */
|
|
|
|
for (chunk = events->tail->next; chunk != NULL; chunk = next_chunk)
|
|
|
|
{
|
|
|
|
next_chunk = chunk->next;
|
|
|
|
pfree(chunk);
|
|
|
|
}
|
|
|
|
/* and clean up the tail chunk to be the right length */
|
|
|
|
events->tail->next = NULL;
|
|
|
|
events->tail->freeptr = events->tailfree;
|
2009-06-11 16:49:15 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* We don't make any effort to remove now-unused shared data records.
|
|
|
|
* They might still be useful, anyway.
|
|
|
|
*/
|
2001-03-13 00:02:00 +01:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerExecute()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
|
|
|
* Fetch the required tuples back from the heap and fire one
|
|
|
|
* single trigger function.
|
2001-06-01 04:41:36 +02:00
|
|
|
*
|
|
|
|
* Frequently, this will be fired many times in a row for triggers of
|
2014-05-06 18:12:18 +02:00
|
|
|
* a single relation. Therefore, we cache the open relation and provide
|
2005-03-25 22:58:00 +01:00
|
|
|
* fmgr lookup cache space at the caller level. (For triggers fired at
|
|
|
|
* the end of a query, we can even piggyback on the executor's state.)
|
2001-06-01 04:41:36 +02:00
|
|
|
*
|
|
|
|
* event: event currently being fired.
|
|
|
|
* rel: open relation for event.
|
2002-10-14 18:51:30 +02:00
|
|
|
* trigdesc: working copy of rel's trigger info.
|
|
|
|
* finfo: array of fmgr lookup cache entries (one per trigger in trigdesc).
|
2005-03-25 22:58:00 +01:00
|
|
|
* instr: array of EXPLAIN ANALYZE instrumentation nodes (one per trigger),
|
|
|
|
* or NULL if no instrumentation is wanted.
|
2001-06-01 04:41:36 +02:00
|
|
|
* per_tuple_context: memory context to call trigger function in.
|
2014-03-23 07:16:34 +01:00
|
|
|
* trig_tuple_slot1: scratch slot for tg_trigtuple (foreign tables only)
|
|
|
|
* trig_tuple_slot2: scratch slot for tg_newtuple (foreign tables only)
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
static void
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerExecute(AfterTriggerEvent event,
|
2005-03-25 22:58:00 +01:00
|
|
|
Relation rel, TriggerDesc *trigdesc,
|
|
|
|
FmgrInfo *finfo, Instrumentation *instr,
|
2014-03-23 07:16:34 +01:00
|
|
|
MemoryContext per_tuple_context,
|
|
|
|
TupleTableSlot *trig_tuple_slot1,
|
|
|
|
TupleTableSlot *trig_tuple_slot2)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
|
|
|
Oid tgoid = evtshared->ats_tgoid;
|
2000-05-29 03:59:17 +02:00
|
|
|
TriggerData LocTriggerData;
|
2008-10-25 01:42:35 +02:00
|
|
|
HeapTupleData tuple1;
|
|
|
|
HeapTupleData tuple2;
|
2000-04-12 19:17:23 +02:00
|
|
|
HeapTuple rettuple;
|
2008-10-25 01:42:35 +02:00
|
|
|
Buffer buffer1 = InvalidBuffer;
|
|
|
|
Buffer buffer2 = InvalidBuffer;
|
2001-06-01 04:41:36 +02:00
|
|
|
int tgindx;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2005-03-25 22:58:00 +01:00
|
|
|
/*
|
|
|
|
* Locate trigger in trigdesc.
|
|
|
|
*/
|
|
|
|
LocTriggerData.tg_trigger = NULL;
|
|
|
|
for (tgindx = 0; tgindx < trigdesc->numtriggers; tgindx++)
|
|
|
|
{
|
|
|
|
if (trigdesc->triggers[tgindx].tgoid == tgoid)
|
|
|
|
{
|
|
|
|
LocTriggerData.tg_trigger = &(trigdesc->triggers[tgindx]);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (LocTriggerData.tg_trigger == NULL)
|
|
|
|
elog(ERROR, "could not find trigger %u", tgoid);
|
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* If doing EXPLAIN ANALYZE, start charging time to this trigger. We want
|
|
|
|
* to include time spent re-fetching tuples in the trigger cost.
|
2005-03-25 22:58:00 +01:00
|
|
|
*/
|
|
|
|
if (instr)
|
|
|
|
InstrStartNode(instr + tgindx);
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Fetch the required tuple(s).
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2014-03-23 07:16:34 +01:00
|
|
|
switch (event->ate_flags & AFTER_TRIGGER_TUP_BITS)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2014-03-23 07:16:34 +01:00
|
|
|
case AFTER_TRIGGER_FDW_FETCH:
|
|
|
|
{
|
2016-11-04 16:49:50 +01:00
|
|
|
Tuplestorestate *fdw_tuplestore =
|
|
|
|
GetTriggerTransitionTuplestore
|
|
|
|
(afterTriggers.fdw_tuplestores);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
if (!tuplestore_gettupleslot(fdw_tuplestore, true, false,
|
|
|
|
trig_tuple_slot1))
|
|
|
|
elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
|
|
|
|
|
|
|
|
if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
|
|
|
|
TRIGGER_EVENT_UPDATE &&
|
|
|
|
!tuplestore_gettupleslot(fdw_tuplestore, true, false,
|
|
|
|
trig_tuple_slot2))
|
|
|
|
elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
|
|
|
|
}
|
|
|
|
/* fall through */
|
|
|
|
case AFTER_TRIGGER_FDW_REUSE:
|
2014-05-06 18:12:18 +02:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
/*
|
|
|
|
* Using ExecMaterializeSlot() rather than ExecFetchSlotTuple()
|
|
|
|
* ensures that tg_trigtuple does not reference tuplestore memory.
|
|
|
|
* (It is formally possible for the trigger function to queue
|
|
|
|
* trigger events that add to the same tuplestore, which can push
|
|
|
|
* other tuples out of memory.) The distinction is academic,
|
|
|
|
* because we start with a minimal tuple that ExecFetchSlotTuple()
|
|
|
|
* must materialize anyway.
|
|
|
|
*/
|
|
|
|
LocTriggerData.tg_trigtuple =
|
|
|
|
ExecMaterializeSlot(trig_tuple_slot1);
|
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
|
|
|
|
LocTriggerData.tg_newtuple =
|
|
|
|
((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
|
|
|
|
TRIGGER_EVENT_UPDATE) ?
|
|
|
|
ExecMaterializeSlot(trig_tuple_slot2) : NULL;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
|
|
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
|
|
|
if (ItemPointerIsValid(&(event->ate_ctid1)))
|
|
|
|
{
|
|
|
|
ItemPointerCopy(&(event->ate_ctid1), &(tuple1.t_self));
|
|
|
|
if (!heap_fetch(rel, SnapshotAny, &tuple1, &buffer1, false, NULL))
|
|
|
|
elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
|
|
|
|
LocTriggerData.tg_trigtuple = &tuple1;
|
|
|
|
LocTriggerData.tg_trigtuplebuf = buffer1;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
LocTriggerData.tg_trigtuple = NULL;
|
|
|
|
LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* don't touch ctid2 if not there */
|
|
|
|
if ((event->ate_flags & AFTER_TRIGGER_TUP_BITS) ==
|
|
|
|
AFTER_TRIGGER_2CTID &&
|
|
|
|
ItemPointerIsValid(&(event->ate_ctid2)))
|
|
|
|
{
|
|
|
|
ItemPointerCopy(&(event->ate_ctid2), &(tuple2.t_self));
|
|
|
|
if (!heap_fetch(rel, SnapshotAny, &tuple2, &buffer2, false, NULL))
|
|
|
|
elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
|
|
|
|
LocTriggerData.tg_newtuple = &tuple2;
|
|
|
|
LocTriggerData.tg_newtuplebuf = buffer2;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
LocTriggerData.tg_newtuple = NULL;
|
|
|
|
LocTriggerData.tg_newtuplebuf = InvalidBuffer;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
/*
|
|
|
|
* Set up the tuplestore information.
|
|
|
|
*/
|
|
|
|
if (LocTriggerData.tg_trigger->tgoldtable)
|
|
|
|
LocTriggerData.tg_oldtable =
|
|
|
|
GetTriggerTransitionTuplestore(afterTriggers.old_tuplestores);
|
|
|
|
else
|
|
|
|
LocTriggerData.tg_oldtable = NULL;
|
|
|
|
if (LocTriggerData.tg_trigger->tgnewtable)
|
|
|
|
LocTriggerData.tg_newtable =
|
|
|
|
GetTriggerTransitionTuplestore(afterTriggers.new_tuplestores);
|
|
|
|
else
|
|
|
|
LocTriggerData.tg_newtable = NULL;
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2006-08-03 18:04:41 +02:00
|
|
|
* Setup the remaining trigger information
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.type = T_TriggerData;
|
2004-09-10 20:40:09 +02:00
|
|
|
LocTriggerData.tg_event =
|
2008-10-25 01:42:35 +02:00
|
|
|
evtshared->ats_event & (TRIGGER_EVENT_OPMASK | TRIGGER_EVENT_ROW);
|
2000-05-29 03:59:17 +02:00
|
|
|
LocTriggerData.tg_relation = rel;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
MemoryContextReset(per_tuple_context);
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Call the trigger and throw away any possibly returned updated tuple.
|
|
|
|
* (Don't let ExecCallTriggerFunc measure EXPLAIN time.)
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2001-06-01 04:41:36 +02:00
|
|
|
rettuple = ExecCallTriggerFunc(&LocTriggerData,
|
2005-03-25 22:58:00 +01:00
|
|
|
tgindx,
|
|
|
|
finfo,
|
|
|
|
NULL,
|
2001-01-22 01:50:07 +01:00
|
|
|
per_tuple_context);
|
2014-03-23 07:16:34 +01:00
|
|
|
if (rettuple != NULL &&
|
|
|
|
rettuple != LocTriggerData.tg_trigtuple &&
|
|
|
|
rettuple != LocTriggerData.tg_newtuple)
|
1999-12-16 23:20:03 +01:00
|
|
|
heap_freetuple(rettuple);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2001-06-01 04:41:36 +02:00
|
|
|
* Release buffers
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if (buffer1 != InvalidBuffer)
|
|
|
|
ReleaseBuffer(buffer1);
|
|
|
|
if (buffer2 != InvalidBuffer)
|
|
|
|
ReleaseBuffer(buffer2);
|
2005-03-25 22:58:00 +01:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
|
|
|
|
* one "tuple returned" (really the number of firings).
|
2005-03-25 22:58:00 +01:00
|
|
|
*/
|
|
|
|
if (instr)
|
2006-05-30 16:01:58 +02:00
|
|
|
InstrStopNode(instr + tgindx, 1);
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
|
|
|
* afterTriggerMarkEvents()
|
|
|
|
*
|
|
|
|
* Scan the given event list for not yet invoked events. Mark the ones
|
|
|
|
* that can be invoked now with the current firing ID.
|
|
|
|
*
|
|
|
|
* If move_list isn't NULL, events that are not to be invoked now are
|
2008-10-25 01:42:35 +02:00
|
|
|
* transferred to move_list.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
|
|
|
* When immediate_only is TRUE, do not invoke currently-deferred triggers.
|
|
|
|
* (This will be FALSE only at main transaction exit.)
|
|
|
|
*
|
|
|
|
* Returns TRUE if any invokable events were found.
|
|
|
|
*/
|
|
|
|
static bool
|
|
|
|
afterTriggerMarkEvents(AfterTriggerEventList *events,
|
|
|
|
AfterTriggerEventList *move_list,
|
|
|
|
bool immediate_only)
|
|
|
|
{
|
|
|
|
bool found = false;
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEvent event;
|
|
|
|
AfterTriggerEventChunk *chunk;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
for_each_event_chunk(event, chunk, *events)
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
2004-09-10 20:40:09 +02:00
|
|
|
bool defer_it = false;
|
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
if (!(event->ate_flags &
|
2004-09-10 20:40:09 +02:00
|
|
|
(AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS)))
|
|
|
|
{
|
|
|
|
/*
|
|
|
|
* This trigger hasn't been called or scheduled yet. Check if we
|
|
|
|
* should call it now.
|
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if (immediate_only && afterTriggerCheckState(evtshared))
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
|
|
|
defer_it = true;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/*
|
|
|
|
* Mark it as to be fired in this firing cycle.
|
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
evtshared->ats_firing_id = afterTriggers.firing_counter;
|
2008-10-25 01:42:35 +02:00
|
|
|
event->ate_flags |= AFTER_TRIGGER_IN_PROGRESS;
|
2004-09-10 20:40:09 +02:00
|
|
|
found = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* If it's deferred, move it to move_list, if requested.
|
|
|
|
*/
|
|
|
|
if (defer_it && move_list != NULL)
|
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
/* add it to move_list */
|
|
|
|
afterTriggerAddEvent(move_list, event, evtshared);
|
|
|
|
/* mark original copy "done" so we don't do it again */
|
|
|
|
event->ate_flags |= AFTER_TRIGGER_DONE;
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return found;
|
|
|
|
}
|
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* afterTriggerInvokeEvents()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2004-09-10 20:40:09 +02:00
|
|
|
* Scan the given event list for events that are marked as to be fired
|
|
|
|
* in the current firing cycle, and fire them.
|
|
|
|
*
|
2007-08-15 23:39:50 +02:00
|
|
|
* If estate isn't NULL, we use its result relation info to avoid repeated
|
|
|
|
* openings and closing of trigger target relations. If it is NULL, we
|
|
|
|
* make one locally to cache the info in case there are multiple trigger
|
|
|
|
* events per rel.
|
2005-03-25 22:58:00 +01:00
|
|
|
*
|
2008-10-25 01:42:35 +02:00
|
|
|
* When delete_ok is TRUE, it's safe to delete fully-processed events.
|
|
|
|
* (We are not very tense about that: we simply reset a chunk to be empty
|
|
|
|
* if all its events got fired. The objective here is just to avoid useless
|
|
|
|
* rescanning of events when a trigger queues new events during transaction
|
|
|
|
* end, so it's not necessary to worry much about the case where only
|
|
|
|
* some events are fired.)
|
|
|
|
*
|
|
|
|
* Returns TRUE if no unfired events remain in the list (this allows us
|
|
|
|
* to avoid repeating afterTriggerMarkEvents).
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
static bool
|
2004-09-10 20:40:09 +02:00
|
|
|
afterTriggerInvokeEvents(AfterTriggerEventList *events,
|
|
|
|
CommandId firing_id,
|
2005-03-25 22:58:00 +01:00
|
|
|
EState *estate,
|
2004-09-10 20:40:09 +02:00
|
|
|
bool delete_ok)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
bool all_fired = true;
|
|
|
|
AfterTriggerEventChunk *chunk;
|
2001-01-22 01:50:07 +01:00
|
|
|
MemoryContext per_tuple_context;
|
2007-08-15 23:39:50 +02:00
|
|
|
bool local_estate = false;
|
2001-06-01 04:41:36 +02:00
|
|
|
Relation rel = NULL;
|
2002-10-14 18:51:30 +02:00
|
|
|
TriggerDesc *trigdesc = NULL;
|
2001-06-01 04:41:36 +02:00
|
|
|
FmgrInfo *finfo = NULL;
|
2005-03-25 22:58:00 +01:00
|
|
|
Instrumentation *instr = NULL;
|
2014-03-23 07:16:34 +01:00
|
|
|
TupleTableSlot *slot1 = NULL,
|
|
|
|
*slot2 = NULL;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2007-08-15 23:39:50 +02:00
|
|
|
/* Make a local EState if need be */
|
|
|
|
if (estate == NULL)
|
|
|
|
{
|
|
|
|
estate = CreateExecutorState();
|
|
|
|
local_estate = true;
|
|
|
|
}
|
|
|
|
|
2001-01-22 01:50:07 +01:00
|
|
|
/* Make a per-tuple memory context for trigger function calls */
|
|
|
|
per_tuple_context =
|
|
|
|
AllocSetContextCreate(CurrentMemoryContext,
|
2004-09-10 20:40:09 +02:00
|
|
|
"AfterTriggerTupleContext",
|
Add macros to make AllocSetContextCreate() calls simpler and safer.
I found that half a dozen (nearly 5%) of our AllocSetContextCreate calls
had typos in the context-sizing parameters. While none of these led to
especially significant problems, they did create minor inefficiencies,
and it's now clear that expecting people to copy-and-paste those calls
accurately is not a great idea. Let's reduce the risk of future errors
by introducing single macros that encapsulate the common use-cases.
Three such macros are enough to cover all but two special-purpose contexts;
those two calls can be left as-is, I think.
While this patch doesn't in itself improve matters for third-party
extensions, it doesn't break anything for them either, and they can
gradually adopt the simplified notation over time.
In passing, change TopMemoryContext to use the default allocation
parameters. Formerly it could only be extended 8K at a time. That was
probably reasonable when this code was written; but nowadays we create
many more contexts than we did then, so that it's not unusual to have a
couple hundred K in TopMemoryContext, even without considering various
dubious code that sticks other things there. There seems no good reason
not to let it use growing blocks like most other contexts.
Back-patch to 9.6, mostly because that's still close enough to HEAD that
it's easy to do so, and keeping the branches in sync can be expected to
avoid some future back-patching pain. The bugs fixed by these changes
don't seem to be significant enough to justify fixing them further back.
Discussion: <21072.1472321324@sss.pgh.pa.us>
2016-08-27 23:50:38 +02:00
|
|
|
ALLOCSET_DEFAULT_SIZES);
|
2001-01-22 01:50:07 +01:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
for_each_chunk(chunk, *events)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEvent event;
|
|
|
|
bool all_fired_in_chunk = true;
|
2001-03-22 07:16:21 +01:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
for_each_event(event, chunk)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Is it one for me to fire?
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if ((event->ate_flags & AFTER_TRIGGER_IN_PROGRESS) &&
|
|
|
|
evtshared->ats_firing_id == firing_id)
|
2001-06-01 04:41:36 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* So let's fire it... but first, find the correct relation if
|
|
|
|
* this is not the same relation as before.
|
|
|
|
*/
|
|
|
|
if (rel == NULL || RelationGetRelid(rel) != evtshared->ats_relid)
|
|
|
|
{
|
|
|
|
ResultRelInfo *rInfo;
|
|
|
|
|
|
|
|
rInfo = ExecGetTriggerResultRel(estate, evtshared->ats_relid);
|
|
|
|
rel = rInfo->ri_RelationDesc;
|
|
|
|
trigdesc = rInfo->ri_TrigDesc;
|
|
|
|
finfo = rInfo->ri_TrigFunctions;
|
|
|
|
instr = rInfo->ri_TrigInstrument;
|
2014-03-23 07:16:34 +01:00
|
|
|
if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
|
|
|
|
{
|
|
|
|
if (slot1 != NULL)
|
|
|
|
{
|
|
|
|
ExecDropSingleTupleTableSlot(slot1);
|
|
|
|
ExecDropSingleTupleTableSlot(slot2);
|
|
|
|
}
|
|
|
|
slot1 = MakeSingleTupleTableSlot(rel->rd_att);
|
|
|
|
slot2 = MakeSingleTupleTableSlot(rel->rd_att);
|
|
|
|
}
|
2009-06-11 16:49:15 +02:00
|
|
|
if (trigdesc == NULL) /* should not happen */
|
2008-10-25 01:42:35 +02:00
|
|
|
elog(ERROR, "relation %u has no triggers",
|
|
|
|
evtshared->ats_relid);
|
|
|
|
}
|
2001-11-16 17:31:16 +01:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* Fire it. Note that the AFTER_TRIGGER_IN_PROGRESS flag is
|
|
|
|
* still set, so recursive examinations of the event list
|
|
|
|
* won't try to re-fire it.
|
|
|
|
*/
|
|
|
|
AfterTriggerExecute(event, rel, trigdesc, finfo, instr,
|
2014-03-23 07:16:34 +01:00
|
|
|
per_tuple_context, slot1, slot2);
|
2001-11-16 17:31:16 +01:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* Mark the event as done.
|
|
|
|
*/
|
|
|
|
event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
|
|
|
|
event->ate_flags |= AFTER_TRIGGER_DONE;
|
|
|
|
}
|
|
|
|
else if (!(event->ate_flags & AFTER_TRIGGER_DONE))
|
|
|
|
{
|
|
|
|
/* something remains to be done */
|
|
|
|
all_fired = all_fired_in_chunk = false;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/* Clear the chunk if delete_ok and nothing left of interest */
|
|
|
|
if (delete_ok && all_fired_in_chunk)
|
2001-11-16 17:31:16 +01:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
chunk->freeptr = CHUNK_DATA_START(chunk);
|
|
|
|
chunk->endfree = chunk->endptr;
|
2010-08-19 17:46:18 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* If it's last chunk, must sync event list's tailfree too. Note
|
|
|
|
* that delete_ok must NOT be passed as true if there could be
|
|
|
|
* stacked AfterTriggerEventList values pointing at this event
|
|
|
|
* list, since we'd fail to fix their copies of tailfree.
|
|
|
|
*/
|
|
|
|
if (chunk == events->tail)
|
|
|
|
events->tailfree = chunk->freeptr;
|
2001-11-16 17:31:16 +01:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
2014-03-23 07:16:34 +01:00
|
|
|
if (slot1 != NULL)
|
|
|
|
{
|
|
|
|
ExecDropSingleTupleTableSlot(slot1);
|
|
|
|
ExecDropSingleTupleTableSlot(slot2);
|
|
|
|
}
|
2001-01-22 01:50:07 +01:00
|
|
|
|
2001-11-16 17:31:16 +01:00
|
|
|
/* Release working resources */
|
2007-08-15 23:39:50 +02:00
|
|
|
MemoryContextDelete(per_tuple_context);
|
|
|
|
|
|
|
|
if (local_estate)
|
2005-03-25 22:58:00 +01:00
|
|
|
{
|
2007-11-16 00:23:44 +01:00
|
|
|
ListCell *l;
|
2007-08-15 23:39:50 +02:00
|
|
|
|
|
|
|
foreach(l, estate->es_trig_target_relations)
|
|
|
|
{
|
|
|
|
ResultRelInfo *resultRelInfo = (ResultRelInfo *) lfirst(l);
|
|
|
|
|
|
|
|
/* Close indices and then the relation itself */
|
|
|
|
ExecCloseIndices(resultRelInfo);
|
|
|
|
heap_close(resultRelInfo->ri_RelationDesc, NoLock);
|
|
|
|
}
|
|
|
|
FreeExecutorState(estate);
|
2005-03-25 22:58:00 +01:00
|
|
|
}
|
2008-10-25 01:42:35 +02:00
|
|
|
|
|
|
|
return all_fired;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
|
1999-09-29 18:06:40 +02:00
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerBeginXact()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
|
|
|
* Called at transaction start (either BEGIN or implicit for single
|
|
|
|
* statement outside of transaction block).
|
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerBeginXact(void)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
/*
|
|
|
|
* Initialize after-trigger state structure to empty
|
|
|
|
*/
|
|
|
|
afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
|
|
|
|
afterTriggers.query_depth = -1;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
|
|
|
/*
|
2014-10-23 18:33:02 +02:00
|
|
|
* Verify that there is no leftover state remaining. If these assertions
|
|
|
|
* trip, it means that AfterTriggerEndXact wasn't called or didn't clean
|
|
|
|
* up properly.
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
Assert(afterTriggers.state == NULL);
|
|
|
|
Assert(afterTriggers.query_stack == NULL);
|
|
|
|
Assert(afterTriggers.fdw_tuplestores == NULL);
|
2016-11-04 16:49:50 +01:00
|
|
|
Assert(afterTriggers.old_tuplestores == NULL);
|
|
|
|
Assert(afterTriggers.new_tuplestores == NULL);
|
2014-10-23 18:33:02 +02:00
|
|
|
Assert(afterTriggers.maxquerydepth == 0);
|
|
|
|
Assert(afterTriggers.event_cxt == NULL);
|
|
|
|
Assert(afterTriggers.events.head == NULL);
|
|
|
|
Assert(afterTriggers.state_stack == NULL);
|
|
|
|
Assert(afterTriggers.events_stack == NULL);
|
|
|
|
Assert(afterTriggers.depth_stack == NULL);
|
|
|
|
Assert(afterTriggers.firing_stack == NULL);
|
|
|
|
Assert(afterTriggers.maxtransdepth == 0);
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
|
|
|
* AfterTriggerBeginQuery()
|
|
|
|
*
|
|
|
|
* Called just before we start processing a single query within a
|
2014-10-23 18:33:02 +02:00
|
|
|
* transaction (or subtransaction). Most of the real work gets deferred
|
|
|
|
* until somebody actually tries to queue a trigger event.
|
2004-09-10 20:40:09 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
|
|
|
AfterTriggerBeginQuery(void)
|
|
|
|
{
|
|
|
|
/* Increase the query stack depth */
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.query_depth++;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerEndQuery()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2004-09-10 20:40:09 +02:00
|
|
|
* Called after one query has been completely processed. At this time
|
|
|
|
* we invoke all AFTER IMMEDIATE trigger events queued by the query, and
|
|
|
|
* transfer deferred trigger events to the global deferred-trigger list.
|
2005-03-25 22:58:00 +01:00
|
|
|
*
|
2011-02-27 19:43:29 +01:00
|
|
|
* Note that this must be called BEFORE closing down the executor
|
2005-03-25 22:58:00 +01:00
|
|
|
* with ExecutorEnd, because we make use of the EState's info about
|
2011-02-27 19:43:29 +01:00
|
|
|
* target relations. Normally it is called from ExecutorFinish.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
2005-03-25 22:58:00 +01:00
|
|
|
AfterTriggerEndQuery(EState *estate)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerEventList *events;
|
2014-03-23 07:16:34 +01:00
|
|
|
Tuplestorestate *fdw_tuplestore;
|
2016-11-04 16:49:50 +01:00
|
|
|
Tuplestorestate *old_tuplestore;
|
|
|
|
Tuplestorestate *new_tuplestore;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
|
|
|
/* Must be inside a query, too */
|
2014-10-23 18:33:02 +02:00
|
|
|
Assert(afterTriggers.query_depth >= 0);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* If we never even got as far as initializing the event stack, there
|
|
|
|
* certainly won't be any events, so exit quickly.
|
|
|
|
*/
|
|
|
|
if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
|
|
|
|
{
|
|
|
|
afterTriggers.query_depth--;
|
|
|
|
return;
|
|
|
|
}
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Process all immediate-mode triggers queued by the query, and move the
|
|
|
|
* deferred ones to the main list of deferred events.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
2005-11-22 19:17:34 +01:00
|
|
|
* Notice that we decide which ones will be fired, and put the deferred
|
|
|
|
* ones on the main list, before anything is actually fired. This ensures
|
2005-10-15 04:49:52 +02:00
|
|
|
* reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
|
|
|
|
* IMMEDIATE: all events we have decided to defer will be available for it
|
|
|
|
* to fire.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
2014-03-23 07:15:52 +01:00
|
|
|
* We loop in case a trigger queues more events at the same query level.
|
|
|
|
* Ordinary trigger functions, including all PL/pgSQL trigger functions,
|
|
|
|
* will instead fire any triggers in a dedicated query level. Foreign key
|
|
|
|
* enforcement triggers do add to the current query level, thanks to their
|
|
|
|
* passing fire_triggers = false to SPI_execute_snapshot(). Other
|
|
|
|
* C-language triggers might do likewise. Be careful here: firing a
|
|
|
|
* trigger could result in query_stack being repalloc'd, so we can't save
|
|
|
|
* its address across afterTriggerInvokeEvents calls.
|
2007-08-15 21:15:47 +02:00
|
|
|
*
|
2005-11-22 19:17:34 +01:00
|
|
|
* If we find no firable events, we don't have to increment
|
|
|
|
* firing_counter.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
for (;;)
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
events = &afterTriggers.query_stack[afterTriggers.query_depth];
|
|
|
|
if (afterTriggerMarkEvents(events, &afterTriggers.events, true))
|
2008-10-25 01:42:35 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
CommandId firing_id = afterTriggers.firing_counter++;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/* OK to delete the immediate events after processing them */
|
|
|
|
if (afterTriggerInvokeEvents(events, firing_id, estate, true))
|
|
|
|
break; /* all fired */
|
|
|
|
}
|
|
|
|
else
|
|
|
|
break;
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
/* Release query-local storage for events, including tuplestore if any */
|
2014-10-23 18:33:02 +02:00
|
|
|
fdw_tuplestore = afterTriggers.fdw_tuplestores[afterTriggers.query_depth];
|
2014-03-23 07:16:34 +01:00
|
|
|
if (fdw_tuplestore)
|
|
|
|
{
|
|
|
|
tuplestore_end(fdw_tuplestore);
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.fdw_tuplestores[afterTriggers.query_depth] = NULL;
|
2014-03-23 07:16:34 +01:00
|
|
|
}
|
2016-11-04 16:49:50 +01:00
|
|
|
old_tuplestore = afterTriggers.old_tuplestores[afterTriggers.query_depth];
|
|
|
|
if (old_tuplestore)
|
|
|
|
{
|
|
|
|
tuplestore_end(old_tuplestore);
|
|
|
|
afterTriggers.old_tuplestores[afterTriggers.query_depth] = NULL;
|
|
|
|
}
|
|
|
|
new_tuplestore = afterTriggers.new_tuplestores[afterTriggers.query_depth];
|
|
|
|
if (new_tuplestore)
|
|
|
|
{
|
|
|
|
tuplestore_end(new_tuplestore);
|
|
|
|
afterTriggers.new_tuplestores[afterTriggers.query_depth] = NULL;
|
|
|
|
}
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggerFreeEventList(&afterTriggers.query_stack[afterTriggers.query_depth]);
|
2008-10-25 01:42:35 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.query_depth--;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
2005-04-11 21:51:16 +02:00
|
|
|
* AfterTriggerFireDeferred()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
|
|
|
* Called just before the current transaction is committed. At this
|
2005-04-11 21:51:16 +02:00
|
|
|
* time we invoke all pending DEFERRED triggers.
|
|
|
|
*
|
|
|
|
* It is possible for other modules to queue additional deferred triggers
|
|
|
|
* during pre-commit processing; therefore xact.c may have to call this
|
|
|
|
* multiple times.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
2005-04-11 21:51:16 +02:00
|
|
|
AfterTriggerFireDeferred(void)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerEventList *events;
|
2008-05-12 22:02:02 +02:00
|
|
|
bool snap_pushed = false;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* Must not be inside a query */
|
|
|
|
Assert(afterTriggers.query_depth == -1);
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2004-12-07 00:57:17 +01:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* If there are any triggers to fire, make sure we have set a snapshot for
|
|
|
|
* them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
|
|
|
|
* can't assume ActiveSnapshot is valid on entry.)
|
2004-12-07 00:57:17 +01:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
events = &afterTriggers.events;
|
2005-04-11 21:51:16 +02:00
|
|
|
if (events->head != NULL)
|
2008-05-12 22:02:02 +02:00
|
|
|
{
|
|
|
|
PushActiveSnapshot(GetTransactionSnapshot());
|
|
|
|
snap_pushed = true;
|
|
|
|
}
|
2004-12-07 00:57:17 +01:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Run all the remaining triggers. Loop until they are all gone, in case
|
2007-11-16 00:23:44 +01:00
|
|
|
* some trigger queues more for us to do.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
while (afterTriggerMarkEvents(events, NULL, false))
|
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
CommandId firing_id = afterTriggers.firing_counter++;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
|
|
|
|
break; /* all fired */
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
/*
|
|
|
|
* We don't bother freeing the event list, since it will go away anyway
|
|
|
|
* (and more efficiently than via pfree) in AfterTriggerEndXact.
|
|
|
|
*/
|
|
|
|
|
2008-05-12 22:02:02 +02:00
|
|
|
if (snap_pushed)
|
|
|
|
PopActiveSnapshot();
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* ----------
|
2005-04-11 21:51:16 +02:00
|
|
|
* AfterTriggerEndXact()
|
|
|
|
*
|
|
|
|
* The current transaction is finishing.
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2005-04-11 21:51:16 +02:00
|
|
|
* Any unfired triggers are canceled so we simply throw
|
1999-09-29 18:06:40 +02:00
|
|
|
* away anything we know.
|
2005-04-11 21:51:16 +02:00
|
|
|
*
|
|
|
|
* Note: it is possible for this to be called repeatedly in case of
|
|
|
|
* error during transaction abort; therefore, do not complain if
|
|
|
|
* already closed down.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
2005-04-11 21:51:16 +02:00
|
|
|
AfterTriggerEndXact(bool isCommit)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2003-06-25 01:25:44 +02:00
|
|
|
/*
|
2014-10-23 18:33:02 +02:00
|
|
|
* Forget the pending-events list.
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
2004-08-29 07:07:03 +02:00
|
|
|
* Since all the info is in TopTransactionContext or children thereof, we
|
2006-11-23 02:14:59 +01:00
|
|
|
* don't really need to do anything to reclaim memory. However, the
|
2007-11-16 00:23:44 +01:00
|
|
|
* pending-events list could be large, and so it's useful to discard it as
|
|
|
|
* soon as possible --- especially if we are aborting because we ran out
|
|
|
|
* of memory for the list!
|
2003-06-25 01:25:44 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
if (afterTriggers.event_cxt)
|
|
|
|
{
|
|
|
|
MemoryContextDelete(afterTriggers.event_cxt);
|
|
|
|
afterTriggers.event_cxt = NULL;
|
|
|
|
afterTriggers.events.head = NULL;
|
|
|
|
afterTriggers.events.tail = NULL;
|
|
|
|
afterTriggers.events.tailfree = NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Forget any subtransaction state as well. Since this can't be very
|
|
|
|
* large, we let the eventual reset of TopTransactionContext free the
|
|
|
|
* memory instead of doing it here.
|
|
|
|
*/
|
|
|
|
afterTriggers.state_stack = NULL;
|
|
|
|
afterTriggers.events_stack = NULL;
|
|
|
|
afterTriggers.depth_stack = NULL;
|
|
|
|
afterTriggers.firing_stack = NULL;
|
|
|
|
afterTriggers.maxtransdepth = 0;
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
2015-08-23 17:38:57 +02:00
|
|
|
* Forget the query stack and constraint-related state information. As
|
2014-10-23 18:33:02 +02:00
|
|
|
* with the subtransaction state information, we don't bother freeing the
|
|
|
|
* memory here.
|
|
|
|
*/
|
|
|
|
afterTriggers.query_stack = NULL;
|
|
|
|
afterTriggers.fdw_tuplestores = NULL;
|
2016-11-04 16:49:50 +01:00
|
|
|
afterTriggers.old_tuplestores = NULL;
|
|
|
|
afterTriggers.new_tuplestores = NULL;
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.maxquerydepth = 0;
|
|
|
|
afterTriggers.state = NULL;
|
2006-11-23 02:14:59 +01:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* No more afterTriggers manipulation until next transaction starts. */
|
|
|
|
afterTriggers.query_depth = -1;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2004-07-01 02:52:04 +02:00
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerBeginSubXact()
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
|
|
|
* Start a subtransaction.
|
|
|
|
*/
|
|
|
|
void
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerBeginSubXact(void)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-09-07 01:33:48 +02:00
|
|
|
int my_level = GetCurrentTransactionNestLevel();
|
|
|
|
|
2004-07-01 02:52:04 +02:00
|
|
|
/*
|
2006-11-23 02:14:59 +01:00
|
|
|
* Allocate more space in the stacks if needed. (Note: because the
|
2007-11-16 00:23:44 +01:00
|
|
|
* minimum nest level of a subtransaction is 2, we waste the first couple
|
|
|
|
* entries of each array; not worth the notational effort to avoid it.)
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
while (my_level >= afterTriggers.maxtransdepth)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
if (afterTriggers.maxtransdepth == 0)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
|
|
|
MemoryContext old_cxt;
|
|
|
|
|
|
|
|
old_cxt = MemoryContextSwitchTo(TopTransactionContext);
|
|
|
|
|
|
|
|
#define DEFTRIG_INITALLOC 8
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack = (SetConstraintState *)
|
2004-09-10 20:40:09 +02:00
|
|
|
palloc(DEFTRIG_INITALLOC * sizeof(SetConstraintState));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.events_stack = (AfterTriggerEventList *)
|
2004-09-10 20:40:09 +02:00
|
|
|
palloc(DEFTRIG_INITALLOC * sizeof(AfterTriggerEventList));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.depth_stack = (int *)
|
2004-09-10 20:40:09 +02:00
|
|
|
palloc(DEFTRIG_INITALLOC * sizeof(int));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.firing_stack = (CommandId *)
|
2004-09-10 20:40:09 +02:00
|
|
|
palloc(DEFTRIG_INITALLOC * sizeof(CommandId));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.maxtransdepth = DEFTRIG_INITALLOC;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
MemoryContextSwitchTo(old_cxt);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* repalloc will keep the stacks in the same context */
|
2014-10-23 18:33:02 +02:00
|
|
|
int new_alloc = afterTriggers.maxtransdepth * 2;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack = (SetConstraintState *)
|
|
|
|
repalloc(afterTriggers.state_stack,
|
2004-09-10 20:40:09 +02:00
|
|
|
new_alloc * sizeof(SetConstraintState));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.events_stack = (AfterTriggerEventList *)
|
|
|
|
repalloc(afterTriggers.events_stack,
|
2004-09-10 20:40:09 +02:00
|
|
|
new_alloc * sizeof(AfterTriggerEventList));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.depth_stack = (int *)
|
|
|
|
repalloc(afterTriggers.depth_stack,
|
2004-09-10 20:40:09 +02:00
|
|
|
new_alloc * sizeof(int));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.firing_stack = (CommandId *)
|
|
|
|
repalloc(afterTriggers.firing_stack,
|
2004-09-10 20:40:09 +02:00
|
|
|
new_alloc * sizeof(CommandId));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.maxtransdepth = new_alloc;
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Push the current information into the stack. The SET CONSTRAINTS state
|
2006-11-23 02:14:59 +01:00
|
|
|
* is not saved until/unless changed. Likewise, we don't make a
|
|
|
|
* per-subtransaction event context until needed.
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack[my_level] = NULL;
|
|
|
|
afterTriggers.events_stack[my_level] = afterTriggers.events;
|
|
|
|
afterTriggers.depth_stack[my_level] = afterTriggers.query_depth;
|
|
|
|
afterTriggers.firing_stack[my_level] = afterTriggers.firing_counter;
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerEndSubXact()
|
2004-07-01 02:52:04 +02:00
|
|
|
*
|
|
|
|
* The current subtransaction is ending.
|
|
|
|
*/
|
|
|
|
void
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerEndSubXact(bool isCommit)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-09-07 01:33:48 +02:00
|
|
|
int my_level = GetCurrentTransactionNestLevel();
|
2004-09-10 20:40:09 +02:00
|
|
|
SetConstraintState state;
|
|
|
|
AfterTriggerEvent event;
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEventChunk *chunk;
|
2004-09-10 20:40:09 +02:00
|
|
|
CommandId subxact_firing_id;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
/*
|
2004-09-07 01:33:48 +02:00
|
|
|
* Pop the prior state if needed.
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
|
|
|
if (isCommit)
|
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
Assert(my_level < afterTriggers.maxtransdepth);
|
2004-07-01 02:52:04 +02:00
|
|
|
/* If we saved a prior state, we don't need it anymore */
|
2014-10-23 18:33:02 +02:00
|
|
|
state = afterTriggers.state_stack[my_level];
|
2004-07-01 02:52:04 +02:00
|
|
|
if (state != NULL)
|
|
|
|
pfree(state);
|
2004-09-07 01:33:48 +02:00
|
|
|
/* this avoids double pfree if error later: */
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack[my_level] = NULL;
|
|
|
|
Assert(afterTriggers.query_depth ==
|
|
|
|
afterTriggers.depth_stack[my_level]);
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/*
|
2010-01-24 22:49:17 +01:00
|
|
|
* Aborting. It is possible subxact start failed before calling
|
|
|
|
* AfterTriggerBeginSubXact, in which case we mustn't risk touching
|
|
|
|
* stack levels that aren't there.
|
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
if (my_level >= afterTriggers.maxtransdepth)
|
2010-01-24 22:49:17 +01:00
|
|
|
return;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Release any event lists from queries being aborted, and restore
|
2014-03-23 07:15:52 +01:00
|
|
|
* query_depth to its pre-subxact value. This assumes that a
|
|
|
|
* subtransaction will not add events to query levels started in a
|
|
|
|
* earlier transaction state.
|
2006-11-23 02:14:59 +01:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
while (afterTriggers.query_depth > afterTriggers.depth_stack[my_level])
|
2006-11-23 02:14:59 +01:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
if (afterTriggers.query_depth < afterTriggers.maxquerydepth)
|
2014-03-23 07:16:34 +01:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
Tuplestorestate *ts;
|
|
|
|
|
|
|
|
ts = afterTriggers.fdw_tuplestores[afterTriggers.query_depth];
|
|
|
|
if (ts)
|
|
|
|
{
|
|
|
|
tuplestore_end(ts);
|
|
|
|
afterTriggers.fdw_tuplestores[afterTriggers.query_depth] = NULL;
|
|
|
|
}
|
2016-11-04 16:49:50 +01:00
|
|
|
ts = afterTriggers.old_tuplestores[afterTriggers.query_depth];
|
|
|
|
if (ts)
|
|
|
|
{
|
|
|
|
tuplestore_end(ts);
|
|
|
|
afterTriggers.old_tuplestores[afterTriggers.query_depth] = NULL;
|
|
|
|
}
|
|
|
|
ts = afterTriggers.new_tuplestores[afterTriggers.query_depth];
|
|
|
|
if (ts)
|
|
|
|
{
|
|
|
|
tuplestore_end(ts);
|
|
|
|
afterTriggers.new_tuplestores[afterTriggers.query_depth] = NULL;
|
|
|
|
}
|
2014-10-23 18:33:02 +02:00
|
|
|
|
|
|
|
afterTriggerFreeEventList(&afterTriggers.query_stack[afterTriggers.query_depth]);
|
2014-03-23 07:16:34 +01:00
|
|
|
}
|
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.query_depth--;
|
2006-11-23 02:14:59 +01:00
|
|
|
}
|
2014-10-23 18:33:02 +02:00
|
|
|
Assert(afterTriggers.query_depth ==
|
|
|
|
afterTriggers.depth_stack[my_level]);
|
2006-11-23 02:14:59 +01:00
|
|
|
|
|
|
|
/*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Restore the global deferred-event list to its former length,
|
|
|
|
* discarding any events queued by the subxact.
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggerRestoreEventList(&afterTriggers.events,
|
|
|
|
&afterTriggers.events_stack[my_level]);
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Restore the trigger state. If the saved state is NULL, then this
|
|
|
|
* subxact didn't save it, so it doesn't need restoring.
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
state = afterTriggers.state_stack[my_level];
|
2004-07-01 02:52:04 +02:00
|
|
|
if (state != NULL)
|
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
pfree(afterTriggers.state);
|
|
|
|
afterTriggers.state = state;
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
2004-09-07 01:33:48 +02:00
|
|
|
/* this avoids double pfree if error later: */
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack[my_level] = NULL;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* Scan for any remaining deferred events that were marked DONE or IN
|
|
|
|
* PROGRESS by this subxact or a child, and un-mark them. We can
|
|
|
|
* recognize such events because they have a firing ID greater than or
|
|
|
|
* equal to the firing_counter value we saved at subtransaction start.
|
|
|
|
* (This essentially assumes that the current subxact includes all
|
|
|
|
* subxacts started after it.)
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
subxact_firing_id = afterTriggers.firing_stack[my_level];
|
|
|
|
for_each_event_chunk(event, chunk, afterTriggers.events)
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
|
|
|
|
|
|
|
if (event->ate_flags &
|
2004-09-10 20:40:09 +02:00
|
|
|
(AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS))
|
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
if (evtshared->ats_firing_id >= subxact_firing_id)
|
|
|
|
event->ate_flags &=
|
2004-09-10 20:40:09 +02:00
|
|
|
~(AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS);
|
|
|
|
}
|
|
|
|
}
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* ----------
|
|
|
|
* AfterTriggerEnlargeQueryState()
|
|
|
|
*
|
|
|
|
* Prepare the necessary state so that we can record AFTER trigger events
|
|
|
|
* queued by a query. It is allowed to have nested queries within a
|
|
|
|
* (sub)transaction, so we need to have separate state for each query
|
|
|
|
* nesting level.
|
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
static void
|
|
|
|
AfterTriggerEnlargeQueryState(void)
|
|
|
|
{
|
2015-05-24 03:35:49 +02:00
|
|
|
int init_depth = afterTriggers.maxquerydepth;
|
2014-10-23 18:33:02 +02:00
|
|
|
|
|
|
|
Assert(afterTriggers.query_depth >= afterTriggers.maxquerydepth);
|
|
|
|
|
|
|
|
if (afterTriggers.maxquerydepth == 0)
|
|
|
|
{
|
2014-10-24 14:17:00 +02:00
|
|
|
int new_alloc = Max(afterTriggers.query_depth + 1, 8);
|
2014-10-23 18:33:02 +02:00
|
|
|
|
|
|
|
afterTriggers.query_stack = (AfterTriggerEventList *)
|
|
|
|
MemoryContextAlloc(TopTransactionContext,
|
|
|
|
new_alloc * sizeof(AfterTriggerEventList));
|
|
|
|
afterTriggers.fdw_tuplestores = (Tuplestorestate **)
|
|
|
|
MemoryContextAllocZero(TopTransactionContext,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
2016-11-04 16:49:50 +01:00
|
|
|
afterTriggers.old_tuplestores = (Tuplestorestate **)
|
|
|
|
MemoryContextAllocZero(TopTransactionContext,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
|
|
|
afterTriggers.new_tuplestores = (Tuplestorestate **)
|
|
|
|
MemoryContextAllocZero(TopTransactionContext,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.maxquerydepth = new_alloc;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
/* repalloc will keep the stack in the same context */
|
|
|
|
int old_alloc = afterTriggers.maxquerydepth;
|
2014-10-24 14:17:00 +02:00
|
|
|
int new_alloc = Max(afterTriggers.query_depth + 1,
|
|
|
|
old_alloc * 2);
|
2014-10-23 18:33:02 +02:00
|
|
|
|
|
|
|
afterTriggers.query_stack = (AfterTriggerEventList *)
|
|
|
|
repalloc(afterTriggers.query_stack,
|
|
|
|
new_alloc * sizeof(AfterTriggerEventList));
|
|
|
|
afterTriggers.fdw_tuplestores = (Tuplestorestate **)
|
|
|
|
repalloc(afterTriggers.fdw_tuplestores,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
2016-11-04 16:49:50 +01:00
|
|
|
afterTriggers.old_tuplestores = (Tuplestorestate **)
|
|
|
|
repalloc(afterTriggers.old_tuplestores,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
|
|
|
afterTriggers.new_tuplestores = (Tuplestorestate **)
|
|
|
|
repalloc(afterTriggers.new_tuplestores,
|
|
|
|
new_alloc * sizeof(Tuplestorestate *));
|
2014-10-23 18:33:02 +02:00
|
|
|
/* Clear newly-allocated slots for subsequent lazy initialization. */
|
|
|
|
memset(afterTriggers.fdw_tuplestores + old_alloc,
|
|
|
|
0, (new_alloc - old_alloc) * sizeof(Tuplestorestate *));
|
2016-11-04 16:49:50 +01:00
|
|
|
memset(afterTriggers.old_tuplestores + old_alloc,
|
|
|
|
0, (new_alloc - old_alloc) * sizeof(Tuplestorestate *));
|
|
|
|
memset(afterTriggers.new_tuplestores + old_alloc,
|
|
|
|
0, (new_alloc - old_alloc) * sizeof(Tuplestorestate *));
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.maxquerydepth = new_alloc;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Initialize new query lists to empty */
|
|
|
|
while (init_depth < afterTriggers.maxquerydepth)
|
|
|
|
{
|
|
|
|
AfterTriggerEventList *events;
|
|
|
|
|
|
|
|
events = &afterTriggers.query_stack[init_depth];
|
|
|
|
events->head = NULL;
|
|
|
|
events->tail = NULL;
|
|
|
|
events->tailfree = NULL;
|
|
|
|
|
|
|
|
++init_depth;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2004-07-01 02:52:04 +02:00
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* Create an empty SetConstraintState with room for numalloc trigstates
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
static SetConstraintState
|
|
|
|
SetConstraintStateCreate(int numalloc)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
SetConstraintState state;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
/* Behave sanely with numalloc == 0 */
|
|
|
|
if (numalloc <= 0)
|
|
|
|
numalloc = 1;
|
|
|
|
|
|
|
|
/*
|
|
|
|
* We assume that zeroing will correctly initialize the state values.
|
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
state = (SetConstraintState)
|
2004-07-01 02:52:04 +02:00
|
|
|
MemoryContextAllocZero(TopTransactionContext,
|
2015-02-20 23:32:01 +01:00
|
|
|
offsetof(SetConstraintStateData, trigstates) +
|
2015-05-24 03:35:49 +02:00
|
|
|
numalloc * sizeof(SetConstraintTriggerData));
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
state->numalloc = numalloc;
|
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2004-09-10 20:40:09 +02:00
|
|
|
* Copy a SetConstraintState
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
static SetConstraintState
|
|
|
|
SetConstraintStateCopy(SetConstraintState origstate)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
SetConstraintState state;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
state = SetConstraintStateCreate(origstate->numstates);
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
state->all_isset = origstate->all_isset;
|
|
|
|
state->all_isdeferred = origstate->all_isdeferred;
|
|
|
|
state->numstates = origstate->numstates;
|
|
|
|
memcpy(state->trigstates, origstate->trigstates,
|
2004-09-10 20:40:09 +02:00
|
|
|
origstate->numstates * sizeof(SetConstraintTriggerData));
|
2004-07-01 02:52:04 +02:00
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* Add a per-trigger item to a SetConstraintState. Returns possibly-changed
|
2004-07-01 02:52:04 +02:00
|
|
|
* pointer to the state object (it will change if we have to repalloc).
|
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
static SetConstraintState
|
|
|
|
SetConstraintStateAddItem(SetConstraintState state,
|
|
|
|
Oid tgoid, bool tgisdeferred)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
|
|
|
if (state->numstates >= state->numalloc)
|
|
|
|
{
|
2004-08-29 07:07:03 +02:00
|
|
|
int newalloc = state->numalloc * 2;
|
2004-07-01 02:52:04 +02:00
|
|
|
|
2004-08-29 07:07:03 +02:00
|
|
|
newalloc = Max(newalloc, 8); /* in case original has size 0 */
|
2004-09-10 20:40:09 +02:00
|
|
|
state = (SetConstraintState)
|
2004-07-01 02:52:04 +02:00
|
|
|
repalloc(state,
|
2015-02-20 23:32:01 +01:00
|
|
|
offsetof(SetConstraintStateData, trigstates) +
|
|
|
|
newalloc * sizeof(SetConstraintTriggerData));
|
2004-07-01 02:52:04 +02:00
|
|
|
state->numalloc = newalloc;
|
|
|
|
Assert(state->numstates < state->numalloc);
|
|
|
|
}
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
state->trigstates[state->numstates].sct_tgoid = tgoid;
|
|
|
|
state->trigstates[state->numstates].sct_tgisdeferred = tgisdeferred;
|
2004-07-01 02:52:04 +02:00
|
|
|
state->numstates++;
|
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerSetState()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2004-09-10 20:40:09 +02:00
|
|
|
* Execute the SET CONSTRAINTS ... utility command.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
|
|
|
void
|
2004-09-10 20:40:09 +02:00
|
|
|
AfterTriggerSetState(ConstraintsSetStmt *stmt)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2004-09-07 01:33:48 +02:00
|
|
|
int my_level = GetCurrentTransactionNestLevel();
|
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* If we haven't already done so, initialize our state. */
|
|
|
|
if (afterTriggers.state == NULL)
|
|
|
|
afterTriggers.state = SetConstraintStateCreate(8);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2004-07-01 02:52:04 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* If in a subtransaction, and we didn't save the current state already,
|
|
|
|
* save it so it can be restored if the subtransaction aborts.
|
2004-07-01 02:52:04 +02:00
|
|
|
*/
|
2004-09-07 01:33:48 +02:00
|
|
|
if (my_level > 1 &&
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack[my_level] == NULL)
|
2004-07-01 02:52:04 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state_stack[my_level] =
|
|
|
|
SetConstraintStateCopy(afterTriggers.state);
|
2004-07-01 02:52:04 +02:00
|
|
|
}
|
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
1999-09-29 18:06:40 +02:00
|
|
|
* Handle SET CONSTRAINTS ALL ...
|
|
|
|
*/
|
2000-04-12 19:17:23 +02:00
|
|
|
if (stmt->constraints == NIL)
|
|
|
|
{
|
2002-08-17 14:15:49 +02:00
|
|
|
/*
|
2004-09-09 01:47:58 +02:00
|
|
|
* Forget any previous SET CONSTRAINTS commands in this transaction.
|
2002-08-17 14:15:49 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state->numstates = 0;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2002-08-17 14:15:49 +02:00
|
|
|
* Set the per-transaction ALL state to known.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state->all_isset = true;
|
|
|
|
afterTriggers.state->all_isdeferred = stmt->deferred;
|
2002-08-17 14:15:49 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
Relation conrel;
|
2002-08-17 14:15:49 +02:00
|
|
|
Relation tgrel;
|
2010-01-17 23:56:23 +01:00
|
|
|
List *conoidlist = NIL;
|
|
|
|
List *tgoidlist = NIL;
|
|
|
|
ListCell *lc;
|
2002-08-17 14:15:49 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
/*
|
2002-08-17 14:15:49 +02:00
|
|
|
* Handle SET CONSTRAINTS constraint-name [, ...]
|
2010-01-17 23:56:23 +01:00
|
|
|
*
|
|
|
|
* First, identify all the named constraints and make a list of their
|
2010-02-26 03:01:40 +01:00
|
|
|
* OIDs. Since, unlike the SQL spec, we allow multiple constraints of
|
|
|
|
* the same name within a schema, the specifications are not
|
2014-05-06 18:12:18 +02:00
|
|
|
* necessarily unique. Our strategy is to target all matching
|
2010-01-17 23:56:23 +01:00
|
|
|
* constraints within the first search-path schema that has any
|
|
|
|
* matches, but disregard matches in schemas beyond the first match.
|
|
|
|
* (This is a bit odd but it's the historical behavior.)
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2010-01-17 23:56:23 +01:00
|
|
|
conrel = heap_open(ConstraintRelationId, AccessShareLock);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
foreach(lc, stmt->constraints)
|
2002-02-19 21:11:20 +01:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
RangeVar *constraint = lfirst(lc);
|
2004-07-01 02:52:04 +02:00
|
|
|
bool found;
|
2010-01-17 23:56:23 +01:00
|
|
|
List *namespacelist;
|
|
|
|
ListCell *nslc;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2006-04-27 02:33:46 +02:00
|
|
|
if (constraint->catalogname)
|
|
|
|
{
|
|
|
|
if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
|
|
|
errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
|
2006-10-04 02:30:14 +02:00
|
|
|
constraint->catalogname, constraint->schemaname,
|
2006-04-27 02:33:46 +02:00
|
|
|
constraint->relname)));
|
|
|
|
}
|
2002-02-19 21:11:20 +01:00
|
|
|
|
2006-10-04 02:30:14 +02:00
|
|
|
/*
|
2006-04-27 02:33:46 +02:00
|
|
|
* If we're given the schema name with the constraint, look only
|
2014-05-06 18:12:18 +02:00
|
|
|
* in that schema. If given a bare constraint name, use the
|
2006-04-27 02:33:46 +02:00
|
|
|
* search path to find the first matching constraint.
|
2002-08-17 14:15:49 +02:00
|
|
|
*/
|
2006-10-04 02:30:14 +02:00
|
|
|
if (constraint->schemaname)
|
|
|
|
{
|
2013-01-26 19:24:50 +01:00
|
|
|
Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
|
|
|
|
false);
|
2006-10-04 02:30:14 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
namespacelist = list_make1_oid(namespaceId);
|
2006-10-04 02:30:14 +02:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
namespacelist = fetch_search_path(true);
|
2006-04-27 02:33:46 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
|
|
|
found = false;
|
2010-01-17 23:56:23 +01:00
|
|
|
foreach(nslc, namespacelist)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
Oid namespaceId = lfirst_oid(nslc);
|
|
|
|
SysScanDesc conscan;
|
|
|
|
ScanKeyData skey[2];
|
|
|
|
HeapTuple tup;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
ScanKeyInit(&skey[0],
|
|
|
|
Anum_pg_constraint_conname,
|
2006-04-27 02:33:46 +02:00
|
|
|
BTEqualStrategyNumber, F_NAMEEQ,
|
2010-01-17 23:56:23 +01:00
|
|
|
CStringGetDatum(constraint->relname));
|
|
|
|
ScanKeyInit(&skey[1],
|
|
|
|
Anum_pg_constraint_connamespace,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(namespaceId));
|
2006-04-27 02:33:46 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
true, NULL, 2, skey);
|
2006-04-27 02:33:46 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
while (HeapTupleIsValid(tup = systable_getnext(conscan)))
|
2004-09-09 01:47:58 +02:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
|
|
|
|
|
|
|
|
if (con->condeferrable)
|
|
|
|
conoidlist = lappend_oid(conoidlist,
|
|
|
|
HeapTupleGetOid(tup));
|
|
|
|
else if (stmt->deferred)
|
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
|
|
|
|
errmsg("constraint \"%s\" is not deferrable",
|
|
|
|
constraint->relname)));
|
2006-04-27 02:33:46 +02:00
|
|
|
found = true;
|
2004-09-09 01:47:58 +02:00
|
|
|
}
|
2006-04-27 02:33:46 +02:00
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
systable_endscan(conscan);
|
2006-04-27 02:33:46 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Once we've found a matching constraint we do not search
|
|
|
|
* later parts of the search path.
|
|
|
|
*/
|
|
|
|
if (found)
|
|
|
|
break;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2010-01-17 23:56:23 +01:00
|
|
|
list_free(namespacelist);
|
2002-08-17 14:15:49 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Not found ?
|
|
|
|
*/
|
|
|
|
if (!found)
|
2003-07-20 23:56:35 +02:00
|
|
|
ereport(ERROR,
|
|
|
|
(errcode(ERRCODE_UNDEFINED_OBJECT),
|
2004-09-09 01:47:58 +02:00
|
|
|
errmsg("constraint \"%s\" does not exist",
|
2006-04-27 02:33:46 +02:00
|
|
|
constraint->relname)));
|
2002-08-17 14:15:49 +02:00
|
|
|
}
|
2010-01-17 23:56:23 +01:00
|
|
|
|
|
|
|
heap_close(conrel, AccessShareLock);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Now, locate the trigger(s) implementing each of these constraints,
|
|
|
|
* and make a list of their OIDs.
|
|
|
|
*/
|
|
|
|
tgrel = heap_open(TriggerRelationId, AccessShareLock);
|
|
|
|
|
|
|
|
foreach(lc, conoidlist)
|
|
|
|
{
|
|
|
|
Oid conoid = lfirst_oid(lc);
|
|
|
|
bool found;
|
|
|
|
ScanKeyData skey;
|
|
|
|
SysScanDesc tgscan;
|
|
|
|
HeapTuple htup;
|
|
|
|
|
|
|
|
found = false;
|
|
|
|
|
|
|
|
ScanKeyInit(&skey,
|
|
|
|
Anum_pg_trigger_tgconstraint,
|
|
|
|
BTEqualStrategyNumber, F_OIDEQ,
|
|
|
|
ObjectIdGetDatum(conoid));
|
|
|
|
|
|
|
|
tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
|
Use an MVCC snapshot, rather than SnapshotNow, for catalog scans.
SnapshotNow scans have the undesirable property that, in the face of
concurrent updates, the scan can fail to see either the old or the new
versions of the row. In many cases, we work around this by requiring
DDL operations to hold AccessExclusiveLock on the object being
modified; in some cases, the existing locking is inadequate and random
failures occur as a result. This commit doesn't change anything
related to locking, but will hopefully pave the way to allowing lock
strength reductions in the future.
The major issue has held us back from making this change in the past
is that taking an MVCC snapshot is significantly more expensive than
using a static special snapshot such as SnapshotNow. However, testing
of various worst-case scenarios reveals that this problem is not
severe except under fairly extreme workloads. To mitigate those
problems, we avoid retaking the MVCC snapshot for each new scan;
instead, we take a new snapshot only when invalidation messages have
been processed. The catcache machinery already requires that
invalidation messages be sent before releasing the related heavyweight
lock; else other backends might rely on locally-cached data rather
than scanning the catalog at all. Thus, making snapshot reuse
dependent on the same guarantees shouldn't break anything that wasn't
already subtly broken.
Patch by me. Review by Michael Paquier and Andres Freund.
2013-07-02 15:47:01 +02:00
|
|
|
NULL, 1, &skey);
|
2010-01-17 23:56:23 +01:00
|
|
|
|
|
|
|
while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
|
|
|
|
{
|
|
|
|
Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
|
|
|
|
|
|
|
|
/*
|
2010-02-26 03:01:40 +01:00
|
|
|
* Silently skip triggers that are marked as non-deferrable in
|
2014-05-06 18:12:18 +02:00
|
|
|
* pg_trigger. This is not an error condition, since a
|
2010-02-26 03:01:40 +01:00
|
|
|
* deferrable RI constraint may have some non-deferrable
|
2010-01-17 23:56:23 +01:00
|
|
|
* actions.
|
|
|
|
*/
|
|
|
|
if (pg_trigger->tgdeferrable)
|
|
|
|
tgoidlist = lappend_oid(tgoidlist,
|
|
|
|
HeapTupleGetOid(htup));
|
|
|
|
|
|
|
|
found = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
systable_endscan(tgscan);
|
|
|
|
|
|
|
|
/* Safety check: a deferrable constraint should have triggers */
|
|
|
|
if (!found)
|
|
|
|
elog(ERROR, "no triggers found for constraint with OID %u",
|
|
|
|
conoid);
|
|
|
|
}
|
|
|
|
|
2002-08-17 14:15:49 +02:00
|
|
|
heap_close(tgrel, AccessShareLock);
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2001-03-22 07:16:21 +01:00
|
|
|
/*
|
2010-01-17 23:56:23 +01:00
|
|
|
* Now we can set the trigger states of individual triggers for this
|
|
|
|
* xact.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2010-01-17 23:56:23 +01:00
|
|
|
foreach(lc, tgoidlist)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2010-01-17 23:56:23 +01:00
|
|
|
Oid tgoid = lfirst_oid(lc);
|
2014-10-23 18:33:02 +02:00
|
|
|
SetConstraintState state = afterTriggers.state;
|
2004-07-01 02:52:04 +02:00
|
|
|
bool found = false;
|
|
|
|
int i;
|
|
|
|
|
2004-09-09 01:47:58 +02:00
|
|
|
for (i = 0; i < state->numstates; i++)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
if (state->trigstates[i].sct_tgoid == tgoid)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2004-09-10 20:40:09 +02:00
|
|
|
state->trigstates[i].sct_tgisdeferred = stmt->deferred;
|
1999-09-29 18:06:40 +02:00
|
|
|
found = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!found)
|
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggers.state =
|
2004-09-10 20:40:09 +02:00
|
|
|
SetConstraintStateAddItem(state, tgoid, stmt->deferred);
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2002-08-17 14:15:49 +02:00
|
|
|
|
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
|
|
|
|
* checks against that constraint must be made when the SET CONSTRAINTS
|
|
|
|
* command is executed -- i.e. the effects of the SET CONSTRAINTS command
|
|
|
|
* apply retroactively. We've updated the constraints state, so scan the
|
|
|
|
* list of previously deferred events to fire any that have now become
|
|
|
|
* immediate.
|
2004-09-10 20:40:09 +02:00
|
|
|
*
|
2005-11-22 19:17:34 +01:00
|
|
|
* Obviously, if this was SET ... DEFERRED then it can't have converted
|
|
|
|
* any unfired events to immediate, so we need do nothing in that case.
|
2002-08-17 14:15:49 +02:00
|
|
|
*/
|
2004-09-10 20:40:09 +02:00
|
|
|
if (!stmt->deferred)
|
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
AfterTriggerEventList *events = &afterTriggers.events;
|
2008-12-13 03:00:20 +01:00
|
|
|
bool snapshot_set = false;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2007-08-15 21:15:47 +02:00
|
|
|
while (afterTriggerMarkEvents(events, NULL, true))
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
CommandId firing_id = afterTriggers.firing_counter++;
|
2004-09-10 20:40:09 +02:00
|
|
|
|
2008-12-13 03:00:20 +01:00
|
|
|
/*
|
|
|
|
* Make sure a snapshot has been established in case trigger
|
2014-05-06 18:12:18 +02:00
|
|
|
* functions need one. Note that we avoid setting a snapshot if
|
2008-12-13 03:00:20 +01:00
|
|
|
* we don't find at least one trigger that has to be fired now.
|
|
|
|
* This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
|
|
|
|
* ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
|
|
|
|
* at the start of a transaction it's not possible for any trigger
|
|
|
|
* events to be queued yet.)
|
|
|
|
*/
|
|
|
|
if (!snapshot_set)
|
|
|
|
{
|
|
|
|
PushActiveSnapshot(GetTransactionSnapshot());
|
|
|
|
snapshot_set = true;
|
|
|
|
}
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
2005-10-15 04:49:52 +02:00
|
|
|
* We can delete fired events if we are at top transaction level,
|
|
|
|
* but we'd better not if inside a subtransaction, since the
|
|
|
|
* subtransaction could later get rolled back.
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if (afterTriggerInvokeEvents(events, firing_id, NULL,
|
|
|
|
!IsSubTransaction()))
|
|
|
|
break; /* all fired */
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
2008-12-13 03:00:20 +01:00
|
|
|
|
|
|
|
if (snapshot_set)
|
|
|
|
PopActiveSnapshot();
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
|
|
|
|
2006-09-04 23:15:56 +02:00
|
|
|
/* ----------
|
2008-01-03 00:34:42 +01:00
|
|
|
* AfterTriggerPendingOnRel()
|
|
|
|
* Test to see if there are any pending after-trigger events for rel.
|
2006-09-04 23:15:56 +02:00
|
|
|
*
|
2008-01-03 00:34:42 +01:00
|
|
|
* This is used by TRUNCATE, CLUSTER, ALTER TABLE, etc to detect whether
|
|
|
|
* it is unsafe to perform major surgery on a relation. Note that only
|
|
|
|
* local pending events are examined. We assume that having exclusive lock
|
|
|
|
* on a rel guarantees there are no unserviced events in other backends ---
|
|
|
|
* but having a lock does not prevent there being such events in our own.
|
2006-09-04 23:15:56 +02:00
|
|
|
*
|
|
|
|
* In some scenarios it'd be reasonable to remove pending events (more
|
|
|
|
* specifically, mark them DONE by the current subxact) but without a lot
|
|
|
|
* of knowledge of the trigger semantics we can't do this in general.
|
|
|
|
* ----------
|
|
|
|
*/
|
2008-01-03 00:34:42 +01:00
|
|
|
bool
|
|
|
|
AfterTriggerPendingOnRel(Oid relid)
|
2006-09-04 23:15:56 +02:00
|
|
|
{
|
|
|
|
AfterTriggerEvent event;
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEventChunk *chunk;
|
2006-09-04 23:15:56 +02:00
|
|
|
int depth;
|
|
|
|
|
|
|
|
/* Scan queued events */
|
2014-10-23 18:33:02 +02:00
|
|
|
for_each_event_chunk(event, chunk, afterTriggers.events)
|
2006-09-04 23:15:56 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
|
|
|
|
2006-09-04 23:15:56 +02:00
|
|
|
/*
|
2014-05-06 18:12:18 +02:00
|
|
|
* We can ignore completed events. (Even if a DONE flag is rolled
|
2006-10-04 02:30:14 +02:00
|
|
|
* back by subxact abort, it's OK because the effects of the TRUNCATE
|
2008-01-03 00:34:42 +01:00
|
|
|
* or whatever must get rolled back too.)
|
2006-09-04 23:15:56 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
if (event->ate_flags & AFTER_TRIGGER_DONE)
|
2006-09-04 23:15:56 +02:00
|
|
|
continue;
|
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
if (evtshared->ats_relid == relid)
|
2008-01-03 00:34:42 +01:00
|
|
|
return true;
|
2006-09-04 23:15:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2006-10-04 02:30:14 +02:00
|
|
|
* Also scan events queued by incomplete queries. This could only matter
|
2008-01-03 00:34:42 +01:00
|
|
|
* if TRUNCATE/etc is executed by a function or trigger within an updating
|
2006-10-04 02:30:14 +02:00
|
|
|
* query on the same relation, which is pretty perverse, but let's check.
|
2006-09-04 23:15:56 +02:00
|
|
|
*/
|
2014-11-10 21:19:56 +01:00
|
|
|
for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
|
2006-09-04 23:15:56 +02:00
|
|
|
{
|
2014-10-23 18:33:02 +02:00
|
|
|
for_each_event_chunk(event, chunk, afterTriggers.query_stack[depth])
|
2006-09-04 23:15:56 +02:00
|
|
|
{
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerShared evtshared = GetTriggerSharedData(event);
|
|
|
|
|
|
|
|
if (event->ate_flags & AFTER_TRIGGER_DONE)
|
2006-09-04 23:15:56 +02:00
|
|
|
continue;
|
|
|
|
|
2008-10-25 01:42:35 +02:00
|
|
|
if (evtshared->ats_relid == relid)
|
2008-01-03 00:34:42 +01:00
|
|
|
return true;
|
2006-09-04 23:15:56 +02:00
|
|
|
}
|
|
|
|
}
|
2008-01-03 00:34:42 +01:00
|
|
|
|
|
|
|
return false;
|
2006-09-04 23:15:56 +02:00
|
|
|
}
|
|
|
|
|
1999-09-29 18:06:40 +02:00
|
|
|
|
|
|
|
/* ----------
|
2004-09-10 20:40:09 +02:00
|
|
|
* AfterTriggerSaveEvent()
|
1999-09-29 18:06:40 +02:00
|
|
|
*
|
2009-07-29 22:56:21 +02:00
|
|
|
* Called by ExecA[RS]...Triggers() to queue up the triggers that should
|
|
|
|
* be fired for an event.
|
2001-01-27 06:16:58 +01:00
|
|
|
*
|
2009-07-29 22:56:21 +02:00
|
|
|
* NOTE: this is called whenever there are any triggers associated with
|
2014-05-06 18:12:18 +02:00
|
|
|
* the event (even if they are disabled). This function decides which
|
2016-11-04 16:49:50 +01:00
|
|
|
* triggers actually need to be queued. It is also called after each row,
|
|
|
|
* even if there are no triggers for that event, if there are any AFTER
|
|
|
|
* STATEMENT triggers for the statement which use transition tables, so that
|
|
|
|
* the transition tuplestores can be built.
|
|
|
|
*
|
|
|
|
* Transition tuplestores are built now, rather than when events are pulled
|
|
|
|
* off of the queue because AFTER ROW triggers are allowed to select from the
|
|
|
|
* transition tables for the statement.
|
1999-09-29 18:06:40 +02:00
|
|
|
* ----------
|
|
|
|
*/
|
2000-06-09 00:38:00 +02:00
|
|
|
static void
|
2009-11-20 21:38:12 +01:00
|
|
|
AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
|
|
|
|
int event, bool row_trigger,
|
2009-07-29 22:56:21 +02:00
|
|
|
HeapTuple oldtup, HeapTuple newtup,
|
2009-10-15 00:14:25 +02:00
|
|
|
List *recheckIndexes, Bitmapset *modifiedCols)
|
1999-09-29 18:06:40 +02:00
|
|
|
{
|
2001-06-01 04:41:36 +02:00
|
|
|
Relation rel = relinfo->ri_RelationDesc;
|
|
|
|
TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
|
2008-10-25 01:42:35 +02:00
|
|
|
AfterTriggerEventData new_event;
|
|
|
|
AfterTriggerSharedData new_shared;
|
2014-03-23 07:16:34 +01:00
|
|
|
char relkind = relinfo->ri_RelationDesc->rd_rel->relkind;
|
2010-10-10 19:43:33 +02:00
|
|
|
int tgtype_event;
|
|
|
|
int tgtype_level;
|
2000-04-12 19:17:23 +02:00
|
|
|
int i;
|
2014-03-23 07:16:34 +01:00
|
|
|
Tuplestorestate *fdw_tuplestore = NULL;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2009-10-27 21:14:27 +01:00
|
|
|
/*
|
2014-10-23 18:33:02 +02:00
|
|
|
* Check state. We use a normal test not Assert because it is possible to
|
2010-02-26 03:01:40 +01:00
|
|
|
* reach here in the wrong state given misconfigured RI triggers, in
|
|
|
|
* particular deferring a cascade action trigger.
|
2009-10-27 21:14:27 +01:00
|
|
|
*/
|
2014-10-23 18:33:02 +02:00
|
|
|
if (afterTriggers.query_depth < 0)
|
2009-10-27 21:14:27 +01:00
|
|
|
elog(ERROR, "AfterTriggerSaveEvent() called outside of query");
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
/* Be sure we have enough space to record events at this query depth. */
|
|
|
|
if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
|
|
|
|
AfterTriggerEnlargeQueryState();
|
|
|
|
|
2016-11-04 16:49:50 +01:00
|
|
|
/*
|
|
|
|
* If the relation has AFTER ... FOR EACH ROW triggers, capture rows into
|
|
|
|
* transition tuplestores for this depth.
|
|
|
|
*/
|
|
|
|
if (row_trigger)
|
|
|
|
{
|
|
|
|
if ((event == TRIGGER_EVENT_DELETE &&
|
|
|
|
trigdesc->trig_delete_old_table) ||
|
|
|
|
(event == TRIGGER_EVENT_UPDATE &&
|
|
|
|
trigdesc->trig_update_old_table))
|
|
|
|
{
|
|
|
|
Tuplestorestate *old_tuplestore;
|
|
|
|
|
|
|
|
Assert(oldtup != NULL);
|
|
|
|
old_tuplestore =
|
|
|
|
GetTriggerTransitionTuplestore
|
|
|
|
(afterTriggers.old_tuplestores);
|
|
|
|
tuplestore_puttuple(old_tuplestore, oldtup);
|
|
|
|
}
|
|
|
|
if ((event == TRIGGER_EVENT_INSERT &&
|
|
|
|
trigdesc->trig_insert_new_table) ||
|
|
|
|
(event == TRIGGER_EVENT_UPDATE &&
|
|
|
|
trigdesc->trig_update_new_table))
|
|
|
|
{
|
|
|
|
Tuplestorestate *new_tuplestore;
|
|
|
|
|
|
|
|
Assert(newtup != NULL);
|
|
|
|
new_tuplestore =
|
|
|
|
GetTriggerTransitionTuplestore
|
|
|
|
(afterTriggers.new_tuplestores);
|
|
|
|
tuplestore_puttuple(new_tuplestore, newtup);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* If transition tables are the only reason we're here, return. */
|
|
|
|
if ((event == TRIGGER_EVENT_DELETE && !trigdesc->trig_delete_after_row) ||
|
|
|
|
(event == TRIGGER_EVENT_INSERT && !trigdesc->trig_insert_after_row) ||
|
|
|
|
(event == TRIGGER_EVENT_UPDATE && !trigdesc->trig_update_after_row))
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2008-03-28 01:21:56 +01:00
|
|
|
/*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Validate the event code and collect the associated tuple CTIDs.
|
|
|
|
*
|
|
|
|
* The event code will be used both as a bitmask and an array offset, so
|
|
|
|
* validation is important to make sure we don't walk off the edge of our
|
|
|
|
* arrays.
|
1999-09-29 18:06:40 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
switch (event)
|
|
|
|
{
|
|
|
|
case TRIGGER_EVENT_INSERT:
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_event = TRIGGER_TYPE_INSERT;
|
2008-10-25 01:42:35 +02:00
|
|
|
if (row_trigger)
|
|
|
|
{
|
|
|
|
Assert(oldtup == NULL);
|
|
|
|
Assert(newtup != NULL);
|
|
|
|
ItemPointerCopy(&(newtup->t_self), &(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
Assert(oldtup == NULL);
|
|
|
|
Assert(newtup == NULL);
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case TRIGGER_EVENT_DELETE:
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_event = TRIGGER_TYPE_DELETE;
|
2008-10-25 01:42:35 +02:00
|
|
|
if (row_trigger)
|
|
|
|
{
|
|
|
|
Assert(oldtup != NULL);
|
|
|
|
Assert(newtup == NULL);
|
|
|
|
ItemPointerCopy(&(oldtup->t_self), &(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
Assert(oldtup == NULL);
|
|
|
|
Assert(newtup == NULL);
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case TRIGGER_EVENT_UPDATE:
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_event = TRIGGER_TYPE_UPDATE;
|
2008-10-25 01:42:35 +02:00
|
|
|
if (row_trigger)
|
|
|
|
{
|
|
|
|
Assert(oldtup != NULL);
|
|
|
|
Assert(newtup != NULL);
|
|
|
|
ItemPointerCopy(&(oldtup->t_self), &(new_event.ate_ctid1));
|
|
|
|
ItemPointerCopy(&(newtup->t_self), &(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
Assert(oldtup == NULL);
|
|
|
|
Assert(newtup == NULL);
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case TRIGGER_EVENT_TRUNCATE:
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_event = TRIGGER_TYPE_TRUNCATE;
|
2008-10-25 01:42:35 +02:00
|
|
|
Assert(oldtup == NULL);
|
|
|
|
Assert(newtup == NULL);
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid1));
|
|
|
|
ItemPointerSetInvalid(&(new_event.ate_ctid2));
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
elog(ERROR, "invalid after-trigger event code: %d", event);
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_event = 0; /* keep compiler quiet */
|
2008-10-25 01:42:35 +02:00
|
|
|
break;
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
if (!(relkind == RELKIND_FOREIGN_TABLE && row_trigger))
|
|
|
|
new_event.ate_flags = (row_trigger && event == TRIGGER_EVENT_UPDATE) ?
|
|
|
|
AFTER_TRIGGER_2CTID : AFTER_TRIGGER_1CTID;
|
|
|
|
/* else, we'll initialize ate_flags for each trigger */
|
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
tgtype_level = (row_trigger ? TRIGGER_TYPE_ROW : TRIGGER_TYPE_STATEMENT);
|
2002-11-23 04:59:09 +01:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
for (i = 0; i < trigdesc->numtriggers; i++)
|
2003-01-08 23:28:32 +01:00
|
|
|
{
|
2010-10-10 19:43:33 +02:00
|
|
|
Trigger *trigger = &trigdesc->triggers[i];
|
2003-01-08 23:28:32 +01:00
|
|
|
|
2010-10-10 19:43:33 +02:00
|
|
|
if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
|
|
|
|
tgtype_level,
|
|
|
|
TRIGGER_TYPE_AFTER,
|
|
|
|
tgtype_event))
|
|
|
|
continue;
|
2009-11-20 21:38:12 +01:00
|
|
|
if (!TriggerEnabled(estate, relinfo, trigger, event,
|
|
|
|
modifiedCols, oldtup, newtup))
|
2009-10-15 00:14:25 +02:00
|
|
|
continue;
|
2003-01-08 23:28:32 +01:00
|
|
|
|
2014-03-23 07:16:34 +01:00
|
|
|
if (relkind == RELKIND_FOREIGN_TABLE && row_trigger)
|
|
|
|
{
|
|
|
|
if (fdw_tuplestore == NULL)
|
|
|
|
{
|
2016-11-04 16:49:50 +01:00
|
|
|
fdw_tuplestore =
|
|
|
|
GetTriggerTransitionTuplestore
|
|
|
|
(afterTriggers.fdw_tuplestores);
|
2014-03-23 07:16:34 +01:00
|
|
|
new_event.ate_flags = AFTER_TRIGGER_FDW_FETCH;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
/* subsequent event for the same tuple */
|
|
|
|
new_event.ate_flags = AFTER_TRIGGER_FDW_REUSE;
|
|
|
|
}
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
2012-06-20 02:07:08 +02:00
|
|
|
* If the trigger is a foreign key enforcement trigger, there are
|
|
|
|
* certain cases where we can skip queueing the event because we can
|
|
|
|
* tell by inspection that the FK constraint will still pass.
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2009-10-15 00:14:25 +02:00
|
|
|
if (TRIGGER_FIRED_BY_UPDATE(event))
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2005-05-30 09:20:59 +02:00
|
|
|
switch (RI_FKey_trigger_type(trigger->tgfoid))
|
2004-09-10 20:40:09 +02:00
|
|
|
{
|
2005-05-30 09:20:59 +02:00
|
|
|
case RI_TRIGGER_PK:
|
2012-06-20 02:07:08 +02:00
|
|
|
/* Update on trigger's PK table */
|
|
|
|
if (!RI_FKey_pk_upd_check_required(trigger, rel,
|
|
|
|
oldtup, newtup))
|
2005-05-30 09:20:59 +02:00
|
|
|
{
|
2012-06-20 02:07:08 +02:00
|
|
|
/* skip queuing this event */
|
2005-05-30 09:20:59 +02:00
|
|
|
continue;
|
|
|
|
}
|
2004-09-10 20:40:09 +02:00
|
|
|
break;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2005-05-30 09:20:59 +02:00
|
|
|
case RI_TRIGGER_FK:
|
2012-06-20 02:07:08 +02:00
|
|
|
/* Update on trigger's FK table */
|
|
|
|
if (!RI_FKey_fk_upd_check_required(trigger, rel,
|
|
|
|
oldtup, newtup))
|
2005-05-30 09:20:59 +02:00
|
|
|
{
|
2012-06-20 02:07:08 +02:00
|
|
|
/* skip queuing this event */
|
2005-05-30 09:20:59 +02:00
|
|
|
continue;
|
|
|
|
}
|
2004-09-10 20:40:09 +02:00
|
|
|
break;
|
2002-09-04 22:31:48 +02:00
|
|
|
|
2005-05-30 09:20:59 +02:00
|
|
|
case RI_TRIGGER_NONE:
|
|
|
|
/* Not an FK trigger */
|
|
|
|
break;
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
2004-09-10 20:40:09 +02:00
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2009-07-29 22:56:21 +02:00
|
|
|
/*
|
2010-02-26 03:01:40 +01:00
|
|
|
* If the trigger is a deferred unique constraint check trigger, only
|
|
|
|
* queue it if the unique constraint was potentially violated, which
|
|
|
|
* we know from index insertion time.
|
2009-07-29 22:56:21 +02:00
|
|
|
*/
|
|
|
|
if (trigger->tgfoid == F_UNIQUE_KEY_RECHECK)
|
|
|
|
{
|
|
|
|
if (!list_member_oid(recheckIndexes, trigger->tgconstrindid))
|
|
|
|
continue; /* Uniqueness definitely not violated */
|
|
|
|
}
|
|
|
|
|
2004-09-10 20:40:09 +02:00
|
|
|
/*
|
2008-10-25 01:42:35 +02:00
|
|
|
* Fill in event structure and add it to the current query's queue.
|
2004-09-10 20:40:09 +02:00
|
|
|
*/
|
2008-10-25 01:42:35 +02:00
|
|
|
new_shared.ats_event =
|
2004-09-10 20:40:09 +02:00
|
|
|
(event & TRIGGER_EVENT_OPMASK) |
|
|
|
|
(row_trigger ? TRIGGER_EVENT_ROW : 0) |
|
|
|
|
(trigger->tgdeferrable ? AFTER_TRIGGER_DEFERRABLE : 0) |
|
|
|
|
(trigger->tginitdeferred ? AFTER_TRIGGER_INITDEFERRED : 0);
|
2008-10-25 01:42:35 +02:00
|
|
|
new_shared.ats_tgoid = trigger->tgoid;
|
|
|
|
new_shared.ats_relid = RelationGetRelid(rel);
|
|
|
|
new_shared.ats_firing_id = 0;
|
1999-09-29 18:06:40 +02:00
|
|
|
|
2014-10-23 18:33:02 +02:00
|
|
|
afterTriggerAddEvent(&afterTriggers.query_stack[afterTriggers.query_depth],
|
2008-10-25 01:42:35 +02:00
|
|
|
&new_event, &new_shared);
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
2014-03-23 07:16:34 +01:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Finally, spool any foreign tuple(s). The tuplestore squashes them to
|
|
|
|
* minimal tuples, so this loses any system columns. The executor lost
|
|
|
|
* those columns before us, for an unrelated reason, so this is fine.
|
|
|
|
*/
|
|
|
|
if (fdw_tuplestore)
|
|
|
|
{
|
|
|
|
if (oldtup != NULL)
|
|
|
|
tuplestore_puttuple(fdw_tuplestore, oldtup);
|
|
|
|
if (newtup != NULL)
|
|
|
|
tuplestore_puttuple(fdw_tuplestore, newtup);
|
|
|
|
}
|
1999-09-29 18:06:40 +02:00
|
|
|
}
|
2012-01-25 17:15:29 +01:00
|
|
|
|
|
|
|
Datum
|
|
|
|
pg_trigger_depth(PG_FUNCTION_ARGS)
|
|
|
|
{
|
|
|
|
PG_RETURN_INT32(MyTriggerDepth);
|
|
|
|
}
|