Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gja8P-0000CM-30 for pgsql-bugs@arkaria.postgresql.org; Wed, 16 Jan 2019 01:36:50 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1gja8N-0005oW-QW for pgsql-bugs@arkaria.postgresql.org; Wed, 16 Jan 2019 01:36:47 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gja8L-0005oP-Ru for pgsql-bugs@lists.postgresql.org; Wed, 16 Jan 2019 01:36:47 +0000 Received: from out5-smtp.messagingengine.com ([66.111.4.29]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gja8G-00035v-UK for pgsql-bugs@postgresql.org; Wed, 16 Jan 2019 01:36:44 +0000 Received: from compute4.internal (compute4.nyi.internal [10.202.2.44]) by mailout.nyi.internal (Postfix) with ESMTP id 861EA2896D; Tue, 15 Jan 2019 20:36:39 -0500 (EST) Received: from mailfrontend2 ([10.202.2.163]) by compute4.internal (MEProxy); Tue, 15 Jan 2019 20:36:39 -0500 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=paquier.xyz; h= date:from:to:cc:subject:message-id:references:mime-version :content-type:in-reply-to; s=fm3; bh=C6O76WxmrvrDKZUsC2/Z7Ej3qBR 6Zrwg0hs56C44qw8=; b=XQgTrZCvPgfBM9W4F+Bs8yhZIW+W5Reclrmde3w98CE cA75wYBUYBXnff6nlu7vUa+3CrBvR7ygDkLP4lBVCqWofAhXVIvWkLLZaoR1XGLO pZs5+6iwSxofgyvhik/ivoAzFVNk7+6k4unPwBebrR5796QN06g8zd4Y4hEH8iVq IqGp4nvl1RRYGLMSogFV1xmzIcZr/utz61dqNEpAi5r0g2cGJ+ERTK4/7zZrImjY vRs1SKrRlFjsQw4o4yHFsYS15KYmNg26LNJJy6iysV2R+QznYgqA1NwPPD2DUj9k kPwmNo1qZBI3o49MAPNDuAR/Wm5RfWnFVJgfWESR/CA== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-type:date:from:in-reply-to :message-id:mime-version:references:subject:to:x-me-proxy :x-me-proxy:x-me-sender:x-me-sender:x-sasl-enc; s=fm1; bh=C6O76W xmrvrDKZUsC2/Z7Ej3qBR6Zrwg0hs56C44qw8=; b=q9MU86h/6j1e+V8Yz1F7AJ XvhtPNOmg+qKI/OSxrUEQFyU2Rd/5gGH+f+9wvQdwbjikWLazfhyuLTiwYV8HSb7 WeAg0Y8NowA7Ank8nHSRhFAwGrOgnRA+T9zG5zd8Fd5693WcIFvBkbCRvwCEyTzy PE+4eJH0vVK3AEzAtwsxLVix91A2AifC7hhaMVoSkiTTaRt9CjbCjbP/fGb9XLLO tS2WUcHiFfEBIzwE7DWoYyUDiQA2KdI3c9p01KQap3bvimtVmr+hmh5hRIHkgAg/ RUisGKFavhfIzP2P2IOt+DbrE/80UQPGnDPmBqy7tnQchRxR2pfF5SOPwgnkrElA == X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgedtledrgeeggdeftdcutefuodetggdotefrodftvf curfhrohhfihhlvgemucfhrghsthforghilhdpqfhuthenuceurghilhhouhhtmecufedt tdenucesvcftvggtihhpihgvnhhtshculddquddttddmnegfrhhlucfvnfffucdljedtmd enucfjughrpeffhffvuffkfhggtggujgesghdtreertddtvdenucfhrhhomhepofhitghh rggvlhcurfgrqhhuihgvrhcuoehmihgthhgrvghlsehprghquhhivghrrdighiiiqeenuc fkphepuddukedrvdeguddrvdegkedrudegjeenucfrrghrrghmpehmrghilhhfrhhomhep mhhitghhrggvlhesphgrqhhuihgvrhdrgiihiienucevlhhushhtvghrufhiiigvpedt X-ME-Proxy: Received: from paquier.xyz (mp76f1f893.ap.nuro.jp [118.241.248.147]) by mail.messagingengine.com (Postfix) with ESMTPA id 44EEF10087; Tue, 15 Jan 2019 20:36:36 -0500 (EST) Date: Wed, 16 Jan 2019 10:36:33 +0900 From: Michael Paquier To: Masahiko Sawada Cc: Tom Lane , Alexey Bashtanov , pgsql-bugs , Mi Tar Subject: Re: Is temporary functions feature official/supported? Found some issues with it. Message-ID: <20190116013633.GH1433@paquier.xyz> References: <9176.1546613679@sss.pgh.pa.us> <20190105000037.GA1626@paquier.xyz> <20190107024211.GA22498@paquier.xyz> <20190109073011.GB23045@paquier.xyz> <20190110034541.GI2157@paquier.xyz> <20190114004520.GA27704@paquier.xyz> MIME-Version: 1.0 Content-Type: multipart/signed; micalg=pgp-sha512; protocol="application/pgp-signature"; boundary="81JctsDUVPekGcy+" Content-Disposition: inline In-Reply-To: List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk --81JctsDUVPekGcy+ Content-Type: multipart/mixed; boundary="y9PDtDHaFrXNoMPU" Content-Disposition: inline --y9PDtDHaFrXNoMPU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Tue, Jan 15, 2019 at 03:36:56PM +0900, Masahiko Sawada wrote: > Thank you for updating the patch. The patch looks good to me. And the > new regression test for CREATE EXTENSION seems to work fine but maybe > it's better to reset client_min_messages at cleanup for safety. Sure, done. I have been working on this patch more this morning, and here is a proposal for commit. So please let me know if there are any objections with that. 9b013dc is the commit which has introduced MyXactFlags, so this means that we cannot get that back-patched further down than v10. Per the lack of complains, that's a restriction I can live with. The first patch is the actual fix to back-patch. The second patch is an improvement I propose only for HEAD which removes ACCESSEDTEMPREL, replacing it with ACCESSEDTEMPNAMESPACE. For now I propose to commit 0001, then I'll spawn a new thread to discuss 0002 on -hackers as XACT_FLAGS_ACCESSEDTEMPREL has the advantage to allow skipping ON COMMIT DELETE if no temporary tables have been accessed. Perhaps that's not worth bothering, but that point seems worth poking at, at least to me. -- Michael --y9PDtDHaFrXNoMPU Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="0001-Restrict-more-the-use-of-temporary-namespace-in-two-.patch" Content-Transfer-Encoding: quoted-printable =46rom eb97099e0d2a6e01a219cbdaa1e14ab0f13620d7 Mon Sep 17 00:00:00 2001 =46rom: Michael Paquier Date: Wed, 16 Jan 2019 10:14:08 +0900 Subject: [PATCH 1/2] Restrict more the use of temporary namespace in two-ph= ase transactions Attempting to use a temporary table within a two phase transaction is forbidden for ages. However, there have been uncovered grounds for a couple of other object types and commands which work on temporary objects with two-phase commit. In short, trying to create, lock or drop an object on a temporary schema should not be authorized within a two-phase transaction, as it would cause its state to create dependencies with other sessions, causing all sorts of side effects with the existing session or other sessions spawned later on trying to use the same temporary schema name. Regression tests are added to cover all the grounds found, the original report mentioned function creation, but monitoring closer there are many other patterns like LOCK, DROP or CREATE EXTENSION which are involved. This is back-patched down to v10, which is where 9b013dc has introduced MyXactFlags, something that this patch relies on. Reported-by: Alexey Bashtanov Author: Michael Paquier Reviewed-by: Masahiko Sawada Discussion: https://postgr.es/m/5d910e2e-0db8-ec06-dd5f-baec420513c3@imap.cc Backpatch-through: 10 --- doc/src/sgml/ref/prepare_transaction.sgml | 6 +- src/backend/access/transam/xact.c | 12 ++++ src/backend/catalog/namespace.c | 60 ++++++++++++---- src/backend/commands/dropcmds.c | 8 +++ src/backend/commands/extension.c | 7 ++ src/backend/commands/lockcmds.c | 10 +++ src/include/access/xact.h | 5 ++ .../expected/test_extensions.out | 33 +++++++++ .../test_extensions/sql/test_extensions.sql | 29 ++++++++ src/test/regress/expected/temp.out | 71 +++++++++++++++++++ src/test/regress/sql/temp.sql | 56 +++++++++++++++ 11 files changed, 279 insertions(+), 18 deletions(-) diff --git a/doc/src/sgml/ref/prepare_transaction.sgml b/doc/src/sgml/ref/p= repare_transaction.sgml index d958f7a06f..5016ca287e 100644 --- a/doc/src/sgml/ref/prepare_transaction.sgml +++ b/doc/src/sgml/ref/prepare_transaction.sgml @@ -98,9 +98,9 @@ PREPARE TRANSACTION tran= saction_id =20 It is not currently allowed to PREPARE a transaction= that - has executed any operations involving temporary tables, - created any cursors WITH HOLD, or executed - LISTEN, UNLISTEN, or + has executed any operations involving temporary tables or the session's + temporary namespace, created any cursors WITH HOLD, = or + executed LISTEN, UNLISTEN, or NOTIFY. Those features are too tightly tied to the current session to be useful in a transaction to be prepare= d. diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam= /xact.c index f665e38ecf..aa61ad0df1 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -2278,6 +2278,18 @@ PrepareTransaction(void) (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot PREPARE a transaction that has operated on temporary t= ables"))); =20 + /* + * Similarly, PREPARE TRANSACTION is not allowed if the temporary + * namespace has been involved in this transaction as we cannot allow it + * to create, lock, or even drop objects within it as this can mess up + * with this session or even a follow-up session trying to use the same + * temporary namespace. + */ + if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot PREPARE a transaction that has operated on temporary n= amespace"))); + /* * Likewise, don't allow PREPARE after pg_export_snapshot. This could be * supported if we added cleanup logic to twophase.c, but for now it diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespac= e.c index 5a6eb495d4..a6be183095 100644 --- a/src/backend/catalog/namespace.c +++ b/src/backend/catalog/namespace.c @@ -192,6 +192,7 @@ char *namespace_search_path =3D NULL; =20 /* Local functions */ static void recomputeNamespacePath(void); +static void AccessTempTableNamespace(bool force); static void InitTempTableNamespace(void); static void RemoveTempRelations(Oid tempNamespaceId); static void RemoveTempRelationsCallback(int code, Datum arg); @@ -459,9 +460,8 @@ RangeVarGetCreationNamespace(const RangeVar *newRelatio= n) /* check for pg_temp alias */ if (strcmp(newRelation->schemaname, "pg_temp") =3D=3D 0) { - /* Initialize temp namespace if first time through */ - if (!OidIsValid(myTempNamespace)) - InitTempTableNamespace(); + /* Initialize temp namespace */ + AccessTempTableNamespace(false); return myTempNamespace; } /* use exact schema given */ @@ -470,9 +470,8 @@ RangeVarGetCreationNamespace(const RangeVar *newRelatio= n) } else if (newRelation->relpersistence =3D=3D RELPERSISTENCE_TEMP) { - /* Initialize temp namespace if first time through */ - if (!OidIsValid(myTempNamespace)) - InitTempTableNamespace(); + /* Initialize temp namespace */ + AccessTempTableNamespace(false); return myTempNamespace; } else @@ -482,7 +481,7 @@ RangeVarGetCreationNamespace(const RangeVar *newRelatio= n) if (activeTempCreationPending) { /* Need to initialize temp namespace */ - InitTempTableNamespace(); + AccessTempTableNamespace(true); return myTempNamespace; } namespaceId =3D activeCreationNamespace; @@ -2921,9 +2920,8 @@ LookupCreationNamespace(const char *nspname) /* check for pg_temp alias */ if (strcmp(nspname, "pg_temp") =3D=3D 0) { - /* Initialize temp namespace if first time through */ - if (!OidIsValid(myTempNamespace)) - InitTempTableNamespace(); + /* Initialize temp namespace */ + AccessTempTableNamespace(false); return myTempNamespace; } =20 @@ -2986,9 +2984,8 @@ QualifiedNameGetCreationNamespace(List *names, char *= *objname_p) /* check for pg_temp alias */ if (strcmp(schemaname, "pg_temp") =3D=3D 0) { - /* Initialize temp namespace if first time through */ - if (!OidIsValid(myTempNamespace)) - InitTempTableNamespace(); + /* Initialize temp namespace */ + AccessTempTableNamespace(false); return myTempNamespace; } /* use exact schema given */ @@ -3002,7 +2999,7 @@ QualifiedNameGetCreationNamespace(List *names, char *= *objname_p) if (activeTempCreationPending) { /* Need to initialize temp namespace */ - InitTempTableNamespace(); + AccessTempTableNamespace(true); return myTempNamespace; } namespaceId =3D activeCreationNamespace; @@ -3832,6 +3829,39 @@ recomputeNamespacePath(void) list_free(oidlist); } =20 +/* + * AccessTempTableNamespace + * Provide access to a temporary namespace, potentially creating it + * if not present yet. This routine registers if the namespace gets + * in use in this transaction. 'force' can be set to true to allow + * the caller to enforce the creation of the temporary namespace for + * use in this backend, which happens for one whose creation is + * pending. + */ +static void +AccessTempTableNamespace(bool force) +{ + /* + * Make note that this temporary namespace has been accessed in this + * transaction. + */ + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; + + /* + * If the caller attempting to access a temporary schema expects the + * creation of the namespace to be pending and should be enforced, then go + * through the creation. + */ + if (!force && OidIsValid(myTempNamespace)) + return; + + /* + * The temporary tablespace does not exist yet and is wanted, so + * initialize it. + */ + InitTempTableNamespace(); +} + /* * InitTempTableNamespace * Initialize temp table namespace on first use in a particular backend @@ -4275,7 +4305,7 @@ fetch_search_path(bool includeImplicit) */ if (activeTempCreationPending) { - InitTempTableNamespace(); + AccessTempTableNamespace(true); recomputeNamespacePath(); } =20 diff --git a/src/backend/commands/dropcmds.c b/src/backend/commands/dropcmd= s.c index 1dc1c746f1..980ce89c62 100644 --- a/src/backend/commands/dropcmds.c +++ b/src/backend/commands/dropcmds.c @@ -14,6 +14,7 @@ */ #include "postgres.h" =20 +#include "access/xact.h" #include "access/heapam.h" #include "access/htup_details.h" #include "catalog/dependency.h" @@ -107,6 +108,13 @@ RemoveObjects(DropStmt *stmt) check_object_ownership(GetUserId(), stmt->removeType, address, object, relation); =20 + /* + * Make note if a temporary namespace has been accessed in this + * transaction. + */ + if (OidIsValid(namespaceId) && isTempNamespace(namespaceId)) + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; + /* Release any relcache reference count, but keep lock until commit. */ if (relation) heap_close(relation, NoLock); diff --git a/src/backend/commands/extension.c b/src/backend/commands/extens= ion.c index e381a30760..4fe71196c4 100644 --- a/src/backend/commands/extension.c +++ b/src/backend/commands/extension.c @@ -1475,6 +1475,13 @@ CreateExtensionInternal(char *extensionName, list_free(search_path); } =20 + /* + * Make note if a temporary namespace has been accessed in this + * transaction. + */ + if (isTempNamespace(schemaOid)) + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; + /* * We don't check creation rights on the target namespace here. If the * extension script actually creates any objects there, it will fail if diff --git a/src/backend/commands/lockcmds.c b/src/backend/commands/lockcmd= s.c index 1b33be1895..4cd7ec2d5f 100644 --- a/src/backend/commands/lockcmds.c +++ b/src/backend/commands/lockcmds.c @@ -14,6 +14,7 @@ */ #include "postgres.h" =20 +#include "access/xact.h" #include "catalog/namespace.h" #include "catalog/pg_inherits.h" #include "commands/lockcmds.h" @@ -83,6 +84,7 @@ RangeVarCallbackForLockTable(const RangeVar *rv, Oid reli= d, Oid oldrelid, { LOCKMODE lockmode =3D *(LOCKMODE *) arg; char relkind; + char relpersistence; AclResult aclresult; =20 if (!OidIsValid(relid)) @@ -100,6 +102,14 @@ RangeVarCallbackForLockTable(const RangeVar *rv, Oid r= elid, Oid oldrelid, errmsg("\"%s\" is not a table or a view", rv->relname))); =20 + /* + * Make note if a temporary relation has been accessed in this + * transaction. + */ + relpersistence =3D get_rel_persistence(relid); + if (relpersistence =3D=3D RELPERSISTENCE_TEMP) + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPREL; + /* Check permissions. */ aclresult =3D LockTableAclCheck(relid, lockmode, GetUserId()); if (aclresult !=3D ACLCHECK_OK) diff --git a/src/include/access/xact.h b/src/include/access/xact.h index 169cf2834c..ed21a13896 100644 --- a/src/include/access/xact.h +++ b/src/include/access/xact.h @@ -98,6 +98,11 @@ extern int MyXactFlags; */ #define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK (1U << 1) =20 +/* + * XACT_FLAGS_ACCESSEDTEMPNAMESPACE - set when a temporary namespace is + * accessed. We don't allow PREPARE TRANSACTION in that case. + */ +#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE (1U << 2) =20 /* * start- and end-of-transaction callbacks for dynamically loaded modules diff --git a/src/test/modules/test_extensions/expected/test_extensions.out = b/src/test/modules/test_extensions/expected/test_extensions.out index 28d86c4b87..1eec5a37d3 100644 --- a/src/test/modules/test_extensions/expected/test_extensions.out +++ b/src/test/modules/test_extensions/expected/test_extensions.out @@ -121,3 +121,36 @@ Objects in extension "test_ext8" =20 -- dropping it should still work drop extension test_ext8; +-- Test creation of extension in temporary schema with two-phase commit, +-- which should not work. This function wrapper is useful for portability. +-- Avoid noise caused by CONTEXT and NOTICE messages including the tempora= ry +-- schema name. +\set SHOW_CONTEXT never +SET client_min_messages TO 'warning'; +-- First enforce presence of temporary schema. +CREATE TEMP TABLE test_ext4_tab (); +CREATE OR REPLACE FUNCTION create_extension_with_temp_schema() + RETURNS VOID AS $$ + DECLARE + tmpschema text; + query text; + BEGIN + SELECT INTO tmpschema pg_my_temp_schema()::regnamespace; + query :=3D 'CREATE EXTENSION test_ext4 SCHEMA ' || tmpschema || ' CASC= ADE;'; + RAISE NOTICE 'query %', query; + EXECUTE query; + END; $$ LANGUAGE plpgsql; +BEGIN; +SELECT create_extension_with_temp_schema(); + create_extension_with_temp_schema=20 +----------------------------------- +=20 +(1 row) + +PREPARE TRANSACTION 'twophase_extension'; +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace +-- Clean up +DROP TABLE test_ext4_tab; +DROP FUNCTION create_extension_with_temp_schema(); +RESET client_min_messages; +\unset SHOW_CONTEXT diff --git a/src/test/modules/test_extensions/sql/test_extensions.sql b/src= /test/modules/test_extensions/sql/test_extensions.sql index 9e64503eb5..f505466ab4 100644 --- a/src/test/modules/test_extensions/sql/test_extensions.sql +++ b/src/test/modules/test_extensions/sql/test_extensions.sql @@ -64,3 +64,32 @@ end'; =20 -- dropping it should still work drop extension test_ext8; + +-- Test creation of extension in temporary schema with two-phase commit, +-- which should not work. This function wrapper is useful for portability. + +-- Avoid noise caused by CONTEXT and NOTICE messages including the tempora= ry +-- schema name. +\set SHOW_CONTEXT never +SET client_min_messages TO 'warning'; +-- First enforce presence of temporary schema. +CREATE TEMP TABLE test_ext4_tab (); +CREATE OR REPLACE FUNCTION create_extension_with_temp_schema() + RETURNS VOID AS $$ + DECLARE + tmpschema text; + query text; + BEGIN + SELECT INTO tmpschema pg_my_temp_schema()::regnamespace; + query :=3D 'CREATE EXTENSION test_ext4 SCHEMA ' || tmpschema || ' CASC= ADE;'; + RAISE NOTICE 'query %', query; + EXECUTE query; + END; $$ LANGUAGE plpgsql; +BEGIN; +SELECT create_extension_with_temp_schema(); +PREPARE TRANSACTION 'twophase_extension'; +-- Clean up +DROP TABLE test_ext4_tab; +DROP FUNCTION create_extension_with_temp_schema(); +RESET client_min_messages; +\unset SHOW_CONTEXT diff --git a/src/test/regress/expected/temp.out b/src/test/regress/expected= /temp.out index f018f17ca0..860f58a3bf 100644 --- a/src/test/regress/expected/temp.out +++ b/src/test/regress/expected/temp.out @@ -301,3 +301,74 @@ select relname from pg_class where relname like 'temp_= inh_oncommit_test%'; (1 row) =20 drop table temp_inh_oncommit_test; +-- Tests with two-phase commit +-- Transactions creating objects in a temporary namespace cannot be used +-- with two-phase commit. +-- These cases generate errors about temporary namespace. +-- Function creation +begin; +create function pg_temp.twophase_func() returns void as + $$ select '2pc_func'::text $$ language sql; +prepare transaction 'twophase_func'; +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace +-- Function drop +create function pg_temp.twophase_func() returns void as + $$ select '2pc_func'::text $$ language sql; +begin; +drop function pg_temp.twophase_func(); +prepare transaction 'twophase_func'; +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace +-- Operator creation +begin; +create operator pg_temp.@@ (leftarg =3D int4, rightarg =3D int4, procedure= =3D int4mi); +prepare transaction 'twophase_operator'; +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace +-- These generate errors about temporary tables. +begin; +create type pg_temp.twophase_type as (a int); +prepare transaction 'twophase_type'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +begin; +create view pg_temp.twophase_view as select 1; +prepare transaction 'twophase_view'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +begin; +create sequence pg_temp.twophase_seq; +prepare transaction 'twophase_sequence'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +-- Temporary tables cannot be used with two-phase commit. +create temp table twophase_tab (a int); +begin; +select a from twophase_tab; + a=20 +--- +(0 rows) + +prepare transaction 'twophase_tab'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +begin; +insert into twophase_tab values (1); +prepare transaction 'twophase_tab'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +begin; +lock twophase_tab in access exclusive mode; +prepare transaction 'twophase_tab'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +begin; +drop table twophase_tab; +prepare transaction 'twophase_tab'; +ERROR: cannot PREPARE a transaction that has operated on temporary tables +-- Corner case: current_schema may create a temporary schema if namespace +-- creation is pending, so check after that. First reset the connection +-- to remove the temporary namespace. +\c - +SET search_path TO 'pg_temp'; +BEGIN; +SELECT current_schema() ~ 'pg_temp' AS is_temp_schema; + is_temp_schema=20 +---------------- + t +(1 row) + +PREPARE TRANSACTION 'twophase_search'; +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace diff --git a/src/test/regress/sql/temp.sql b/src/test/regress/sql/temp.sql index 1beccc6ceb..e634ddb9ca 100644 --- a/src/test/regress/sql/temp.sql +++ b/src/test/regress/sql/temp.sql @@ -224,3 +224,59 @@ select * from temp_inh_oncommit_test; -- one relation remains select relname from pg_class where relname like 'temp_inh_oncommit_test%'; drop table temp_inh_oncommit_test; + +-- Tests with two-phase commit +-- Transactions creating objects in a temporary namespace cannot be used +-- with two-phase commit. + +-- These cases generate errors about temporary namespace. +-- Function creation +begin; +create function pg_temp.twophase_func() returns void as + $$ select '2pc_func'::text $$ language sql; +prepare transaction 'twophase_func'; +-- Function drop +create function pg_temp.twophase_func() returns void as + $$ select '2pc_func'::text $$ language sql; +begin; +drop function pg_temp.twophase_func(); +prepare transaction 'twophase_func'; +-- Operator creation +begin; +create operator pg_temp.@@ (leftarg =3D int4, rightarg =3D int4, procedure= =3D int4mi); +prepare transaction 'twophase_operator'; + +-- These generate errors about temporary tables. +begin; +create type pg_temp.twophase_type as (a int); +prepare transaction 'twophase_type'; +begin; +create view pg_temp.twophase_view as select 1; +prepare transaction 'twophase_view'; +begin; +create sequence pg_temp.twophase_seq; +prepare transaction 'twophase_sequence'; + +-- Temporary tables cannot be used with two-phase commit. +create temp table twophase_tab (a int); +begin; +select a from twophase_tab; +prepare transaction 'twophase_tab'; +begin; +insert into twophase_tab values (1); +prepare transaction 'twophase_tab'; +begin; +lock twophase_tab in access exclusive mode; +prepare transaction 'twophase_tab'; +begin; +drop table twophase_tab; +prepare transaction 'twophase_tab'; + +-- Corner case: current_schema may create a temporary schema if namespace +-- creation is pending, so check after that. First reset the connection +-- to remove the temporary namespace. +\c - +SET search_path TO 'pg_temp'; +BEGIN; +SELECT current_schema() ~ 'pg_temp' AS is_temp_schema; +PREPARE TRANSACTION 'twophase_search'; --=20 2.20.1 --y9PDtDHaFrXNoMPU Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="0002-Simplify-2PC-restriction-handling-for-temporary-obje.patch" Content-Transfer-Encoding: quoted-printable =46rom 883e60f9a369cd6eb140f054bb0b602ffa19c978 Mon Sep 17 00:00:00 2001 =46rom: Michael Paquier Date: Wed, 16 Jan 2019 10:34:13 +0900 Subject: [PATCH 2/2] Simplify 2PC restriction handling for temporary objects There are two flags used to control access to temporary tables and access to the temporary namespace of a session, however the first control flag is actually a concept included in the second. This removes the flag for temporary table tracking, keeping around only the one at namespace level. --- src/backend/access/heap/heapam.c | 4 ++-- src/backend/access/transam/xact.c | 19 ++++++------------- src/backend/commands/lockcmds.c | 2 +- src/backend/commands/tablecmds.c | 2 +- src/include/access/xact.h | 12 +++--------- src/test/regress/expected/temp.out | 14 +++++++------- 6 files changed, 20 insertions(+), 33 deletions(-) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/hea= pam.c index 9afbc8228d..dd54810052 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -1144,7 +1144,7 @@ relation_open(Oid relationId, LOCKMODE lockmode) =20 /* Make note that we've accessed a temporary relation */ if (RelationUsesLocalBuffers(r)) - MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPREL; + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; =20 pgstat_initstats(r); =20 @@ -1194,7 +1194,7 @@ try_relation_open(Oid relationId, LOCKMODE lockmode) =20 /* Make note that we've accessed a temporary relation */ if (RelationUsesLocalBuffers(r)) - MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPREL; + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; =20 pgstat_initstats(r); =20 diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam= /xact.c index aa61ad0df1..0c20729c68 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -2259,13 +2259,18 @@ PrepareTransaction(void) /* NOTIFY will be handled below */ =20 /* - * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in + * Don't allow PREPARE TRANSACTION if we've accessed a temporary object in * this transaction. Having the prepared xact hold locks on another * backend's temp table seems a bad idea --- for instance it would prevent * the backend from exiting. There are other problems too, such as how to * clean up the source backend's local buffers and ON COMMIT state if the * prepared xact includes a DROP of a temp table. * + * Other objects types, like functions, operators or extensions, share the + * same restriction as they should not be created, locked or dropped as + * this can mess up with this session or even a follow-up session trying + * to use the same temporary namespace. + * * We must check this after executing any ON COMMIT actions, because they * might still access a temp relation. * @@ -2273,18 +2278,6 @@ PrepareTransaction(void) * cases, such as a temp table created and dropped all within the * transaction. That seems to require much more bookkeeping though. */ - if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPREL)) - ereport(ERROR, - (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), - errmsg("cannot PREPARE a transaction that has operated on temporary t= ables"))); - - /* - * Similarly, PREPARE TRANSACTION is not allowed if the temporary - * namespace has been involved in this transaction as we cannot allow it - * to create, lock, or even drop objects within it as this can mess up - * with this session or even a follow-up session trying to use the same - * temporary namespace. - */ if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), diff --git a/src/backend/commands/lockcmds.c b/src/backend/commands/lockcmd= s.c index 4cd7ec2d5f..bea99b59a2 100644 --- a/src/backend/commands/lockcmds.c +++ b/src/backend/commands/lockcmds.c @@ -108,7 +108,7 @@ RangeVarCallbackForLockTable(const RangeVar *rv, Oid re= lid, Oid oldrelid, */ relpersistence =3D get_rel_persistence(relid); if (relpersistence =3D=3D RELPERSISTENCE_TEMP) - MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPREL; + MyXactFlags |=3D XACT_FLAGS_ACCESSEDTEMPNAMESPACE; =20 /* Check permissions. */ aclresult =3D LockTableAclCheck(relid, lockmode, GetUserId()); diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablec= mds.c index d2781cbf19..79b0a0d6e8 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -13253,7 +13253,7 @@ PreCommit_on_commit_actions(void) * relations, we can skip truncating ON COMMIT DELETE ROWS * tables, as they must still be empty. */ - if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPREL)) + if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE)) oids_to_truncate =3D lappend_oid(oids_to_truncate, oc->relid); break; case ONCOMMIT_DROP: diff --git a/src/include/access/xact.h b/src/include/access/xact.h index ed21a13896..ae89920687 100644 --- a/src/include/access/xact.h +++ b/src/include/access/xact.h @@ -87,10 +87,10 @@ extern int synchronous_commit; extern int MyXactFlags; =20 /* - * XACT_FLAGS_ACCESSEDTEMPREL - set when a temporary relation is accessed.= We - * don't allow PREPARE TRANSACTION in that case. + * XACT_FLAGS_ACCESSEDTEMPNAMESPACE - set when a temporary namespace is + * accessed. We don't allow PREPARE TRANSACTION in that case. */ -#define XACT_FLAGS_ACCESSEDTEMPREL (1U << 0) +#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE (1U << 0) =20 /* * XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK - records whether the top level = xact @@ -98,12 +98,6 @@ extern int MyXactFlags; */ #define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK (1U << 1) =20 -/* - * XACT_FLAGS_ACCESSEDTEMPNAMESPACE - set when a temporary namespace is - * accessed. We don't allow PREPARE TRANSACTION in that case. - */ -#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE (1U << 2) - /* * start- and end-of-transaction callbacks for dynamically loaded modules */ diff --git a/src/test/regress/expected/temp.out b/src/test/regress/expected= /temp.out index 860f58a3bf..d9e569a46d 100644 --- a/src/test/regress/expected/temp.out +++ b/src/test/regress/expected/temp.out @@ -327,15 +327,15 @@ ERROR: cannot PREPARE a transaction that has operate= d on temporary namespace begin; create type pg_temp.twophase_type as (a int); prepare transaction 'twophase_type'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace begin; create view pg_temp.twophase_view as select 1; prepare transaction 'twophase_view'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace begin; create sequence pg_temp.twophase_seq; prepare transaction 'twophase_sequence'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace -- Temporary tables cannot be used with two-phase commit. create temp table twophase_tab (a int); begin; @@ -345,19 +345,19 @@ select a from twophase_tab; (0 rows) =20 prepare transaction 'twophase_tab'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace begin; insert into twophase_tab values (1); prepare transaction 'twophase_tab'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace begin; lock twophase_tab in access exclusive mode; prepare transaction 'twophase_tab'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace begin; drop table twophase_tab; prepare transaction 'twophase_tab'; -ERROR: cannot PREPARE a transaction that has operated on temporary tables +ERROR: cannot PREPARE a transaction that has operated on temporary namesp= ace -- Corner case: current_schema may create a temporary schema if namespace -- creation is pending, so check after that. First reset the connection -- to remove the temporary namespace. --=20 2.20.1 --y9PDtDHaFrXNoMPU-- --81JctsDUVPekGcy+ Content-Type: application/pgp-signature; name="signature.asc" -----BEGIN PGP SIGNATURE----- iQIzBAABCgAdFiEEG72nH6vTowiyblFKnvQgOdbyQH0FAlw+iqEACgkQnvQgOdby QH0u5xAAgEwM97Er9EoyK4MerhTlLYCINCyu6nS+tmMgJUE9akc7J39QXWLkXVTJ bVmj1jSKM8JnZusua1Qz6pemMggFueI/68bBuk9Sisuh6Sta4nesH8J+4kd7Tz/G 3IjWXRokDox0cIeKr0u0UsyDJwqrZDLYKw3xTCVAvSfgtc/sswmZPiSJnN4C03zn U4VBIGbqMiAE2LS7ahKYcP/17hyCuIpC5KmnLGAf2nawHVGIddbKwzcv+3v3jtYh BHZLxs4YKP7lr67/gIlSFgm5tuyxKIe7JrXNuzCOIVmOCV4YtphfyPnbQdwrkJ6G 6HHpQXXeNmh8AhtNsMGRv8XSmIgu6ON46w4nfjSQIdw8cI6ydn9geRcJps9wcDwd o6NCE/CUySHmh2Ds9GXVy5QBYNitHDUJmc7Bg5wyH08waEMFRtlVn8r0VApyFnUa UKbfd/Grm08UMPxnpOXbmyCSseDeWr3MqaYulDDaks5NpTIGZq8k7qfuDa4ssgnI 4B+4hMlVpvb9eNIK0hsZ/nTL6Ycg4vc+bDoN3M7krsa+3PsUeVPMV7LWLTX3tCtm 7CP7SM+6TxiDfk9iOQIEK6T5QI3iY2GKqYSUHn1Q3dMd0s3LIg6ueDuC6M+O0bXb Z4Q54JTdEuOrKStFdC4ukk9PPgrcJPDq5dExdwkGFjhQjihs5Yk= =MrrN -----END PGP SIGNATURE----- --81JctsDUVPekGcy+--