]> git.ipfire.org Git - thirdparty/postgresql.git/commitdiff
Fix misbehavior with expression indexes on ON COMMIT DELETE ROWS tables.
authorTom Lane <tgl@sss.pgh.pa.us>
Sun, 1 Dec 2019 18:09:26 +0000 (13:09 -0500)
committerTom Lane <tgl@sss.pgh.pa.us>
Sun, 1 Dec 2019 18:09:26 +0000 (13:09 -0500)
We implement ON COMMIT DELETE ROWS by truncating tables marked that
way, which requires also truncating/rebuilding their indexes.  But
RelationTruncateIndexes asks the relcache for up-to-date copies of any
index expressions, which may cause execution of eval_const_expressions
on them, which can result in actual execution of subexpressions.
This is a bad thing to have happening during ON COMMIT.  Manuel Rigger
reported that use of a SQL function resulted in crashes due to
expectations that ActiveSnapshot would be set, which it isn't.
The most obvious fix perhaps would be to push a snapshot during
PreCommit_on_commit_actions, but I think that would just open the door
to more problems: CommitTransaction explicitly expects that no
user-defined code can be running at this point.

Fortunately, since we know that no tuples exist to be indexed, there
seems no need to use the real index expressions or predicates during
RelationTruncateIndexes.  We can set up dummy index expressions
instead (we do need something that will expose the right data type,
as there are places that build index tupdescs based on this), and
just ignore predicates and exclusion constraints.

In a green field it'd likely be better to reimplement ON COMMIT DELETE
ROWS using the same "init fork" infrastructure used for unlogged
relations.  That seems impractical without catalog changes though,
and even without that it'd be too big a change to back-patch.
So for now do it like this.

Per private report from Manuel Rigger.  This has been broken forever,
so back-patch to all supported branches.

src/backend/catalog/heap.c
src/backend/catalog/index.c
src/backend/utils/cache/relcache.c
src/include/catalog/index.h
src/include/utils/relcache.h
src/test/regress/expected/temp.out
src/test/regress/sql/temp.sql

index 9e7b1186ee9b3ee6f48344e2fd4ad7fa2bced2ed..03d65a2d8a4d9aeab671c889d6d8f80cb5b584a6 100644 (file)
@@ -3065,8 +3065,15 @@ RelationTruncateIndexes(Relation heapRelation)
                /* Open the index relation; use exclusive lock, just to be sure */
                currentIndex = index_open(indexId, AccessExclusiveLock);
 
-               /* Fetch info needed for index_build */
-               indexInfo = BuildIndexInfo(currentIndex);
+               /*
+                * Fetch info needed for index_build.  Since we know there are no
+                * tuples that actually need indexing, we can use a dummy IndexInfo.
+                * This is slightly cheaper to build, but the real point is to avoid
+                * possibly running user-defined code in index expressions or
+                * predicates.  We might be getting invoked during ON COMMIT
+                * processing, and we don't want to run any such code then.
+                */
+               indexInfo = BuildDummyIndexInfo(currentIndex);
 
                /*
                 * Now truncate the actual file (and discard buffers).
index d959b7cc819f0c5a94d07a95aacdae42ccfc372f..be363ce4dc3a75c50085bf21220804eeaf074b0e 100644 (file)
@@ -1838,6 +1838,75 @@ BuildIndexInfo(Relation index)
        return ii;
 }
 
+/* ----------------
+ *             BuildDummyIndexInfo
+ *                     Construct a dummy IndexInfo record for an open index
+ *
+ * This differs from the real BuildIndexInfo in that it will never run any
+ * user-defined code that might exist in index expressions or predicates.
+ * Instead of the real index expressions, we return null constants that have
+ * the right types/typmods/collations.  Predicates and exclusion clauses are
+ * just ignored.  This is sufficient for the purpose of truncating an index,
+ * since we will not need to actually evaluate the expressions or predicates;
+ * the only thing that's likely to be done with the data is construction of
+ * a tupdesc describing the index's rowtype.
+ * ----------------
+ */
+IndexInfo *
+BuildDummyIndexInfo(Relation index)
+{
+       IndexInfo  *ii = makeNode(IndexInfo);
+       Form_pg_index indexStruct = index->rd_index;
+       int                     i;
+       int                     numAtts;
+
+       /* check the number of keys, and copy attr numbers into the IndexInfo */
+       numAtts = indexStruct->indnatts;
+       if (numAtts < 1 || numAtts > INDEX_MAX_KEYS)
+               elog(ERROR, "invalid indnatts %d for index %u",
+                        numAtts, RelationGetRelid(index));
+       ii->ii_NumIndexAttrs = numAtts;
+       ii->ii_NumIndexKeyAttrs = indexStruct->indnkeyatts;
+       Assert(ii->ii_NumIndexKeyAttrs != 0);
+       Assert(ii->ii_NumIndexKeyAttrs <= ii->ii_NumIndexAttrs);
+
+       for (i = 0; i < numAtts; i++)
+               ii->ii_IndexAttrNumbers[i] = indexStruct->indkey.values[i];
+
+       /* fetch dummy expressions for expressional indexes */
+       ii->ii_Expressions = RelationGetDummyIndexExpressions(index);
+       ii->ii_ExpressionsState = NIL;
+
+       /* pretend there is no predicate */
+       ii->ii_Predicate = NIL;
+       ii->ii_PredicateState = NULL;
+
+       /* We ignore the exclusion constraint if any */
+       ii->ii_ExclusionOps = NULL;
+       ii->ii_ExclusionProcs = NULL;
+       ii->ii_ExclusionStrats = NULL;
+
+       /* other info */
+       ii->ii_Unique = indexStruct->indisunique;
+       ii->ii_ReadyForInserts = IndexIsReady(indexStruct);
+       /* assume not doing speculative insertion for now */
+       ii->ii_UniqueOps = NULL;
+       ii->ii_UniqueProcs = NULL;
+       ii->ii_UniqueStrats = NULL;
+
+       /* initialize index-build state to default */
+       ii->ii_Concurrent = false;
+       ii->ii_BrokenHotChain = false;
+       ii->ii_ParallelWorkers = 0;
+
+       /* set up for possible use by index AM */
+       ii->ii_Am = index->rd_rel->relam;
+       ii->ii_AmCache = NULL;
+       ii->ii_Context = CurrentMemoryContext;
+
+       return ii;
+}
+
 /*
  * CompareIndexInfo
  *             Return whether the properties of two indexes (in different tables)
index e2568a21c3e8f5efbc1c4d2cfcc5535817281db7..9d017037919c491e7c89513b98532da3e4884777 100644 (file)
@@ -67,6 +67,7 @@
 #include "commands/policy.h"
 #include "commands/trigger.h"
 #include "miscadmin.h"
+#include "nodes/makefuncs.h"
 #include "nodes/nodeFuncs.h"
 #include "optimizer/clauses.h"
 #include "optimizer/cost.h"
@@ -4647,6 +4648,57 @@ RelationGetIndexExpressions(Relation relation)
        return result;
 }
 
+/*
+ * RelationGetDummyIndexExpressions -- get dummy expressions for an index
+ *
+ * Return a list of dummy expressions (just Const nodes) with the same
+ * types/typmods/collations as the index's real expressions.  This is
+ * useful in situations where we don't want to run any user-defined code.
+ */
+List *
+RelationGetDummyIndexExpressions(Relation relation)
+{
+       List       *result;
+       Datum           exprsDatum;
+       bool            isnull;
+       char       *exprsString;
+       List       *rawExprs;
+       ListCell   *lc;
+
+       /* Quick exit if there is nothing to do. */
+       if (relation->rd_indextuple == NULL ||
+               heap_attisnull(relation->rd_indextuple, Anum_pg_index_indexprs, NULL))
+               return NIL;
+
+       /* Extract raw node tree(s) from index tuple. */
+       exprsDatum = heap_getattr(relation->rd_indextuple,
+                                                         Anum_pg_index_indexprs,
+                                                         GetPgIndexDescriptor(),
+                                                         &isnull);
+       Assert(!isnull);
+       exprsString = TextDatumGetCString(exprsDatum);
+       rawExprs = (List *) stringToNode(exprsString);
+       pfree(exprsString);
+
+       /* Construct null Consts; the typlen and typbyval are arbitrary. */
+       result = NIL;
+       foreach(lc, rawExprs)
+       {
+               Node       *rawExpr = (Node *) lfirst(lc);
+
+               result = lappend(result,
+                                                makeConst(exprType(rawExpr),
+                                                                  exprTypmod(rawExpr),
+                                                                  exprCollation(rawExpr),
+                                                                  1,
+                                                                  (Datum) 0,
+                                                                  true,
+                                                                  true));
+       }
+
+       return result;
+}
+
 /*
  * RelationGetIndexPredicate -- get the index predicate for an index
  *
index 35a29f3498f1b423d4ba33e848af5ef4d339d625..feaf760f51a39edd296f170f794908dc5c3b2367 100644 (file)
@@ -91,6 +91,8 @@ extern void index_drop(Oid indexId, bool concurrent);
 
 extern IndexInfo *BuildIndexInfo(Relation index);
 
+extern IndexInfo *BuildDummyIndexInfo(Relation index);
+
 extern bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2,
                                 Oid *collations1, Oid *collations2,
                                 Oid *opfamilies1, Oid *opfamilies2,
index dbbf41b0c16d8008f42909a294bf6933d3321215..54394303a8578de89dd4f768ccc9522505c0cf4c 100644 (file)
@@ -49,6 +49,7 @@ extern Oid    RelationGetOidIndex(Relation relation);
 extern Oid     RelationGetPrimaryKeyIndex(Relation relation);
 extern Oid     RelationGetReplicaIndex(Relation relation);
 extern List *RelationGetIndexExpressions(Relation relation);
+extern List *RelationGetDummyIndexExpressions(Relation relation);
 extern List *RelationGetIndexPredicate(Relation relation);
 
 typedef enum IndexAttrBitmapKind
index ed0053904ea6045f84581346a052d132cc16a4d7..5fa20a05bfe4768b448e918f495b7a1fae86e91a 100644 (file)
@@ -49,6 +49,8 @@ LINE 1: SELECT * FROM temptest;
                       ^
 -- Test ON COMMIT DELETE ROWS
 CREATE TEMP TABLE temptest(col int) ON COMMIT DELETE ROWS;
+-- while we're here, verify successful truncation of index with SQL function
+CREATE INDEX ON temptest(bit_length(''));
 BEGIN;
 INSERT INTO temptest VALUES (1);
 INSERT INTO temptest VALUES (2);
index 470e165b850e03e4acf131df5b232acaec2d39cc..fdef2b0f978fdced17fb0eca669442e2003a842e 100644 (file)
@@ -55,6 +55,9 @@ SELECT * FROM temptest;
 
 CREATE TEMP TABLE temptest(col int) ON COMMIT DELETE ROWS;
 
+-- while we're here, verify successful truncation of index with SQL function
+CREATE INDEX ON temptest(bit_length(''));
+
 BEGIN;
 INSERT INTO temptest VALUES (1);
 INSERT INTO temptest VALUES (2);