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 1hnxzS-00072z-EF for pgsql-bugs@arkaria.postgresql.org; Thu, 18 Jul 2019 04:25:59 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1hnxzQ-00035K-T5 for pgsql-bugs@arkaria.postgresql.org; Thu, 18 Jul 2019 04:25:56 +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 1hnxzO-000352-So for pgsql-bugs@lists.postgresql.org; Thu, 18 Jul 2019 04:25:56 +0000 Received: from wout2-smtp.messagingengine.com ([64.147.123.25]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.92) (envelope-from ) id 1hnxzK-0004bZ-O4 for pgsql-bugs@lists.postgresql.org; Thu, 18 Jul 2019 04:25:53 +0000 Received: from compute4.internal (compute4.nyi.internal [10.202.2.44]) by mailout.west.internal (Postfix) with ESMTP id D0C4A4BE; Thu, 18 Jul 2019 00:25:47 -0400 (EDT) Received: from mailfrontend2 ([10.202.2.163]) by compute4.internal (MEProxy); Thu, 18 Jul 2019 00:25:48 -0400 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=fm2; bh=m37zxj24vRN3Z8xDT/FLtX4Xktq 4or4HQJA3FMEM3e8=; b=GkjPZVXyUroj1wCnNYWfXeyB4trLidCWxVkEAdAqkdB +MCCSQdfGt5I9BVrkWUSy0YRwAUVh56rPKywNjCz+1ruTQxnq3Yv/vEzAOX6EHhg 53LBk/MsP63jn/Dc5YJlt4uKn7OlqJUevc16Fmzza2kpWpRia54JdqVjN0C8Pzyc DKzmTXdpwW2JOJfVtRec7cw4DpIRGv502sxQ7/ARl01IhZPdIJ07zW251CO0RxIy oyhRRp0YDZmKHBvo77QdTD9lgV23N0mZ6eOypsiqtODzxmCVOZ5WyJSd0m6SJp0t KGj25b57VtEHe52JUsxOqFNH6940o4yzlJqQhNo5RDg== 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=fm3; bh=m37zxj 24vRN3Z8xDT/FLtX4Xktq4or4HQJA3FMEM3e8=; b=sqb/GB6zFisLUf+SRLyeOc VQ4tQuJwcIL5BgsFgKcAsjGvJ8q1iD6o5XyN7k1H+7csMYsZUT7chHg93MqPm+9I k7/u9+FPbS/0rS3ahJJeY1kZSXFgqsfCklWwJVT2vphC21aMOIYCGHFo/rv7HXgY PbGUyScw6ANoYoCCdcTCa/AXymrXJX8GhWh+I+Sxig6EXq+THQwjT8bxsp1EpTnB oBkU/68Ud1rjptkgEmGudiY3HH822Q+tVgmzyKomGqRCXT08gDww23CDJGXjlULa MrcUoQB9O/QUHE+agyQa7bBTSR2wugoy6das2MktR03yeylaXUGzyuceVp0lkNRg == X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeduvddrieeggdekvdcutefuodetggdotefrodftvf curfhrohhfihhlvgemucfhrghsthforghilhdpqfgfvfdpuffrtefokffrpgfnqfghnecu uegrihhlohhuthemuceftddtnecusecvtfgvtghiphhivghnthhsucdlqddutddtmdenfg hrlhcuvffnffculdejtddmnecujfgurhepfffhvffukfhfgggtuggjsehgtderredttddv necuhfhrohhmpefoihgthhgrvghlucfrrghquhhivghruceomhhitghhrggvlhesphgrqh huihgvrhdrgiihiieqnecukfhppeduuddurddutddvrddukedtrddukeehnecurfgrrhgr mhepmhgrihhlfhhrohhmpehmihgthhgrvghlsehprghquhhivghrrdighiiinecuvehluh hsthgvrhfuihiivgeptd X-ME-Proxy: Received: from paquier.xyz (ee0822lan1.rev.em-net.ne.jp [111.102.180.185]) by mail.messagingengine.com (Postfix) with ESMTPA id EA52C380075; Thu, 18 Jul 2019 00:25:45 -0400 (EDT) Date: Thu, 18 Jul 2019 13:25:43 +0900 From: Michael Paquier To: Manuel Rigger Cc: PostgreSQL mailing lists Subject: Re: REINDEX CONCURRENTLY causes ALTER TABLE to fail Message-ID: <20190718042543.GE1416@paquier.xyz> References: <20190718030232.GD1416@paquier.xyz> MIME-Version: 1.0 Content-Type: multipart/signed; micalg=pgp-sha512; protocol="application/pgp-signature"; boundary="DO5DiztRLs659m5i" Content-Disposition: inline In-Reply-To: <20190718030232.GD1416@paquier.xyz> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk --DO5DiztRLs659m5i Content-Type: multipart/mixed; boundary="fWddYNRDgTk9wQGZ" Content-Disposition: inline --fWddYNRDgTk9wQGZ Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Thu, Jul 18, 2019 at 12:02:32PM +0900, Michael Paquier wrote: > There are a couple of approaches that we could do to fix that. The > first one I could think about is to change the relcache level so as we > don't apply planner-level optimizations when creating a concurrent > index entry. Another one, which is less invasive, is to just update > the list of expressions and predicates after calling > BuildIndexInfo(). Still that means overriding the contents of the > relcache with what has been optimized for the planner to what we want > to use for the reindex build and I think that this weakens the logic > of index_build. I have done some work on that, and for now I am finishing with the attached. This takes the approach of updating BuildIndexInfo() so as the optimizations for the planner are not done. That's not completely right yet though as even if it passes your initial test case, this does not allow the index expressions and predicates to have an exact match. I have designed a test case for this purpose which stores the contents of pg_node_tree before and after the REINDEX and even if the collation gets right, all the location fields from pg_node_tree get reset. The solution is not complete, still the test case is quite useful. So even if the solution happens to not be like the attached, I'd rather keep the test case and perhaps extend it. -- Michael --fWddYNRDgTk9wQGZ Content-Type: text/x-diff; charset=us-ascii Content-Disposition: attachment; filename="reindex-conc-predicates-v1.patch" Content-Transfer-Encoding: quoted-printable diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtre= e.c index 9126c18d0e..6bfce99ca2 100644 --- a/contrib/amcheck/verify_nbtree.c +++ b/contrib/amcheck/verify_nbtree.c @@ -514,7 +514,7 @@ bt_check_every_level(Relation rel, Relation heaprel, bo= ol heapkeyspace, */ if (state->heapallindexed) { - IndexInfo *indexinfo =3D BuildIndexInfo(state->rel); + IndexInfo *indexinfo =3D BuildIndexInfo(state->rel, true); TableScanDesc scan; =20 /* Report on extra downlink checks performed in readonly case */ diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c index ae7b729edd..ab68840ebc 100644 --- a/src/backend/access/brin/brin.c +++ b/src/backend/access/brin/brin.c @@ -1370,7 +1370,7 @@ brinsummarize(Relation index, Relation heapRel, Block= Number pageRange, Assert(!indexInfo); state =3D initialize_brin_buildstate(index, revmap, pagesPerRange); - indexInfo =3D BuildIndexInfo(index); + indexInfo =3D BuildIndexInfo(index, true); } summarize_range(indexInfo, state, heapRel, startBlk, heapNumBlocks); =20 diff --git a/src/backend/access/nbtree/nbtsort.c b/src/backend/access/nbtre= e/nbtsort.c index d0b9013caf..b73c40ee8b 100644 --- a/src/backend/access/nbtree/nbtsort.c +++ b/src/backend/access/nbtree/nbtsort.c @@ -1766,7 +1766,7 @@ _bt_parallel_scan_and_sort(BTSpool *btspool, BTSpool = *btspool2, buildstate.btleader =3D NULL; =20 /* Join parallel scan */ - indexInfo =3D BuildIndexInfo(btspool->index); + indexInfo =3D BuildIndexInfo(btspool->index, true); indexInfo->ii_Concurrent =3D btshared->isconcurrent; scan =3D table_beginscan_parallel(btspool->heap, ParallelTableScanFromBTShared(btshared)); diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c index 032fab9ac4..4db8f0615e 100644 --- a/src/backend/catalog/heap.c +++ b/src/backend/catalog/heap.c @@ -3149,7 +3149,7 @@ RelationTruncateIndexes(Relation heapRelation) currentIndex =3D index_open(indexId, AccessExclusiveLock); =20 /* Fetch info needed for index_build */ - indexInfo =3D BuildIndexInfo(currentIndex); + indexInfo =3D BuildIndexInfo(currentIndex, true); =20 /* * Now truncate the actual file (and discard buffers). diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c index 9234e93261..80eaddb59a 100644 --- a/src/backend/catalog/index.c +++ b/src/backend/catalog/index.c @@ -1212,7 +1212,7 @@ index_concurrently_create_copy(Relation heapRelation,= Oid oldIndexId, const char indexRelation =3D index_open(oldIndexId, RowExclusiveLock); =20 /* New index uses the same index information as old index */ - indexInfo =3D BuildIndexInfo(indexRelation); + indexInfo =3D BuildIndexInfo(indexRelation, false); =20 /* Get the array of class and column options IDs from index info */ indexTuple =3D SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldIndexId)); @@ -1312,7 +1312,7 @@ index_concurrently_build(Oid heapRelationId, * commit of the transaction where this concurrent index was created at * the catalog level. */ - indexInfo =3D BuildIndexInfo(indexRelation); + indexInfo =3D BuildIndexInfo(indexRelation, true); Assert(!indexInfo->ii_ReadyForInserts); indexInfo->ii_Concurrent =3D true; indexInfo->ii_BrokenHotChain =3D false; @@ -2162,10 +2162,14 @@ index_drop(Oid indexId, bool concurrent, bool concu= rrent_lock_mode) * FormIndexDatum, which is used for both index_build() and later insertion * of individual index tuples. Normally we build an IndexInfo for an index * just once per command, and then use it for (potentially) many tuples. + * + * If "optimize" is true, index expressions and predicates are not made + * planner-ready. This is used by REINDEX CONCURRENTLY when creating a + * duplicate index entry rebuilt concurrently. * ---------------- */ IndexInfo * -BuildIndexInfo(Relation index) +BuildIndexInfo(Relation index, bool optimize) { IndexInfo *ii =3D makeNode(IndexInfo); Form_pg_index indexStruct =3D index->rd_index; @@ -2186,11 +2190,11 @@ BuildIndexInfo(Relation index) ii->ii_IndexAttrNumbers[i] =3D indexStruct->indkey.values[i]; =20 /* fetch any expressions needed for expressional indexes */ - ii->ii_Expressions =3D RelationGetIndexExpressions(index); + ii->ii_Expressions =3D RelationGetIndexExpressions(index, optimize); ii->ii_ExpressionsState =3D NIL; =20 /* fetch index predicate if any */ - ii->ii_Predicate =3D RelationGetIndexPredicate(index); + ii->ii_Predicate =3D RelationGetIndexPredicate(index, optimize); ii->ii_PredicateState =3D NULL; =20 /* fetch exclusion constraint info if any */ @@ -3034,7 +3038,7 @@ validate_index(Oid heapId, Oid indexId, Snapshot snap= shot) * passed in from DefineIndex, but its copy is long gone due to having * been built in a previous transaction.) */ - indexInfo =3D BuildIndexInfo(indexRelation); + indexInfo =3D BuildIndexInfo(indexRelation, true); =20 /* mark build is concurrent just for consistency */ indexInfo->ii_Concurrent =3D true; @@ -3322,7 +3326,7 @@ reindex_index(Oid indexId, bool skip_constraint_check= s, char persistence, TransferPredicateLocksToHeapRelation(iRel); =20 /* Fetch info needed for index_build */ - indexInfo =3D BuildIndexInfo(iRel); + indexInfo =3D BuildIndexInfo(iRel, true); =20 /* If requested, skip checking uniqueness/exclusion constraints */ if (skip_constraint_checks) diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 8d633f2585..3f5b05b325 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -434,7 +434,7 @@ do_analyze_rel(Relation onerel, VacuumParams *params, AnlIndexData *thisdata =3D &indexdata[ind]; IndexInfo *indexInfo; =20 - thisdata->indexInfo =3D indexInfo =3D BuildIndexInfo(Irel[ind]); + thisdata->indexInfo =3D indexInfo =3D BuildIndexInfo(Irel[ind], true); thisdata->tupleFract =3D 1.0; /* fix later if partial */ if (indexInfo->ii_Expressions !=3D NIL && va_cols =3D=3D NIL) { diff --git a/src/backend/commands/constraint.c b/src/backend/commands/const= raint.c index 806962a686..05fef01e79 100644 --- a/src/backend/commands/constraint.c +++ b/src/backend/commands/constraint.c @@ -132,7 +132,7 @@ unique_key_recheck(PG_FUNCTION_ARGS) */ indexRel =3D index_open(trigdata->tg_trigger->tgconstrindid, RowExclusiveLock); - indexInfo =3D BuildIndexInfo(indexRel); + indexInfo =3D BuildIndexInfo(indexRel, true); =20 /* * Typically the index won't have expressions, but if it does we need an diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexc= mds.c index fd299273c5..42675360ef 100644 --- a/src/backend/commands/indexcmds.c +++ b/src/backend/commands/indexcmds.c @@ -1121,7 +1121,7 @@ DefineIndex(Oid relationId, continue; =20 cldidx =3D index_open(cldidxid, lockmode); - cldIdxInfo =3D BuildIndexInfo(cldidx); + cldIdxInfo =3D BuildIndexInfo(cldidx, true); if (CompareIndexInfo(cldIdxInfo, indexInfo, cldidx->rd_indcollation, collationObjectId, diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c index 537d0e8cef..5dfd06447e 100644 --- a/src/backend/commands/matview.c +++ b/src/backend/commands/matview.c @@ -871,7 +871,7 @@ is_usable_unique_index(Relation indexRel) indexStruct->indimmediate && indexRel->rd_rel->relam =3D=3D BTREE_AM_OID && indexStruct->indisvalid && - RelationGetIndexPredicate(indexRel) =3D=3D NIL && + RelationGetIndexPredicate(indexRel, true) =3D=3D NIL && indexStruct->indnatts > 0) { /* diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablec= mds.c index fc1c4dfa4c..7ba1bfdfeb 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -7242,7 +7242,7 @@ ATExecAddIndexConstraint(AlteredTableInfo *tab, Relat= ion rel, =20 indexName =3D pstrdup(RelationGetRelationName(indexRel)); =20 - indexInfo =3D BuildIndexInfo(indexRel); + indexInfo =3D BuildIndexInfo(indexRel, true); =20 /* this should have been checked at parse time */ if (!indexInfo->ii_Unique) @@ -13817,13 +13817,13 @@ ATExecReplicaIdentity(Relation rel, ReplicaIdenti= tyStmt *stmt, LOCKMODE lockmode errmsg("cannot use non-immediate index \"%s\" as replica identity", RelationGetRelationName(indexRel)))); /* Expression indexes aren't supported. */ - if (RelationGetIndexExpressions(indexRel) !=3D NIL) + if (RelationGetIndexExpressions(indexRel, true) !=3D NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot use expression index \"%s\" as replica identity", RelationGetRelationName(indexRel)))); /* Predicate indexes aren't supported. */ - if (RelationGetIndexPredicate(indexRel) !=3D NIL) + if (RelationGetIndexPredicate(indexRel, true) !=3D NIL) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot use partial index \"%s\" as replica identity", @@ -15725,7 +15725,7 @@ AttachPartitionEnsureIndexes(Relation rel, Relation= attachrel) Oid cldIdxId =3D lfirst_oid(cell); =20 attachrelIdxRels[i] =3D index_open(cldIdxId, AccessShareLock); - attachInfos[i] =3D BuildIndexInfo(attachrelIdxRels[i]); + attachInfos[i] =3D BuildIndexInfo(attachrelIdxRels[i], true); i++; } =20 @@ -15781,7 +15781,7 @@ AttachPartitionEnsureIndexes(Relation rel, Relation= attachrel) } =20 /* construct an indexinfo to compare existing indexes against */ - info =3D BuildIndexInfo(idxRel); + info =3D BuildIndexInfo(idxRel, true); attmap =3D convert_tuples_by_name_map(RelationGetDescr(attachrel), RelationGetDescr(rel), gettext_noop("could not convert row type")); @@ -16357,8 +16357,8 @@ ATExecAttachPartitionIdx(List **wqueue, Relation pa= rentIdx, RangeVar *name) RelationGetRelationName(parentTbl)))); =20 /* Ensure the indexes are compatible */ - childInfo =3D BuildIndexInfo(partIdx); - parentInfo =3D BuildIndexInfo(parentIdx); + childInfo =3D BuildIndexInfo(partIdx, true); + parentInfo =3D BuildIndexInfo(parentIdx, true); attmap =3D convert_tuples_by_name_map(RelationGetDescr(partTbl), RelationGetDescr(parentTbl), gettext_noop("could not convert row type")); diff --git a/src/backend/executor/execIndexing.c b/src/backend/executor/exe= cIndexing.c index 40bd8049f0..4158b02f04 100644 --- a/src/backend/executor/execIndexing.c +++ b/src/backend/executor/execIndexing.c @@ -199,7 +199,7 @@ ExecOpenIndices(ResultRelInfo *resultRelInfo, bool spec= ulative) indexDesc =3D index_open(indexOid, RowExclusiveLock); =20 /* extract index key information from the index's pg_index info */ - ii =3D BuildIndexInfo(indexDesc); + ii =3D BuildIndexInfo(indexDesc, true); =20 /* * If the indexes are to be used for speculative insertion, add extra diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/p= lan/planner.c index ca3b7f29e1..076530172e 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -6307,8 +6307,8 @@ plan_create_index_workers(Oid tableOid, Oid indexOid) * safe. */ if (heap->rd_rel->relpersistence =3D=3D RELPERSISTENCE_TEMP || - !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) || - !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index))) + !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index, true= )) || + !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index, true))) { parallel_workers =3D 0; goto done; diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/u= til/plancat.c index 98e99481c6..93a300880c 100644 --- a/src/backend/optimizer/util/plancat.c +++ b/src/backend/optimizer/util/plancat.c @@ -368,8 +368,8 @@ get_relation_info(PlannerInfo *root, Oid relationObject= Id, bool inhparent, * correct varno for the parent relation, so that they match up * correctly against qual clauses. */ - info->indexprs =3D RelationGetIndexExpressions(indexRelation); - info->indpred =3D RelationGetIndexPredicate(indexRelation); + info->indexprs =3D RelationGetIndexExpressions(indexRelation, true); + info->indpred =3D RelationGetIndexPredicate(indexRelation, true); if (info->indexprs && varno !=3D 1) ChangeVarNodes((Node *) info->indexprs, 1, varno, 0); if (info->indpred && varno !=3D 1) @@ -759,7 +759,7 @@ infer_arbiter_indexes(PlannerInfo *root) goto next; =20 /* Expression attributes (if any) must match */ - idxExprs =3D RelationGetIndexExpressions(idxRel); + idxExprs =3D RelationGetIndexExpressions(idxRel, true); foreach(el, onconflict->arbiterElems) { InferenceElem *elem =3D (InferenceElem *) lfirst(el); @@ -810,7 +810,7 @@ infer_arbiter_indexes(PlannerInfo *root) * If it's a partial index, its predicate must be implied by the ON * CONFLICT's WHERE clause. */ - predExprs =3D RelationGetIndexPredicate(idxRel); + predExprs =3D RelationGetIndexPredicate(idxRel, true); =20 if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, = false)) goto next; diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_= utilcmd.c index f0f6ee7db6..4c03f38581 100644 --- a/src/backend/parser/parse_utilcmd.c +++ b/src/backend/parser/parse_utilcmd.c @@ -2078,14 +2078,14 @@ transformIndexConstraint(Constraint *constraint, Cr= eateStmtContext *cxt) errdetail("Cannot create a primary key or unique constraint using su= ch an index."), parser_errposition(cxt->pstate, constraint->location))); =20 - if (RelationGetIndexExpressions(index_rel) !=3D NIL) + if (RelationGetIndexExpressions(index_rel, true) !=3D NIL) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("index \"%s\" contains expressions", index_name), errdetail("Cannot create a primary key or unique constraint using su= ch an index."), parser_errposition(cxt->pstate, constraint->location))); =20 - if (RelationGetIndexPredicate(index_rel) !=3D NIL) + if (RelationGetIndexPredicate(index_rel, true) !=3D NIL) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("\"%s\" is a partial index", index_name), diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/r= elcache.c index 7aa5d7c7fa..5e478b785c 100644 --- a/src/backend/utils/cache/relcache.c +++ b/src/backend/utils/cache/relcache.c @@ -4570,9 +4570,13 @@ RelationGetReplicaIndex(Relation relation) * Otherwise, the returned tree is copied into the caller's memory context. * (We don't want to return a pointer to the relcache copy, since it could * disappear due to relcache invalidation.) + * + * If "optimize" is true, apply all optimizations to make this result + * usable by the planner. Non-optimized expressions are currently used + * when creating a concurrent index for REINDEX CONCURRENTLY. */ List * -RelationGetIndexExpressions(Relation relation) +RelationGetIndexExpressions(Relation relation, bool optimize) { List *result; Datum exprsDatum; @@ -4603,14 +4607,17 @@ RelationGetIndexExpressions(Relation relation) result =3D (List *) stringToNode(exprsString); pfree(exprsString); =20 - /* - * Run the expressions through eval_const_expressions. This is not just an - * optimization, but is necessary, because the planner will be comparing - * them to similarly-processed qual clauses, and may fail to detect valid - * matches without this. We must not use canonicalize_qual, however, - * since these aren't qual expressions. - */ - result =3D (List *) eval_const_expressions(NULL, (Node *) result); + if (optimize) + { + /* + * Run the expressions through eval_const_expressions. This is not just = an + * optimization, but is necessary, because the planner will be comparing + * them to similarly-processed qual clauses, and may fail to detect valid + * matches without this. We must not use canonicalize_qual, however, + * since these aren't qual expressions. + */ + result =3D (List *) eval_const_expressions(NULL, (Node *) result); + } =20 /* May as well fix opfuncids too */ fix_opfuncids((Node *) result); @@ -4627,14 +4634,18 @@ RelationGetIndexExpressions(Relation relation) * RelationGetIndexPredicate -- get the index predicate for an index * * We cache the result of transforming pg_index.indpred into an implicit-A= ND - * node tree (suitable for use in planning). + * node tree suitable for use in planning if "optimize" is true. * If the rel is not an index or has no predicate, we return NIL. * Otherwise, the returned tree is copied into the caller's memory context. * (We don't want to return a pointer to the relcache copy, since it could * disappear due to relcache invalidation.) + * + * If "optimize" is true, apply all optimizations to make this result + * usable by the planner. Non-optimized expressions are currently used + * when creating a concurrent index for REINDEX CONCURRENTLY. */ List * -RelationGetIndexPredicate(Relation relation) +RelationGetIndexPredicate(Relation relation, bool optimize) { List *result; Datum predDatum; @@ -4665,24 +4676,28 @@ RelationGetIndexPredicate(Relation relation) result =3D (List *) stringToNode(predString); pfree(predString); =20 - /* - * Run the expression through const-simplification and canonicalization. - * This is not just an optimization, but is necessary, because the planner - * will be comparing it to similarly-processed qual clauses, and may fail - * to detect valid matches without this. This must match the processing - * done to qual clauses in preprocess_expression()! (We can skip the - * stuff involving subqueries, however, since we don't allow any in index - * predicates.) - */ - result =3D (List *) eval_const_expressions(NULL, (Node *) result); + if (optimize) + { + /* + * Run the expression through const-simplification and canonicalization. + * This is not just an optimization, but is necessary, because the plann= er + * will be comparing it to similarly-processed qual clauses, and may fail + * to detect valid matches without this. This must match the processing + * done to qual clauses in preprocess_expression()! (We can skip the + * stuff involving subqueries, however, since we don't allow any in index + * predicates.) + */ + result =3D (List *) eval_const_expressions(NULL, (Node *) result); =20 - result =3D (List *) canonicalize_qual((Expr *) result, false); + result =3D (List *) canonicalize_qual((Expr *) result, false); + } =20 /* Also convert to implicit-AND format */ result =3D make_ands_implicit((Expr *) result); =20 /* May as well fix opfuncids too */ - fix_opfuncids((Node *) result); + if (optimize) + fix_opfuncids((Node *) result); =20 /* Now save a copy of the completed tree in the relcache entry. */ oldcxt =3D MemoryContextSwitchTo(relation->rd_indexcxt); diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tu= plesort.c index 7b8e67899e..cd963fda3f 100644 --- a/src/backend/utils/sort/tuplesort.c +++ b/src/backend/utils/sort/tuplesort.c @@ -915,7 +915,7 @@ tuplesort_begin_cluster(TupleDesc tupDesc, state->readtup =3D readtup_cluster; state->abbrevNext =3D 10; =20 - state->indexInfo =3D BuildIndexInfo(indexRel); + state->indexInfo =3D BuildIndexInfo(indexRel, true); =20 state->tupDesc =3D tupDesc; /* assume we need not copy tupDesc */ =20 diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h index 1113d25b2d..5b9d429e9f 100644 --- a/src/include/catalog/index.h +++ b/src/include/catalog/index.h @@ -104,7 +104,7 @@ extern ObjectAddress index_constraint_create(Relation h= eapRelation, =20 extern void index_drop(Oid indexId, bool concurrent, bool concurrent_lock_= mode); =20 -extern IndexInfo *BuildIndexInfo(Relation index); +extern IndexInfo *BuildIndexInfo(Relation index, bool optimize); =20 extern bool CompareIndexInfo(IndexInfo *info1, IndexInfo *info2, Oid *collations1, Oid *collations2, diff --git a/src/include/utils/relcache.h b/src/include/utils/relcache.h index d9c10ffcba..ee96bf0d36 100644 --- a/src/include/utils/relcache.h +++ b/src/include/utils/relcache.h @@ -47,8 +47,8 @@ extern List *RelationGetIndexList(Relation relation); extern List *RelationGetStatExtList(Relation relation); extern Oid RelationGetPrimaryKeyIndex(Relation relation); extern Oid RelationGetReplicaIndex(Relation relation); -extern List *RelationGetIndexExpressions(Relation relation); -extern List *RelationGetIndexPredicate(Relation relation); +extern List *RelationGetIndexExpressions(Relation relation, bool optimize); +extern List *RelationGetIndexPredicate(Relation relation, bool optimize); =20 typedef enum IndexAttrBitmapKind { diff --git a/src/test/regress/expected/create_index.out b/src/test/regress/= expected/create_index.out index 9305649c11..ab419972c8 100644 --- a/src/test/regress/expected/create_index.out +++ b/src/test/regress/expected/create_index.out @@ -2170,6 +2170,40 @@ Indexes: "concur_reindex_ind5" UNIQUE, btree (c1) =20 DROP TABLE concur_reindex_tab4; +-- Check handling of indexes with expressions and predicates. +-- Run a couple of commands, then the state of the expression and +-- predicate tree stored in the catalogs before and after the rebuilds. +-- Note that the index name is used for the tree comparison as the OID +-- of an index rebuilt changes. +CREATE TEMP TABLE concur_reindex_trees ( + relname text, + indexprs_before pg_node_tree, + indexprs_after pg_node_tree, + indpred_before pg_node_tree, + indpred_after pg_node_tree); +CREATE TABLE concur_exprs_tab (c1 int , c2 boolean); +INSERT INTO concur_exprs_tab (c1, c2) VALUES (1369652450, FALSE), + (414515746, TRUE), + (897778963, FALSE); +CREATE UNIQUE INDEX concur_exprs_index ON concur_exprs_tab ((1 / c1)) + WHERE ('-H') >=3D (c2::TEXT) COLLATE "C"; +INSERT INTO concur_reindex_trees (relname, indexprs_before, indpred_before) + SELECT indexrelid::regclass, indexprs, indpred FROM pg_index + WHERE indexrelid =3D 'concur_exprs_index'::regclass; +REINDEX TABLE CONCURRENTLY concur_exprs_tab; +UPDATE concur_reindex_trees SET (indexprs_after, indpred_after) =3D + (SELECT indexprs, indpred FROM pg_index WHERE indexrelid =3D 'concur_exp= rs_index'::regclass) + WHERE relname =3D 'concur_exprs_index'; +SELECT relname, + indexprs_before =3D indexprs_after AS same_exprs, + indpred_before =3D indpred_after AS same_pred + FROM concur_reindex_trees; + relname | same_exprs | same_pred=20 +--------------------+------------+----------- + concur_exprs_index | f | f +(1 row) + +DROP TABLE concur_exprs_tab; -- -- REINDEX SCHEMA -- diff --git a/src/test/regress/sql/create_index.sql b/src/test/regress/sql/c= reate_index.sql index cd46f071bd..c92e107b35 100644 --- a/src/test/regress/sql/create_index.sql +++ b/src/test/regress/sql/create_index.sql @@ -872,6 +872,36 @@ REINDEX INDEX CONCURRENTLY concur_reindex_ind5; \d concur_reindex_tab4 DROP TABLE concur_reindex_tab4; =20 +-- Check handling of indexes with expressions and predicates. +-- Run a couple of commands, then the state of the expression and +-- predicate tree stored in the catalogs before and after the rebuilds. +-- Note that the index name is used for the tree comparison as the OID +-- of an index rebuilt changes. +CREATE TEMP TABLE concur_reindex_trees ( + relname text, + indexprs_before pg_node_tree, + indexprs_after pg_node_tree, + indpred_before pg_node_tree, + indpred_after pg_node_tree); +CREATE TABLE concur_exprs_tab (c1 int , c2 boolean); +INSERT INTO concur_exprs_tab (c1, c2) VALUES (1369652450, FALSE), + (414515746, TRUE), + (897778963, FALSE); +CREATE UNIQUE INDEX concur_exprs_index ON concur_exprs_tab ((1 / c1)) + WHERE ('-H') >=3D (c2::TEXT) COLLATE "C"; +INSERT INTO concur_reindex_trees (relname, indexprs_before, indpred_before) + SELECT indexrelid::regclass, indexprs, indpred FROM pg_index + WHERE indexrelid =3D 'concur_exprs_index'::regclass; +REINDEX TABLE CONCURRENTLY concur_exprs_tab; +UPDATE concur_reindex_trees SET (indexprs_after, indpred_after) =3D + (SELECT indexprs, indpred FROM pg_index WHERE indexrelid =3D 'concur_exp= rs_index'::regclass) + WHERE relname =3D 'concur_exprs_index'; +SELECT relname, + indexprs_before =3D indexprs_after AS same_exprs, + indpred_before =3D indpred_after AS same_pred + FROM concur_reindex_trees; +DROP TABLE concur_exprs_tab; + -- -- REINDEX SCHEMA -- --fWddYNRDgTk9wQGZ-- --DO5DiztRLs659m5i Content-Type: application/pgp-signature; name="signature.asc" -----BEGIN PGP SIGNATURE----- iQIzBAABCgAdFiEEG72nH6vTowiyblFKnvQgOdbyQH0FAl0v9McACgkQnvQgOdby QH1AwhAAqghmVcBZLfzhhQeoKFNACGCXayM+bTGr+ANA82gCxjUvX0MVWHS2dxsb maxOGchvrxZzG0iyoOQbfTuiEzcFoCjTtm8NXJ1jR7RIdClf094A/dQ+Ln6XMJ1S 1FnKgXTrsq+4BgLwjOIBubTVwGksD8PMoC3XWjBpQ1ZlQFIEhMqwNUkFV7ZDrbt1 LMsSPJFii/Ii6wUUMp5m6D7D6Ux2TN1nQUg3bdCoiz1L8PGZIGXyOwTXJaleUylr VY3pFR0TW9VG4IIpWxyXS9bw6MJTqAAbh68XMnZMXBkbVqo9QHhXVfVIP879+Cn9 UiNWBuzsF+YFTjI9HrCkewf4ig2P9iECVIm7sR9Kzh9p43B4Lt3BrmvTNAoG7FJx v8xvSF4fdierHmJQg6fCq2nIj2iFSJaLf0+B2ffdgiqE1psQsTxH9HW1A5O2qYIE /T6ewhRN9xMgWPojfNEhU54HIlANeHLlqST5JAIYj/L+Xy96tv0WSIHDHnW93ugz 9WZar/gIeNiMK01oFTLGYVrkw0F7Vl8L4673iV6FAoBFrZIfhShIgO17HiGFEaEo k+UpPCfT615qyur85hY9TUZ/piFSimVqO1LadgAuPDMJegy1h61jk4m0D/kjnqWt 5W8YW5MrxZXC7iICotUdM2OEC59KiXqqccA8t7DmFaJ5ahwbSj8= =8773 -----END PGP SIGNATURE----- --DO5DiztRLs659m5i--