Modify the relcache to record the temp status of both local and nonlocal
authorTom Lane <tgl@sss.pgh.pa.us>
Tue, 31 Mar 2009 22:12:48 +0000 (22:12 +0000)
committerTom Lane <tgl@sss.pgh.pa.us>
Tue, 31 Mar 2009 22:12:48 +0000 (22:12 +0000)
temp relations; this is no more expensive than before, now that we have
pg_class.relistemp.  Insert tests into bufmgr.c to prevent attempting
to fetch pages from nonlocal temp relations.  This provides a low-level
defense against bugs-of-omission allowing temp pages to be loaded into shared
buffers, as in the contrib/pgstattuple problem reported by Stuart Bishop.
While at it, tweak a bunch of places to use new relcache tests (instead of
expensive probes into pg_namespace) to detect local or nonlocal temp tables.

14 files changed:
src/backend/catalog/index.c
src/backend/catalog/namespace.c
src/backend/catalog/toasting.c
src/backend/commands/analyze.c
src/backend/commands/cluster.c
src/backend/commands/copy.c
src/backend/commands/indexcmds.c
src/backend/commands/tablecmds.c
src/backend/commands/vacuum.c
src/backend/optimizer/prep/prepunion.c
src/backend/postmaster/autovacuum.c
src/backend/storage/buffer/bufmgr.c
src/backend/utils/cache/relcache.c
src/include/utils/rel.h

index 641270784c3625a179043b5188fcdbf2b2d8a041..96c5983ef9b473e56fc8ea79d53e4138229e4adf 100644 (file)
@@ -2264,7 +2264,7 @@ reindex_index(Oid indexId)
         * Don't allow reindex on temp tables of other backends ... their local
         * buffer manager is not going to cope.
         */
-       if (isOtherTempNamespace(RelationGetNamespace(iRel)))
+       if (RELATION_IS_OTHER_TEMP(iRel))
                ereport(ERROR,
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                 errmsg("cannot reindex temporary tables of other sessions")));
index acaa6aa72e26eb67dd1ac095bb222bf2a9f2c880..1b36b803910bec2c2a1a3f461021452d348996ba 100644 (file)
@@ -2389,6 +2389,9 @@ isAnyTempNamespace(Oid namespaceId)
 /*
  * isOtherTempNamespace - is the given namespace some other backend's
  * temporary-table namespace (including temporary-toast-table namespaces)?
+ *
+ * Note: for most purposes in the C code, this function is obsolete.  Use
+ * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
  */
 bool
 isOtherTempNamespace(Oid namespaceId)
index 7f93523da271f580fc0af4c88610d9b06ad9573c..e87cc2e84b3c15e50ebf91157384e3de5ac2a760 100644 (file)
@@ -179,7 +179,7 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid, Datum reloptio
         * Toast tables for regular relations go in pg_toast; those for temp
         * relations go into the per-backend temp-toast-table namespace.
         */
-       if (rel->rd_istemp)
+       if (rel->rd_islocaltemp)
                namespaceid = GetTempToastNamespace();
        else
                namespaceid = PG_TOAST_NAMESPACE;
index 8d9c1e6a01ec7b1766d6a3640fa4ebabc6c2bcd6..79e0cf81f220e841151f4789042174c7c3463627 100644 (file)
@@ -213,7 +213,7 @@ analyze_rel(Oid relid, VacuumStmt *vacstmt,
         * probably not up-to-date on disk.  (We don't throw a warning here; it
         * would just lead to chatter during a database-wide ANALYZE.)
         */
-       if (isOtherTempNamespace(RelationGetNamespace(onerel)))
+       if (RELATION_IS_OTHER_TEMP(onerel))
        {
                relation_close(onerel, ShareUpdateExclusiveLock);
                return;
index e08873abe1467e414ed61c943d1b48633ea6c8fd..ba1cda6a63ce3b62b7892cdcad77bbf59528dcad 100644 (file)
@@ -117,7 +117,7 @@ cluster(ClusterStmt *stmt, bool isTopLevel)
                 * Reject clustering a remote temp table ... their local buffer
                 * manager is not going to cope.
                 */
-               if (isOtherTempNamespace(RelationGetNamespace(rel)))
+               if (RELATION_IS_OTHER_TEMP(rel))
                        ereport(ERROR,
                                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                           errmsg("cannot cluster temporary tables of other sessions")));
@@ -302,7 +302,7 @@ cluster_rel(RelToCluster *rvtc, bool recheck, bool verbose)
                 * check_index_is_clusterable which is redundant, but we leave it for
                 * extra safety.
                 */
-               if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
+               if (RELATION_IS_OTHER_TEMP(OldHeap))
                {
                        relation_close(OldHeap, AccessExclusiveLock);
                        return;
@@ -465,7 +465,7 @@ check_index_is_clusterable(Relation OldHeap, Oid indexOid, bool recheck)
         * Don't allow cluster on temp tables of other backends ... their local
         * buffer manager is not going to cope.
         */
-       if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
+       if (RELATION_IS_OTHER_TEMP(OldHeap))
                ereport(ERROR,
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                           errmsg("cannot cluster temporary tables of other sessions")));
index 92e2f2cb799b02c9dfee865fd286d7817caee3f9..c8223bf9049d7c78cec95a084bb7cbdb54d5f0eb 100644 (file)
@@ -1001,8 +1001,7 @@ DoCopy(const CopyStmt *stmt, const char *queryString)
                }
 
                /* check read-only transaction */
-               if (XactReadOnly && is_from &&
-                       !isTempNamespace(RelationGetNamespace(cstate->rel)))
+               if (XactReadOnly && is_from && !cstate->rel->rd_islocaltemp)
                        ereport(ERROR,
                                        (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
                                         errmsg("transaction is read-only")));
index 8c36d7d6355fb514f95ec115bfbb670af5ad8615..4246c11aecb567922f9ca8bbb9843e1423e92675 100644 (file)
@@ -175,7 +175,7 @@ DefineIndex(RangeVar *heapRelation,
        /*
         * Don't try to CREATE INDEX on temp tables of other backends.
         */
-       if (isOtherTempNamespace(namespaceId))
+       if (RELATION_IS_OTHER_TEMP(rel))
                ereport(ERROR,
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                 errmsg("cannot create indexes on temporary tables of other sessions")));
@@ -1404,7 +1404,8 @@ ReindexDatabase(const char *databaseName, bool do_system, bool do_user)
                        continue;
 
                /* Skip temp tables of other backends; we can't reindex them at all */
-               if (isOtherTempNamespace(classtuple->relnamespace))
+               if (classtuple->relistemp &&
+                       !isTempNamespace(classtuple->relnamespace))
                        continue;
 
                /* Check user/system classification, and optionally skip */
index 8d680f87a527fb735e70b7f31134f960bad10606..0ba4c2c983cfa70cf3b8b2ee72dae942740d03ee 100644 (file)
@@ -1056,7 +1056,7 @@ truncate_check_rel(Relation rel)
         * Don't allow truncate on temp tables of other backends ... their local
         * buffer manager is not going to cope.
         */
-       if (isOtherTempNamespace(RelationGetNamespace(rel)))
+       if (RELATION_IS_OTHER_TEMP(rel))
                ereport(ERROR,
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                          errmsg("cannot truncate temporary tables of other sessions")));
@@ -1203,7 +1203,7 @@ MergeAttributes(List *schema, List *supers, bool istemp,
                                         errmsg("inherited relation \"%s\" is not a table",
                                                        parent->relname)));
                /* Permanent rels cannot inherit from temporary ones */
-               if (!istemp && isTempNamespace(RelationGetNamespace(relation)))
+               if (!istemp && relation->rd_istemp)
                        ereport(ERROR,
                                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                         errmsg("cannot inherit from temporary relation \"%s\"",
@@ -2793,7 +2793,7 @@ ATRewriteTables(List **wqueue)
                         * Don't allow rewrite on temp tables of other backends ... their
                         * local buffer manager is not going to cope.
                         */
-                       if (isOtherTempNamespace(RelationGetNamespace(OldHeap)))
+                       if (RELATION_IS_OTHER_TEMP(OldHeap))
                                ereport(ERROR,
                                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                errmsg("cannot rewrite temporary tables of other sessions")));
@@ -4603,16 +4603,16 @@ ATAddForeignKeyConstraint(AlteredTableInfo *tab, Relation rel,
         * backend has created in the temp table, because non-shared buffers are
         * used for temp tables.)
         */
-       if (isTempNamespace(RelationGetNamespace(pkrel)))
+       if (pkrel->rd_istemp)
        {
-               if (!isTempNamespace(RelationGetNamespace(rel)))
+               if (!rel->rd_istemp)
                        ereport(ERROR,
                                        (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                                         errmsg("cannot reference temporary table from permanent table constraint")));
        }
        else
        {
-               if (isTempNamespace(RelationGetNamespace(rel)))
+               if (rel->rd_istemp)
                        ereport(ERROR,
                                        (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
                                         errmsg("cannot reference permanent table from temporary table constraint")));
@@ -6690,7 +6690,7 @@ ATExecSetTableSpace(Oid tableOid, Oid newTableSpace)
         * Don't allow moving temp tables of other backends ... their local buffer
         * manager is not going to cope.
         */
-       if (isOtherTempNamespace(RelationGetNamespace(rel)))
+       if (RELATION_IS_OTHER_TEMP(rel))
                ereport(ERROR,
                                (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                 errmsg("cannot move temporary tables of other sessions")));
@@ -6901,8 +6901,7 @@ ATExecAddInherit(Relation child_rel, RangeVar *parent)
        ATSimplePermissions(parent_rel, false);
 
        /* Permanent rels cannot inherit from temporary ones */
-       if (!isTempNamespace(RelationGetNamespace(child_rel)) &&
-               isTempNamespace(RelationGetNamespace(parent_rel)))
+       if (parent_rel->rd_istemp && !child_rel->rd_istemp)
                ereport(ERROR,
                                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                 errmsg("cannot inherit from temporary relation \"%s\"",
index 25f36585c30e72ce86b3c3ef5e745948e30b5531..ef0a3dce685dbe55606c4cb711d8f21b2afcf49d 100644 (file)
@@ -1147,7 +1147,7 @@ vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast, bool for_wraparound,
         * warning here; it would just lead to chatter during a database-wide
         * VACUUM.)
         */
-       if (isOtherTempNamespace(RelationGetNamespace(onerel)))
+       if (RELATION_IS_OTHER_TEMP(onerel))
        {
                relation_close(onerel, lmode);
                PopActiveSnapshot();
index 6698917987011bcc1d40eb14eacdf2eab0a225b7..0d0bfd01043a040170b2f21df2bee67370daee62 100644 (file)
@@ -1258,21 +1258,23 @@ expand_inherited_rtentry(PlannerInfo *root, RangeTblEntry *rte, Index rti)
                Index           childRTindex;
                AppendRelInfo *appinfo;
 
+               /* Open rel, acquire the appropriate lock type */
+               if (childOID != parentOID)
+                       newrelation = heap_open(childOID, lockmode);
+               else
+                       newrelation = oldrelation;
+
                /*
                 * It is possible that the parent table has children that are temp
                 * tables of other backends.  We cannot safely access such tables
                 * (because of buffering issues), and the best thing to do seems to be
                 * to silently ignore them.
                 */
-               if (childOID != parentOID &&
-                       isOtherTempNamespace(get_rel_namespace(childOID)))
+               if (childOID != parentOID && RELATION_IS_OTHER_TEMP(newrelation))
+               {
+                       heap_close(newrelation, lockmode);
                        continue;
-
-               /* Open rel, acquire the appropriate lock type */
-               if (childOID != parentOID)
-                       newrelation = heap_open(childOID, lockmode);
-               else
-                       newrelation = oldrelation;
+               }
 
                /*
                 * Build an RTE for the child, and attach to query's rangetable list.
index 94bbb8dca9f0115e84e0057e640d98f4e950450c..20a5d707486af4085c927ac164965b2e764f30c5 100644 (file)
@@ -1942,7 +1942,6 @@ do_autovacuum(void)
                bool            dovacuum;
                bool            doanalyze;
                bool            wraparound;
-               int                     backendID;
 
                relid = HeapTupleGetOid(tuple);
 
@@ -1959,10 +1958,12 @@ do_autovacuum(void)
                 * Check if it is a temp table (presumably, of some other backend's).
                 * We cannot safely process other backends' temp tables.
                 */
-               backendID = GetTempNamespaceBackendId(classForm->relnamespace);
-
-               if (backendID > 0)
+               if (classForm->relistemp)
                {
+                       int                     backendID;
+
+                       backendID = GetTempNamespaceBackendId(classForm->relnamespace);
+
                        /* We just ignore it if the owning backend is still active */
                        if (backendID == MyBackendId || !BackendIdIsActive(backendID))
                        {
@@ -2052,10 +2053,9 @@ do_autovacuum(void)
                bool            wraparound;
 
                /*
-                * Skip temp tables (i.e. those in temp namespaces).  We cannot safely
-                * process other backends' temp tables.
+                * We cannot safely process other backends' temp tables, so skip 'em.
                 */
-               if (isAnyTempNamespace(classForm->relnamespace))
+               if (classForm->relistemp)
                        continue;
 
                relid = HeapTupleGetOid(tuple);
index 9d47120123b958ab9c9c6e87b253137a270315cf..856e4825537d904a2e11ed789ac3c9892cb8345b 100644 (file)
@@ -122,6 +122,12 @@ PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
 
        if (reln->rd_istemp)
        {
+               /* see comments in ReadBufferExtended */
+               if (RELATION_IS_OTHER_TEMP(reln))
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                        errmsg("cannot access temporary tables of other sessions")));
+
                /* pass it off to localbuf.c */
                LocalPrefetchBuffer(reln->rd_smgr, forkNum, blockNum);
        }
@@ -204,6 +210,16 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
        /* Open it at the smgr level if not already done */
        RelationOpenSmgr(reln);
 
+       /*
+        * Reject attempts to read non-local temporary relations; we would
+        * be likely to get wrong data since we have no visibility into the
+        * owning session's local buffers.
+        */
+       if (RELATION_IS_OTHER_TEMP(reln))
+               ereport(ERROR,
+                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                errmsg("cannot access temporary tables of other sessions")));
+
        /*
         * Read the buffer, and update pgstat counters to reflect a cache
         * hit or miss.
@@ -220,6 +236,8 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 /*
  * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
  *             a relcache entry for the relation.
+ *
+ * NB: caller is assumed to know what it's doing if isTemp is true.
  */
 Buffer
 ReadBufferWithoutRelcache(RelFileNode rnode, bool isTemp,
index 3eede5020eac5f277914b297256917fd0023ada8..5b2fe5159214ace1e33d66fab6d6108eed5bcc2d 100644 (file)
@@ -829,7 +829,11 @@ RelationBuildDesc(Oid targetRelId, Relation oldrelation)
        relation->rd_isnailed = false;
        relation->rd_createSubid = InvalidSubTransactionId;
        relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
-       relation->rd_istemp = isTempOrToastNamespace(relation->rd_rel->relnamespace);
+       relation->rd_istemp = relation->rd_rel->relistemp;
+       if (relation->rd_istemp)
+               relation->rd_islocaltemp = isTempOrToastNamespace(relation->rd_rel->relnamespace);
+       else
+               relation->rd_islocaltemp = false;
 
        /*
         * initialize the tuple descriptor (relation->rd_att).
@@ -1375,6 +1379,7 @@ formrdesc(const char *relationName, Oid relationReltype,
        relation->rd_createSubid = InvalidSubTransactionId;
        relation->rd_newRelfilenodeSubid = InvalidSubTransactionId;
        relation->rd_istemp = false;
+       relation->rd_islocaltemp = false;
 
        /*
         * initialize relation tuple form
@@ -2355,8 +2360,9 @@ RelationBuildLocalRelation(const char *relname,
        /* must flag that we have rels created in this transaction */
        need_eoxact_work = true;
 
-       /* is it a temporary relation? */
+       /* it is temporary if and only if it is in my temp-table namespace */
        rel->rd_istemp = isTempOrToastNamespace(relnamespace);
+       rel->rd_islocaltemp = rel->rd_istemp;
 
        /*
         * create a new tuple descriptor from the one passed in.  We do this
@@ -2403,9 +2409,7 @@ RelationBuildLocalRelation(const char *relname,
         * as the logical ID (OID).
         */
        rel->rd_rel->relisshared = shared_relation;
-
-       /* it is temporary if and only if it is in my temp-table namespace */
-       rel->rd_rel->relistemp = isTempOrToastNamespace(relnamespace);
+       rel->rd_rel->relistemp = rel->rd_istemp;
 
        RelationGetRelid(rel) = relid;
 
index 8eeec805fe742bae2db1be1db5c4cc8bfea49eaf..f7901dfb3e1c6f104f6d7eae862779e938aea1c8 100644 (file)
@@ -126,7 +126,8 @@ typedef struct RelationData
        BlockNumber rd_targblock;       /* current insertion target block, or
                                                                 * InvalidBlockNumber */
        int                     rd_refcnt;              /* reference count */
-       bool            rd_istemp;              /* rel uses the local buffer mgr */
+       bool            rd_istemp;              /* rel is a temporary relation */
+       bool            rd_islocaltemp; /* rel is a temp rel of this session */
        bool            rd_isnailed;    /* rel is nailed in cache */
        bool            rd_isvalid;             /* relcache entry is valid */
        char            rd_indexvalid;  /* state of rd_indexlist: 0 = not valid, 1 =
@@ -355,9 +356,18 @@ typedef struct StdRdOptions
  * Beware of multiple eval of argument
  */
 #define RELATION_IS_LOCAL(relation) \
-       ((relation)->rd_istemp || \
+       ((relation)->rd_islocaltemp || \
         (relation)->rd_createSubid != InvalidSubTransactionId)
 
+/*
+ * RELATION_IS_OTHER_TEMP
+ *             Test for a temporary relation that belongs to some other session.
+ *
+ * Beware of multiple eval of argument
+ */
+#define RELATION_IS_OTHER_TEMP(relation) \
+       ((relation)->rd_istemp && !(relation)->rd_islocaltemp)
+
 /* routines in utils/cache/relcache.c */
 extern void RelationIncrementReferenceCount(Relation rel);
 extern void RelationDecrementReferenceCount(Relation rel);