| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* indexcmds.c |
| 4 |
* POSTGRES define and remove index code. |
| 5 |
* |
| 6 |
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group |
| 7 |
* Portions Copyright (c) 1994, Regents of the University of California |
| 8 |
* |
| 9 |
* |
| 10 |
* IDENTIFICATION |
| 11 |
* src/backend/commands/indexcmds.c |
| 12 |
* |
| 13 |
*------------------------------------------------------------------------- |
| 14 |
*/ |
| 15 |
|
| 16 |
#include "postgres.h" |
| 17 |
|
| 18 |
#include "access/amapi.h" |
| 19 |
#include "access/gist.h" |
| 20 |
#include "access/heapam.h" |
| 21 |
#include "access/htup_details.h" |
| 22 |
#include "access/reloptions.h" |
| 23 |
#include "access/sysattr.h" |
| 24 |
#include "access/tableam.h" |
| 25 |
#include "access/xact.h" |
| 26 |
#include "catalog/catalog.h" |
| 27 |
#include "catalog/index.h" |
| 28 |
#include "catalog/indexing.h" |
| 29 |
#include "catalog/namespace.h" |
| 30 |
#include "catalog/pg_am.h" |
| 31 |
#include "catalog/pg_authid.h" |
| 32 |
#include "catalog/pg_collation.h" |
| 33 |
#include "catalog/pg_constraint.h" |
| 34 |
#include "catalog/pg_database.h" |
| 35 |
#include "catalog/pg_inherits.h" |
| 36 |
#include "catalog/pg_namespace.h" |
| 37 |
#include "catalog/pg_opclass.h" |
| 38 |
#include "catalog/pg_tablespace.h" |
| 39 |
#include "catalog/pg_type.h" |
| 40 |
#include "commands/comment.h" |
| 41 |
#include "commands/dbcommands.h" |
| 42 |
#include "commands/defrem.h" |
| 43 |
#include "commands/event_trigger.h" |
| 44 |
#include "commands/progress.h" |
| 45 |
#include "commands/tablecmds.h" |
| 46 |
#include "commands/tablespace.h" |
| 47 |
#include "mb/pg_wchar.h" |
| 48 |
#include "miscadmin.h" |
| 49 |
#include "nodes/makefuncs.h" |
| 50 |
#include "nodes/nodeFuncs.h" |
| 51 |
#include "optimizer/optimizer.h" |
| 52 |
#include "parser/parse_coerce.h" |
| 53 |
#include "parser/parse_oper.h" |
| 54 |
#include "parser/parse_utilcmd.h" |
| 55 |
#include "partitioning/partdesc.h" |
| 56 |
#include "pgstat.h" |
| 57 |
#include "rewrite/rewriteManip.h" |
| 58 |
#include "storage/lmgr.h" |
| 59 |
#include "storage/proc.h" |
| 60 |
#include "storage/procarray.h" |
| 61 |
#include "utils/acl.h" |
| 62 |
#include "utils/builtins.h" |
| 63 |
#include "utils/fmgroids.h" |
| 64 |
#include "utils/guc.h" |
| 65 |
#include "utils/injection_point.h" |
| 66 |
#include "utils/inval.h" |
| 67 |
#include "utils/lsyscache.h" |
| 68 |
#include "utils/memutils.h" |
| 69 |
#include "utils/partcache.h" |
| 70 |
#include "utils/pg_rusage.h" |
| 71 |
#include "utils/regproc.h" |
| 72 |
#include "utils/snapmgr.h" |
| 73 |
#include "utils/syscache.h" |
| 74 |
|
| 75 |
|
| 76 |
/* non-export function prototypes */ |
| 77 |
static bool CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts); |
| 78 |
static void CheckPredicate(Expr *predicate); |
| 79 |
static void ComputeIndexAttrs(IndexInfo *indexInfo, |
| 80 |
Oid *typeOids, |
| 81 |
Oid *collationOids, |
| 82 |
Oid *opclassOids, |
| 83 |
Datum *opclassOptions, |
| 84 |
int16 *colOptions, |
| 85 |
const List *attList, |
| 86 |
const List *exclusionOpNames, |
| 87 |
Oid relId, |
| 88 |
const char *accessMethodName, |
| 89 |
Oid accessMethodId, |
| 90 |
bool amcanorder, |
| 91 |
bool isconstraint, |
| 92 |
bool iswithoutoverlaps, |
| 93 |
Oid ddl_userid, |
| 94 |
int ddl_sec_context, |
| 95 |
int *ddl_save_nestlevel); |
| 96 |
static char *ChooseIndexName(const char *tabname, Oid namespaceId, |
| 97 |
const List *colnames, const List *exclusionOpNames, |
| 98 |
bool primary, bool isconstraint); |
| 99 |
static char *ChooseIndexNameAddition(const List *colnames); |
| 100 |
static List *ChooseIndexColumnNames(const List *indexElems); |
| 101 |
static void ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, |
| 102 |
bool isTopLevel); |
| 103 |
static void RangeVarCallbackForReindexIndex(const RangeVar *relation, |
| 104 |
Oid relId, Oid oldRelId, void *arg); |
| 105 |
static Oid ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, |
| 106 |
bool isTopLevel); |
| 107 |
static void ReindexMultipleTables(const ReindexStmt *stmt, |
| 108 |
const ReindexParams *params); |
| 109 |
static void reindex_error_callback(void *arg); |
| 110 |
static void ReindexPartitions(const ReindexStmt *stmt, Oid relid, |
| 111 |
const ReindexParams *params, bool isTopLevel); |
| 112 |
static void ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, |
| 113 |
const ReindexParams *params); |
| 114 |
static bool ReindexRelationConcurrently(const ReindexStmt *stmt, |
| 115 |
Oid relationOid, |
| 116 |
const ReindexParams *params); |
| 117 |
static void update_relispartition(Oid relationId, bool newval); |
| 118 |
static inline void set_indexsafe_procflags(void); |
| 119 |
|
| 120 |
/* |
| 121 |
* callback argument type for RangeVarCallbackForReindexIndex() |
| 122 |
*/ |
| 123 |
struct ReindexIndexCallbackState |
| 124 |
{ |
| 125 |
ReindexParams params; /* options from statement */ |
| 126 |
Oid locked_table_oid; /* tracks previously locked table */ |
| 127 |
}; |
| 128 |
|
| 129 |
/* |
| 130 |
* callback arguments for reindex_error_callback() |
| 131 |
*/ |
| 132 |
typedef struct ReindexErrorInfo |
| 133 |
{ |
| 134 |
char *relname; |
| 135 |
char *relnamespace; |
| 136 |
char relkind; |
| 137 |
} ReindexErrorInfo; |
| 138 |
|
| 139 |
/* |
| 140 |
* CheckIndexCompatible |
| 141 |
* Determine whether an existing index definition is compatible with a |
| 142 |
* prospective index definition, such that the existing index storage |
| 143 |
* could become the storage of the new index, avoiding a rebuild. |
| 144 |
* |
| 145 |
* 'oldId': the OID of the existing index |
| 146 |
* 'accessMethodName': name of the AM to use. |
| 147 |
* 'attributeList': a list of IndexElem specifying columns and expressions |
| 148 |
* to index on. |
| 149 |
* 'exclusionOpNames': list of names of exclusion-constraint operators, |
| 150 |
* or NIL if not an exclusion constraint. |
| 151 |
* 'isWithoutOverlaps': true iff this index has a WITHOUT OVERLAPS clause. |
| 152 |
* |
| 153 |
* This is tailored to the needs of ALTER TABLE ALTER TYPE, which recreates |
| 154 |
* any indexes that depended on a changing column from their pg_get_indexdef |
| 155 |
* or pg_get_constraintdef definitions. We omit some of the sanity checks of |
| 156 |
* DefineIndex. We assume that the old and new indexes have the same number |
| 157 |
* of columns and that if one has an expression column or predicate, both do. |
| 158 |
* Errors arising from the attribute list still apply. |
| 159 |
* |
| 160 |
* Most column type changes that can skip a table rewrite do not invalidate |
| 161 |
* indexes. We acknowledge this when all operator classes, collations and |
| 162 |
* exclusion operators match. Though we could further permit intra-opfamily |
| 163 |
* changes for btree and hash indexes, that adds subtle complexity with no |
| 164 |
* concrete benefit for core types. Note, that INCLUDE columns aren't |
| 165 |
* checked by this function, for them it's enough that table rewrite is |
| 166 |
* skipped. |
| 167 |
* |
| 168 |
* When a comparison or exclusion operator has a polymorphic input type, the |
| 169 |
* actual input types must also match. This defends against the possibility |
| 170 |
* that operators could vary behavior in response to get_fn_expr_argtype(). |
| 171 |
* At present, this hazard is theoretical: check_exclusion_constraint() and |
| 172 |
* all core index access methods decline to set fn_expr for such calls. |
| 173 |
* |
| 174 |
* We do not yet implement a test to verify compatibility of expression |
| 175 |
* columns or predicates, so assume any such index is incompatible. |
| 176 |
*/ |
| 177 |
bool |
| 178 |
CheckIndexCompatible(Oid oldId, |
| 179 |
const char *accessMethodName, |
| 180 |
const List *attributeList, |
| 181 |
const List *exclusionOpNames, |
| 182 |
bool isWithoutOverlaps) |
| 183 |
{ |
| 184 |
bool isconstraint; |
| 185 |
Oid *typeIds; |
| 186 |
Oid *collationIds; |
| 187 |
Oid *opclassIds; |
| 188 |
Datum *opclassOptions; |
| 189 |
Oid accessMethodId; |
| 190 |
Oid relationId; |
| 191 |
HeapTuple tuple; |
| 192 |
Form_pg_index indexForm; |
| 193 |
Form_pg_am accessMethodForm; |
| 194 |
IndexAmRoutine *amRoutine; |
| 195 |
bool amcanorder; |
| 196 |
bool amsummarizing; |
| 197 |
int16 *coloptions; |
| 198 |
IndexInfo *indexInfo; |
| 199 |
int numberOfAttributes; |
| 200 |
int old_natts; |
| 201 |
bool ret = true; |
| 202 |
oidvector *old_indclass; |
| 203 |
oidvector *old_indcollation; |
| 204 |
Relation irel; |
| 205 |
int i; |
| 206 |
Datum d; |
| 207 |
|
| 208 |
/* Caller should already have the relation locked in some way. */ |
| 209 |
relationId = IndexGetRelation(oldId, false); |
| 210 |
|
| 211 |
/* |
| 212 |
* We can pretend isconstraint = false unconditionally. It only serves to |
| 213 |
* decide the text of an error message that should never happen for us. |
| 214 |
*/ |
| 215 |
isconstraint = false; |
| 216 |
|
| 217 |
numberOfAttributes = list_length(attributeList); |
| 218 |
Assert(numberOfAttributes > 0); |
| 219 |
Assert(numberOfAttributes <= INDEX_MAX_KEYS); |
| 220 |
|
| 221 |
/* look up the access method */ |
| 222 |
tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName)); |
| 223 |
if (!HeapTupleIsValid(tuple)) |
| 224 |
ereport(ERROR, |
| 225 |
(errcode(ERRCODE_UNDEFINED_OBJECT), |
| 226 |
errmsg("access method \"%s\" does not exist", |
| 227 |
accessMethodName))); |
| 228 |
accessMethodForm = (Form_pg_am) GETSTRUCT(tuple); |
| 229 |
accessMethodId = accessMethodForm->oid; |
| 230 |
amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler); |
| 231 |
ReleaseSysCache(tuple); |
| 232 |
|
| 233 |
amcanorder = amRoutine->amcanorder; |
| 234 |
amsummarizing = amRoutine->amsummarizing; |
| 235 |
|
| 236 |
/* |
| 237 |
* Compute the operator classes, collations, and exclusion operators for |
| 238 |
* the new index, so we can test whether it's compatible with the existing |
| 239 |
* one. Note that ComputeIndexAttrs might fail here, but that's OK: |
| 240 |
* DefineIndex would have failed later. Our attributeList contains only |
| 241 |
* key attributes, thus we're filling ii_NumIndexAttrs and |
| 242 |
* ii_NumIndexKeyAttrs with same value. |
| 243 |
*/ |
| 244 |
indexInfo = makeIndexInfo(numberOfAttributes, numberOfAttributes, |
| 245 |
accessMethodId, NIL, NIL, false, false, |
| 246 |
false, false, amsummarizing, isWithoutOverlaps); |
| 247 |
typeIds = palloc_array(Oid, numberOfAttributes); |
| 248 |
collationIds = palloc_array(Oid, numberOfAttributes); |
| 249 |
opclassIds = palloc_array(Oid, numberOfAttributes); |
| 250 |
opclassOptions = palloc_array(Datum, numberOfAttributes); |
| 251 |
coloptions = palloc_array(int16, numberOfAttributes); |
| 252 |
ComputeIndexAttrs(indexInfo, |
| 253 |
typeIds, collationIds, opclassIds, opclassOptions, |
| 254 |
coloptions, attributeList, |
| 255 |
exclusionOpNames, relationId, |
| 256 |
accessMethodName, accessMethodId, |
| 257 |
amcanorder, isconstraint, isWithoutOverlaps, InvalidOid, |
| 258 |
0, NULL); |
| 259 |
|
| 260 |
/* Get the soon-obsolete pg_index tuple. */ |
| 261 |
tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(oldId)); |
| 262 |
if (!HeapTupleIsValid(tuple)) |
| 263 |
elog(ERROR, "cache lookup failed for index %u", oldId); |
| 264 |
indexForm = (Form_pg_index) GETSTRUCT(tuple); |
| 265 |
|
| 266 |
/* |
| 267 |
* We don't assess expressions or predicates; assume incompatibility. |
| 268 |
* Also, if the index is invalid for any reason, treat it as incompatible. |
| 269 |
*/ |
| 270 |
if (!(heap_attisnull(tuple, Anum_pg_index_indpred, NULL) && |
| 271 |
heap_attisnull(tuple, Anum_pg_index_indexprs, NULL) && |
| 272 |
indexForm->indisvalid)) |
| 273 |
{ |
| 274 |
ReleaseSysCache(tuple); |
| 275 |
return false; |
| 276 |
} |
| 277 |
|
| 278 |
/* Any change in operator class or collation breaks compatibility. */ |
| 279 |
old_natts = indexForm->indnkeyatts; |
| 280 |
Assert(old_natts == numberOfAttributes); |
| 281 |
|
| 282 |
d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indcollation); |
| 283 |
old_indcollation = (oidvector *) DatumGetPointer(d); |
| 284 |
|
| 285 |
d = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indclass); |
| 286 |
old_indclass = (oidvector *) DatumGetPointer(d); |
| 287 |
|
| 288 |
ret = (memcmp(old_indclass->values, opclassIds, old_natts * sizeof(Oid)) == 0 && |
| 289 |
memcmp(old_indcollation->values, collationIds, old_natts * sizeof(Oid)) == 0); |
| 290 |
|
| 291 |
ReleaseSysCache(tuple); |
| 292 |
|
| 293 |
if (!ret) |
| 294 |
return false; |
| 295 |
|
| 296 |
/* For polymorphic opcintype, column type changes break compatibility. */ |
| 297 |
irel = index_open(oldId, AccessShareLock); /* caller probably has a lock */ |
| 298 |
for (i = 0; i < old_natts; i++) |
| 299 |
{ |
| 300 |
if (IsPolymorphicType(get_opclass_input_type(opclassIds[i])) && |
| 301 |
TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i]) |
| 302 |
{ |
| 303 |
ret = false; |
| 304 |
break; |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
/* Any change in opclass options break compatibility. */ |
| 309 |
if (ret) |
| 310 |
{ |
| 311 |
Datum *oldOpclassOptions = palloc_array(Datum, old_natts); |
| 312 |
|
| 313 |
for (i = 0; i < old_natts; i++) |
| 314 |
oldOpclassOptions[i] = get_attoptions(oldId, i + 1); |
| 315 |
|
| 316 |
ret = CompareOpclassOptions(oldOpclassOptions, opclassOptions, old_natts); |
| 317 |
|
| 318 |
pfree(oldOpclassOptions); |
| 319 |
} |
| 320 |
|
| 321 |
/* Any change in exclusion operator selections breaks compatibility. */ |
| 322 |
if (ret && indexInfo->ii_ExclusionOps != NULL) |
| 323 |
{ |
| 324 |
Oid *old_operators, |
| 325 |
*old_procs; |
| 326 |
uint16 *old_strats; |
| 327 |
|
| 328 |
RelationGetExclusionInfo(irel, &old_operators, &old_procs, &old_strats); |
| 329 |
ret = memcmp(old_operators, indexInfo->ii_ExclusionOps, |
| 330 |
old_natts * sizeof(Oid)) == 0; |
| 331 |
|
| 332 |
/* Require an exact input type match for polymorphic operators. */ |
| 333 |
if (ret) |
| 334 |
{ |
| 335 |
for (i = 0; i < old_natts && ret; i++) |
| 336 |
{ |
| 337 |
Oid left, |
| 338 |
right; |
| 339 |
|
| 340 |
op_input_types(indexInfo->ii_ExclusionOps[i], &left, &right); |
| 341 |
if ((IsPolymorphicType(left) || IsPolymorphicType(right)) && |
| 342 |
TupleDescAttr(irel->rd_att, i)->atttypid != typeIds[i]) |
| 343 |
{ |
| 344 |
ret = false; |
| 345 |
break; |
| 346 |
} |
| 347 |
} |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
index_close(irel, NoLock); |
| 352 |
return ret; |
| 353 |
} |
| 354 |
|
| 355 |
/* |
| 356 |
* CompareOpclassOptions |
| 357 |
* |
| 358 |
* Compare per-column opclass options which are represented by arrays of text[] |
| 359 |
* datums. Both elements of arrays and array themselves can be NULL. |
| 360 |
*/ |
| 361 |
static bool |
| 362 |
CompareOpclassOptions(const Datum *opts1, const Datum *opts2, int natts) |
| 363 |
{ |
| 364 |
int i; |
| 365 |
FmgrInfo fm; |
| 366 |
|
| 367 |
if (!opts1 && !opts2) |
| 368 |
return true; |
| 369 |
|
| 370 |
fmgr_info(F_ARRAY_EQ, &fm); |
| 371 |
for (i = 0; i < natts; i++) |
| 372 |
{ |
| 373 |
Datum opt1 = opts1 ? opts1[i] : (Datum) 0; |
| 374 |
Datum opt2 = opts2 ? opts2[i] : (Datum) 0; |
| 375 |
|
| 376 |
if (opt1 == (Datum) 0) |
| 377 |
{ |
| 378 |
if (opt2 == (Datum) 0) |
| 379 |
continue; |
| 380 |
else |
| 381 |
return false; |
| 382 |
} |
| 383 |
else if (opt2 == (Datum) 0) |
| 384 |
return false; |
| 385 |
|
| 386 |
/* |
| 387 |
* Compare non-NULL text[] datums. Use C collation to enforce binary |
| 388 |
* equivalence of texts, because we don't know anything about the |
| 389 |
* semantics of opclass options. |
| 390 |
*/ |
| 391 |
if (!DatumGetBool(FunctionCall2Coll(&fm, C_COLLATION_OID, opt1, opt2))) |
| 392 |
return false; |
| 393 |
} |
| 394 |
|
| 395 |
return true; |
| 396 |
} |
| 397 |
|
| 398 |
/* |
| 399 |
* WaitForOlderSnapshots |
| 400 |
* |
| 401 |
* Wait for transactions that might have an older snapshot than the given xmin |
| 402 |
* limit, because it might not contain tuples deleted just before it has |
| 403 |
* been taken. Obtain a list of VXIDs of such transactions, and wait for them |
| 404 |
* individually. This is used when building an index concurrently. |
| 405 |
* |
| 406 |
* We can exclude any running transactions that have xmin > the xmin given; |
| 407 |
* their oldest snapshot must be newer than our xmin limit. |
| 408 |
* We can also exclude any transactions that have xmin = zero, since they |
| 409 |
* evidently have no live snapshot at all (and any one they might be in |
| 410 |
* process of taking is certainly newer than ours). Transactions in other |
| 411 |
* DBs can be ignored too, since they'll never even be able to see the |
| 412 |
* index being worked on. |
| 413 |
* |
| 414 |
* We can also exclude autovacuum processes and processes running manual |
| 415 |
* lazy VACUUMs, because they won't be fazed by missing index entries |
| 416 |
* either. (Manual ANALYZEs, however, can't be excluded because they |
| 417 |
* might be within transactions that are going to do arbitrary operations |
| 418 |
* later.) Processes running CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY |
| 419 |
* on indexes that are neither expressional nor partial are also safe to |
| 420 |
* ignore, since we know that those processes won't examine any data |
| 421 |
* outside the table they're indexing. |
| 422 |
* |
| 423 |
* Also, GetCurrentVirtualXIDs never reports our own vxid, so we need not |
| 424 |
* check for that. |
| 425 |
* |
| 426 |
* If a process goes idle-in-transaction with xmin zero, we do not need to |
| 427 |
* wait for it anymore, per the above argument. We do not have the |
| 428 |
* infrastructure right now to stop waiting if that happens, but we can at |
| 429 |
* least avoid the folly of waiting when it is idle at the time we would |
| 430 |
* begin to wait. We do this by repeatedly rechecking the output of |
| 431 |
* GetCurrentVirtualXIDs. If, during any iteration, a particular vxid |
| 432 |
* doesn't show up in the output, we know we can forget about it. |
| 433 |
*/ |
| 434 |
void |
| 435 |
WaitForOlderSnapshots(TransactionId limitXmin, bool progress) |
| 436 |
{ |
| 437 |
int n_old_snapshots; |
| 438 |
int i; |
| 439 |
VirtualTransactionId *old_snapshots; |
| 440 |
|
| 441 |
old_snapshots = GetCurrentVirtualXIDs(limitXmin, true, false, |
| 442 |
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM |
| 443 |
| PROC_IN_SAFE_IC, |
| 444 |
&n_old_snapshots); |
| 445 |
if (progress) |
| 446 |
pgstat_progress_update_param(PROGRESS_WAITFOR_TOTAL, n_old_snapshots); |
| 447 |
|
| 448 |
for (i = 0; i < n_old_snapshots; i++) |
| 449 |
{ |
| 450 |
if (!VirtualTransactionIdIsValid(old_snapshots[i])) |
| 451 |
continue; /* found uninteresting in previous cycle */ |
| 452 |
|
| 453 |
if (i > 0) |
| 454 |
{ |
| 455 |
/* see if anything's changed ... */ |
| 456 |
VirtualTransactionId *newer_snapshots; |
| 457 |
int n_newer_snapshots; |
| 458 |
int j; |
| 459 |
int k; |
| 460 |
|
| 461 |
newer_snapshots = GetCurrentVirtualXIDs(limitXmin, |
| 462 |
true, false, |
| 463 |
PROC_IS_AUTOVACUUM | PROC_IN_VACUUM |
| 464 |
| PROC_IN_SAFE_IC, |
| 465 |
&n_newer_snapshots); |
| 466 |
for (j = i; j < n_old_snapshots; j++) |
| 467 |
{ |
| 468 |
if (!VirtualTransactionIdIsValid(old_snapshots[j])) |
| 469 |
continue; /* found uninteresting in previous cycle */ |
| 470 |
for (k = 0; k < n_newer_snapshots; k++) |
| 471 |
{ |
| 472 |
if (VirtualTransactionIdEquals(old_snapshots[j], |
| 473 |
newer_snapshots[k])) |
| 474 |
break; |
| 475 |
} |
| 476 |
if (k >= n_newer_snapshots) /* not there anymore */ |
| 477 |
SetInvalidVirtualTransactionId(old_snapshots[j]); |
| 478 |
} |
| 479 |
pfree(newer_snapshots); |
| 480 |
} |
| 481 |
|
| 482 |
if (VirtualTransactionIdIsValid(old_snapshots[i])) |
| 483 |
{ |
| 484 |
/* If requested, publish who we're going to wait for. */ |
| 485 |
if (progress) |
| 486 |
{ |
| 487 |
PGPROC *holder = ProcNumberGetProc(old_snapshots[i].procNumber); |
| 488 |
|
| 489 |
if (holder) |
| 490 |
pgstat_progress_update_param(PROGRESS_WAITFOR_CURRENT_PID, |
| 491 |
holder->pid); |
| 492 |
} |
| 493 |
VirtualXactLock(old_snapshots[i], true); |
| 494 |
} |
| 495 |
|
| 496 |
if (progress) |
| 497 |
pgstat_progress_update_param(PROGRESS_WAITFOR_DONE, i + 1); |
| 498 |
} |
| 499 |
} |
| 500 |
|
| 501 |
|
| 502 |
/* |
| 503 |
* DefineIndex |
| 504 |
* Creates a new index. |
| 505 |
* |
| 506 |
* This function manages the current userid according to the needs of pg_dump. |
| 507 |
* Recreating old-database catalog entries in new-database is fine, regardless |
| 508 |
* of which users would have permission to recreate those entries now. That's |
| 509 |
* just preservation of state. Running opaque expressions, like calling a |
| 510 |
* function named in a catalog entry or evaluating a pg_node_tree in a catalog |
| 511 |
* entry, as anyone other than the object owner, is not fine. To adhere to |
| 512 |
* those principles and to remain fail-safe, use the table owner userid for |
| 513 |
* most ACL checks. Use the original userid for ACL checks reached without |
| 514 |
* traversing opaque expressions. (pg_dump can predict such ACL checks from |
| 515 |
* catalogs.) Overall, this is a mess. Future DDL development should |
| 516 |
* consider offering one DDL command for catalog setup and a separate DDL |
| 517 |
* command for steps that run opaque expressions. |
| 518 |
* |
| 519 |
* 'tableId': the OID of the table relation on which the index is to be |
| 520 |
* created |
| 521 |
* 'stmt': IndexStmt describing the properties of the new index. |
| 522 |
* 'indexRelationId': normally InvalidOid, but during bootstrap can be |
| 523 |
* nonzero to specify a preselected OID for the index. |
| 524 |
* 'parentIndexId': the OID of the parent index; InvalidOid if not the child |
| 525 |
* of a partitioned index. |
| 526 |
* 'parentConstraintId': the OID of the parent constraint; InvalidOid if not |
| 527 |
* the child of a constraint (only used when recursing) |
| 528 |
* 'total_parts': total number of direct and indirect partitions of relation; |
| 529 |
* pass -1 if not known or rel is not partitioned. |
| 530 |
* 'is_alter_table': this is due to an ALTER rather than a CREATE operation. |
| 531 |
* 'check_rights': check for CREATE rights in namespace and tablespace. (This |
| 532 |
* should be true except when ALTER is deleting/recreating an index.) |
| 533 |
* 'check_not_in_use': check for table not already in use in current session. |
| 534 |
* This should be true unless caller is holding the table open, in which |
| 535 |
* case the caller had better have checked it earlier. |
| 536 |
* 'skip_build': make the catalog entries but don't create the index files |
| 537 |
* 'quiet': suppress the NOTICE chatter ordinarily provided for constraints. |
| 538 |
* |
| 539 |
* Returns the object address of the created index. |
| 540 |
*/ |
| 541 |
ObjectAddress |
| 542 |
DefineIndex(Oid tableId, |
| 543 |
IndexStmt *stmt, |
| 544 |
Oid indexRelationId, |
| 545 |
Oid parentIndexId, |
| 546 |
Oid parentConstraintId, |
| 547 |
int total_parts, |
| 548 |
bool is_alter_table, |
| 549 |
bool check_rights, |
| 550 |
bool check_not_in_use, |
| 551 |
bool skip_build, |
| 552 |
bool quiet) |
| 553 |
{ |
| 554 |
bool concurrent; |
| 555 |
char *indexRelationName; |
| 556 |
char *accessMethodName; |
| 557 |
Oid *typeIds; |
| 558 |
Oid *collationIds; |
| 559 |
Oid *opclassIds; |
| 560 |
Datum *opclassOptions; |
| 561 |
Oid accessMethodId; |
| 562 |
Oid namespaceId; |
| 563 |
Oid tablespaceId; |
| 564 |
Oid createdConstraintId = InvalidOid; |
| 565 |
List *indexColNames; |
| 566 |
List *allIndexParams; |
| 567 |
Relation rel; |
| 568 |
HeapTuple tuple; |
| 569 |
Form_pg_am accessMethodForm; |
| 570 |
IndexAmRoutine *amRoutine; |
| 571 |
bool amcanorder; |
| 572 |
bool amissummarizing; |
| 573 |
amoptions_function amoptions; |
| 574 |
bool exclusion; |
| 575 |
bool partitioned; |
| 576 |
bool safe_index; |
| 577 |
Datum reloptions; |
| 578 |
int16 *coloptions; |
| 579 |
IndexInfo *indexInfo; |
| 580 |
bits16 flags; |
| 581 |
bits16 constr_flags; |
| 582 |
int numberOfAttributes; |
| 583 |
int numberOfKeyAttributes; |
| 584 |
TransactionId limitXmin; |
| 585 |
ObjectAddress address; |
| 586 |
LockRelId heaprelid; |
| 587 |
LOCKTAG heaplocktag; |
| 588 |
LOCKMODE lockmode; |
| 589 |
Snapshot snapshot; |
| 590 |
Oid root_save_userid; |
| 591 |
int root_save_sec_context; |
| 592 |
int root_save_nestlevel; |
| 593 |
|
| 594 |
root_save_nestlevel = NewGUCNestLevel(); |
| 595 |
|
| 596 |
RestrictSearchPath(); |
| 597 |
|
| 598 |
/* |
| 599 |
* Some callers need us to run with an empty default_tablespace; this is a |
| 600 |
* necessary hack to be able to reproduce catalog state accurately when |
| 601 |
* recreating indexes after table-rewriting ALTER TABLE. |
| 602 |
*/ |
| 603 |
if (stmt->reset_default_tblspc) |
| 604 |
(void) set_config_option("default_tablespace", "", |
| 605 |
PGC_USERSET, PGC_S_SESSION, |
| 606 |
GUC_ACTION_SAVE, true, 0, false); |
| 607 |
|
| 608 |
/* |
| 609 |
* Force non-concurrent build on temporary relations, even if CONCURRENTLY |
| 610 |
* was requested. Other backends can't access a temporary relation, so |
| 611 |
* there's no harm in grabbing a stronger lock, and a non-concurrent DROP |
| 612 |
* is more efficient. Do this before any use of the concurrent option is |
| 613 |
* done. |
| 614 |
*/ |
| 615 |
if (stmt->concurrent && get_rel_persistence(tableId) != RELPERSISTENCE_TEMP) |
| 616 |
concurrent = true; |
| 617 |
else |
| 618 |
concurrent = false; |
| 619 |
|
| 620 |
/* |
| 621 |
* Start progress report. If we're building a partition, this was already |
| 622 |
* done. |
| 623 |
*/ |
| 624 |
if (!OidIsValid(parentIndexId)) |
| 625 |
{ |
| 626 |
pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, tableId); |
| 627 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_COMMAND, |
| 628 |
concurrent ? |
| 629 |
PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY : |
| 630 |
PROGRESS_CREATEIDX_COMMAND_CREATE); |
| 631 |
} |
| 632 |
|
| 633 |
/* |
| 634 |
* No index OID to report yet |
| 635 |
*/ |
| 636 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_INDEX_OID, |
| 637 |
InvalidOid); |
| 638 |
|
| 639 |
/* |
| 640 |
* count key attributes in index |
| 641 |
*/ |
| 642 |
numberOfKeyAttributes = list_length(stmt->indexParams); |
| 643 |
|
| 644 |
/* |
| 645 |
* Calculate the new list of index columns including both key columns and |
| 646 |
* INCLUDE columns. Later we can determine which of these are key |
| 647 |
* columns, and which are just part of the INCLUDE list by checking the |
| 648 |
* list position. A list item in a position less than ii_NumIndexKeyAttrs |
| 649 |
* is part of the key columns, and anything equal to and over is part of |
| 650 |
* the INCLUDE columns. |
| 651 |
*/ |
| 652 |
allIndexParams = list_concat_copy(stmt->indexParams, |
| 653 |
stmt->indexIncludingParams); |
| 654 |
numberOfAttributes = list_length(allIndexParams); |
| 655 |
|
| 656 |
if (numberOfKeyAttributes <= 0) |
| 657 |
ereport(ERROR, |
| 658 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 659 |
errmsg("must specify at least one column"))); |
| 660 |
if (numberOfAttributes > INDEX_MAX_KEYS) |
| 661 |
ereport(ERROR, |
| 662 |
(errcode(ERRCODE_TOO_MANY_COLUMNS), |
| 663 |
errmsg("cannot use more than %d columns in an index", |
| 664 |
INDEX_MAX_KEYS))); |
| 665 |
|
| 666 |
/* |
| 667 |
* Only SELECT ... FOR UPDATE/SHARE are allowed while doing a standard |
| 668 |
* index build; but for concurrent builds we allow INSERT/UPDATE/DELETE |
| 669 |
* (but not VACUUM). |
| 670 |
* |
| 671 |
* NB: Caller is responsible for making sure that tableId refers to the |
| 672 |
* relation on which the index should be built; except in bootstrap mode, |
| 673 |
* this will typically require the caller to have already locked the |
| 674 |
* relation. To avoid lock upgrade hazards, that lock should be at least |
| 675 |
* as strong as the one we take here. |
| 676 |
* |
| 677 |
* NB: If the lock strength here ever changes, code that is run by |
| 678 |
* parallel workers under the control of certain particular ambuild |
| 679 |
* functions will need to be updated, too. |
| 680 |
*/ |
| 681 |
lockmode = concurrent ? ShareUpdateExclusiveLock : ShareLock; |
| 682 |
rel = table_open(tableId, lockmode); |
| 683 |
|
| 684 |
/* |
| 685 |
* Switch to the table owner's userid, so that any index functions are run |
| 686 |
* as that user. Also lock down security-restricted operations. We |
| 687 |
* already arranged to make GUC variable changes local to this command. |
| 688 |
*/ |
| 689 |
GetUserIdAndSecContext(&root_save_userid, &root_save_sec_context); |
| 690 |
SetUserIdAndSecContext(rel->rd_rel->relowner, |
| 691 |
root_save_sec_context | SECURITY_RESTRICTED_OPERATION); |
| 692 |
|
| 693 |
namespaceId = RelationGetNamespace(rel); |
| 694 |
|
| 695 |
/* |
| 696 |
* It has exclusion constraint behavior if it's an EXCLUDE constraint or a |
| 697 |
* temporal PRIMARY KEY/UNIQUE constraint |
| 698 |
*/ |
| 699 |
exclusion = stmt->excludeOpNames || stmt->iswithoutoverlaps; |
| 700 |
|
| 701 |
/* Ensure that it makes sense to index this kind of relation */ |
| 702 |
switch (rel->rd_rel->relkind) |
| 703 |
{ |
| 704 |
case RELKIND_RELATION: |
| 705 |
case RELKIND_MATVIEW: |
| 706 |
case RELKIND_PARTITIONED_TABLE: |
| 707 |
/* OK */ |
| 708 |
break; |
| 709 |
default: |
| 710 |
ereport(ERROR, |
| 711 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 712 |
errmsg("cannot create index on relation \"%s\"", |
| 713 |
RelationGetRelationName(rel)), |
| 714 |
errdetail_relkind_not_supported(rel->rd_rel->relkind))); |
| 715 |
break; |
| 716 |
} |
| 717 |
|
| 718 |
/* |
| 719 |
* Establish behavior for partitioned tables, and verify sanity of |
| 720 |
* parameters. |
| 721 |
* |
| 722 |
* We do not build an actual index in this case; we only create a few |
| 723 |
* catalog entries. The actual indexes are built by recursing for each |
| 724 |
* partition. |
| 725 |
*/ |
| 726 |
partitioned = rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE; |
| 727 |
if (partitioned) |
| 728 |
{ |
| 729 |
/* |
| 730 |
* Note: we check 'stmt->concurrent' rather than 'concurrent', so that |
| 731 |
* the error is thrown also for temporary tables. Seems better to be |
| 732 |
* consistent, even though we could do it on temporary table because |
| 733 |
* we're not actually doing it concurrently. |
| 734 |
*/ |
| 735 |
if (stmt->concurrent) |
| 736 |
ereport(ERROR, |
| 737 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 738 |
errmsg("cannot create index on partitioned table \"%s\" concurrently", |
| 739 |
RelationGetRelationName(rel)))); |
| 740 |
} |
| 741 |
|
| 742 |
/* |
| 743 |
* Don't try to CREATE INDEX on temp tables of other backends. |
| 744 |
*/ |
| 745 |
if (RELATION_IS_OTHER_TEMP(rel)) |
| 746 |
ereport(ERROR, |
| 747 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 748 |
errmsg("cannot create indexes on temporary tables of other sessions"))); |
| 749 |
|
| 750 |
/* |
| 751 |
* Unless our caller vouches for having checked this already, insist that |
| 752 |
* the table not be in use by our own session, either. Otherwise we might |
| 753 |
* fail to make entries in the new index (for instance, if an INSERT or |
| 754 |
* UPDATE is in progress and has already made its list of target indexes). |
| 755 |
*/ |
| 756 |
if (check_not_in_use) |
| 757 |
CheckTableNotInUse(rel, "CREATE INDEX"); |
| 758 |
|
| 759 |
/* |
| 760 |
* Verify we (still) have CREATE rights in the rel's namespace. |
| 761 |
* (Presumably we did when the rel was created, but maybe not anymore.) |
| 762 |
* Skip check if caller doesn't want it. Also skip check if |
| 763 |
* bootstrapping, since permissions machinery may not be working yet. |
| 764 |
*/ |
| 765 |
if (check_rights && !IsBootstrapProcessingMode()) |
| 766 |
{ |
| 767 |
AclResult aclresult; |
| 768 |
|
| 769 |
aclresult = object_aclcheck(NamespaceRelationId, namespaceId, root_save_userid, |
| 770 |
ACL_CREATE); |
| 771 |
if (aclresult != ACLCHECK_OK) |
| 772 |
aclcheck_error(aclresult, OBJECT_SCHEMA, |
| 773 |
get_namespace_name(namespaceId)); |
| 774 |
} |
| 775 |
|
| 776 |
/* |
| 777 |
* Select tablespace to use. If not specified, use default tablespace |
| 778 |
* (which may in turn default to database's default). |
| 779 |
*/ |
| 780 |
if (stmt->tableSpace) |
| 781 |
{ |
| 782 |
tablespaceId = get_tablespace_oid(stmt->tableSpace, false); |
| 783 |
if (partitioned && tablespaceId == MyDatabaseTableSpace) |
| 784 |
ereport(ERROR, |
| 785 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 786 |
errmsg("cannot specify default tablespace for partitioned relations"))); |
| 787 |
} |
| 788 |
else |
| 789 |
{ |
| 790 |
tablespaceId = GetDefaultTablespace(rel->rd_rel->relpersistence, |
| 791 |
partitioned); |
| 792 |
/* note InvalidOid is OK in this case */ |
| 793 |
} |
| 794 |
|
| 795 |
/* Check tablespace permissions */ |
| 796 |
if (check_rights && |
| 797 |
OidIsValid(tablespaceId) && tablespaceId != MyDatabaseTableSpace) |
| 798 |
{ |
| 799 |
AclResult aclresult; |
| 800 |
|
| 801 |
aclresult = object_aclcheck(TableSpaceRelationId, tablespaceId, root_save_userid, |
| 802 |
ACL_CREATE); |
| 803 |
if (aclresult != ACLCHECK_OK) |
| 804 |
aclcheck_error(aclresult, OBJECT_TABLESPACE, |
| 805 |
get_tablespace_name(tablespaceId)); |
| 806 |
} |
| 807 |
|
| 808 |
/* |
| 809 |
* Force shared indexes into the pg_global tablespace. This is a bit of a |
| 810 |
* hack but seems simpler than marking them in the BKI commands. On the |
| 811 |
* other hand, if it's not shared, don't allow it to be placed there. |
| 812 |
*/ |
| 813 |
if (rel->rd_rel->relisshared) |
| 814 |
tablespaceId = GLOBALTABLESPACE_OID; |
| 815 |
else if (tablespaceId == GLOBALTABLESPACE_OID) |
| 816 |
ereport(ERROR, |
| 817 |
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
| 818 |
errmsg("only shared relations can be placed in pg_global tablespace"))); |
| 819 |
|
| 820 |
/* |
| 821 |
* Choose the index column names. |
| 822 |
*/ |
| 823 |
indexColNames = ChooseIndexColumnNames(allIndexParams); |
| 824 |
|
| 825 |
/* |
| 826 |
* Select name for index if caller didn't specify |
| 827 |
*/ |
| 828 |
indexRelationName = stmt->idxname; |
| 829 |
if (indexRelationName == NULL) |
| 830 |
indexRelationName = ChooseIndexName(RelationGetRelationName(rel), |
| 831 |
namespaceId, |
| 832 |
indexColNames, |
| 833 |
stmt->excludeOpNames, |
| 834 |
stmt->primary, |
| 835 |
stmt->isconstraint); |
| 836 |
|
| 837 |
/* |
| 838 |
* look up the access method, verify it can handle the requested features |
| 839 |
*/ |
| 840 |
accessMethodName = stmt->accessMethod; |
| 841 |
tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName)); |
| 842 |
if (!HeapTupleIsValid(tuple)) |
| 843 |
{ |
| 844 |
/* |
| 845 |
* Hack to provide more-or-less-transparent updating of old RTREE |
| 846 |
* indexes to GiST: if RTREE is requested and not found, use GIST. |
| 847 |
*/ |
| 848 |
if (strcmp(accessMethodName, "rtree") == 0) |
| 849 |
{ |
| 850 |
ereport(NOTICE, |
| 851 |
(errmsg("substituting access method \"gist\" for obsolete method \"rtree\""))); |
| 852 |
accessMethodName = "gist"; |
| 853 |
tuple = SearchSysCache1(AMNAME, PointerGetDatum(accessMethodName)); |
| 854 |
} |
| 855 |
|
| 856 |
if (!HeapTupleIsValid(tuple)) |
| 857 |
ereport(ERROR, |
| 858 |
(errcode(ERRCODE_UNDEFINED_OBJECT), |
| 859 |
errmsg("access method \"%s\" does not exist", |
| 860 |
accessMethodName))); |
| 861 |
} |
| 862 |
accessMethodForm = (Form_pg_am) GETSTRUCT(tuple); |
| 863 |
accessMethodId = accessMethodForm->oid; |
| 864 |
amRoutine = GetIndexAmRoutine(accessMethodForm->amhandler); |
| 865 |
|
| 866 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID, |
| 867 |
accessMethodId); |
| 868 |
|
| 869 |
if (stmt->unique && !stmt->iswithoutoverlaps && !amRoutine->amcanunique) |
| 870 |
ereport(ERROR, |
| 871 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 872 |
errmsg("access method \"%s\" does not support unique indexes", |
| 873 |
accessMethodName))); |
| 874 |
if (stmt->indexIncludingParams != NIL && !amRoutine->amcaninclude) |
| 875 |
ereport(ERROR, |
| 876 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 877 |
errmsg("access method \"%s\" does not support included columns", |
| 878 |
accessMethodName))); |
| 879 |
if (numberOfKeyAttributes > 1 && !amRoutine->amcanmulticol) |
| 880 |
ereport(ERROR, |
| 881 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 882 |
errmsg("access method \"%s\" does not support multicolumn indexes", |
| 883 |
accessMethodName))); |
| 884 |
if (exclusion && amRoutine->amgettuple == NULL) |
| 885 |
ereport(ERROR, |
| 886 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 887 |
errmsg("access method \"%s\" does not support exclusion constraints", |
| 888 |
accessMethodName))); |
| 889 |
if (stmt->iswithoutoverlaps && strcmp(accessMethodName, "gist") != 0) |
| 890 |
ereport(ERROR, |
| 891 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 892 |
errmsg("access method \"%s\" does not support WITHOUT OVERLAPS constraints", |
| 893 |
accessMethodName))); |
| 894 |
|
| 895 |
amcanorder = amRoutine->amcanorder; |
| 896 |
amoptions = amRoutine->amoptions; |
| 897 |
amissummarizing = amRoutine->amsummarizing; |
| 898 |
|
| 899 |
pfree(amRoutine); |
| 900 |
ReleaseSysCache(tuple); |
| 901 |
|
| 902 |
/* |
| 903 |
* Validate predicate, if given |
| 904 |
*/ |
| 905 |
if (stmt->whereClause) |
| 906 |
CheckPredicate((Expr *) stmt->whereClause); |
| 907 |
|
| 908 |
/* |
| 909 |
* Parse AM-specific options, convert to text array form, validate. |
| 910 |
*/ |
| 911 |
reloptions = transformRelOptions((Datum) 0, stmt->options, |
| 912 |
NULL, NULL, false, false); |
| 913 |
|
| 914 |
(void) index_reloptions(amoptions, reloptions, true); |
| 915 |
|
| 916 |
/* |
| 917 |
* Prepare arguments for index_create, primarily an IndexInfo structure. |
| 918 |
* Note that predicates must be in implicit-AND format. In a concurrent |
| 919 |
* build, mark it not-ready-for-inserts. |
| 920 |
*/ |
| 921 |
indexInfo = makeIndexInfo(numberOfAttributes, |
| 922 |
numberOfKeyAttributes, |
| 923 |
accessMethodId, |
| 924 |
NIL, /* expressions, NIL for now */ |
| 925 |
make_ands_implicit((Expr *) stmt->whereClause), |
| 926 |
stmt->unique, |
| 927 |
stmt->nulls_not_distinct, |
| 928 |
!concurrent, |
| 929 |
concurrent, |
| 930 |
amissummarizing, |
| 931 |
stmt->iswithoutoverlaps); |
| 932 |
|
| 933 |
typeIds = palloc_array(Oid, numberOfAttributes); |
| 934 |
collationIds = palloc_array(Oid, numberOfAttributes); |
| 935 |
opclassIds = palloc_array(Oid, numberOfAttributes); |
| 936 |
opclassOptions = palloc_array(Datum, numberOfAttributes); |
| 937 |
coloptions = palloc_array(int16, numberOfAttributes); |
| 938 |
ComputeIndexAttrs(indexInfo, |
| 939 |
typeIds, collationIds, opclassIds, opclassOptions, |
| 940 |
coloptions, allIndexParams, |
| 941 |
stmt->excludeOpNames, tableId, |
| 942 |
accessMethodName, accessMethodId, |
| 943 |
amcanorder, stmt->isconstraint, stmt->iswithoutoverlaps, |
| 944 |
root_save_userid, root_save_sec_context, |
| 945 |
&root_save_nestlevel); |
| 946 |
|
| 947 |
/* |
| 948 |
* The below call to index_create() creates the dependencies on types. We |
| 949 |
* are responsible for checking USAGE. |
| 950 |
*/ |
| 951 |
if (check_rights) |
| 952 |
{ |
| 953 |
if (indexInfo->ii_Expressions) |
| 954 |
CheckUsageOnTypesInSingleRelExpr((Node *) indexInfo->ii_Expressions, |
| 955 |
tableId, |
| 956 |
root_save_userid); |
| 957 |
if (indexInfo->ii_Predicate) |
| 958 |
CheckUsageOnTypesInSingleRelExpr((Node *) indexInfo->ii_Predicate, |
| 959 |
tableId, |
| 960 |
root_save_userid); |
| 961 |
} |
| 962 |
|
| 963 |
/* |
| 964 |
* Extra checks when creating a PRIMARY KEY index. |
| 965 |
*/ |
| 966 |
if (stmt->primary) |
| 967 |
index_check_primary_key(rel, indexInfo, is_alter_table, stmt); |
| 968 |
|
| 969 |
/* |
| 970 |
* If this table is partitioned and we're creating a unique index, primary |
| 971 |
* key, or exclusion constraint, make sure that the partition key is a |
| 972 |
* subset of the index's columns. Otherwise it would be possible to |
| 973 |
* violate uniqueness by putting values that ought to be unique in |
| 974 |
* different partitions. |
| 975 |
* |
| 976 |
* We could lift this limitation if we had global indexes, but those have |
| 977 |
* their own problems, so this is a useful feature combination. |
| 978 |
*/ |
| 979 |
if (partitioned && (stmt->unique || exclusion)) |
| 980 |
{ |
| 981 |
PartitionKey key = RelationGetPartitionKey(rel); |
| 982 |
const char *constraint_type; |
| 983 |
int i; |
| 984 |
|
| 985 |
if (stmt->primary) |
| 986 |
constraint_type = "PRIMARY KEY"; |
| 987 |
else if (stmt->unique) |
| 988 |
constraint_type = "UNIQUE"; |
| 989 |
else if (stmt->excludeOpNames) |
| 990 |
constraint_type = "EXCLUDE"; |
| 991 |
else |
| 992 |
{ |
| 993 |
elog(ERROR, "unknown constraint type"); |
| 994 |
constraint_type = NULL; /* keep compiler quiet */ |
| 995 |
} |
| 996 |
|
| 997 |
/* |
| 998 |
* Verify that all the columns in the partition key appear in the |
| 999 |
* unique key definition, with the same notion of equality. |
| 1000 |
*/ |
| 1001 |
for (i = 0; i < key->partnatts; i++) |
| 1002 |
{ |
| 1003 |
bool found = false; |
| 1004 |
int eq_strategy; |
| 1005 |
Oid ptkey_eqop; |
| 1006 |
int j; |
| 1007 |
|
| 1008 |
/* |
| 1009 |
* Identify the equality operator associated with this partkey |
| 1010 |
* column. For list and range partitioning, partkeys use btree |
| 1011 |
* operator classes; hash partitioning uses hash operator classes. |
| 1012 |
* (Keep this in sync with ComputePartitionAttrs!) |
| 1013 |
*/ |
| 1014 |
if (key->strategy == PARTITION_STRATEGY_HASH) |
| 1015 |
eq_strategy = HTEqualStrategyNumber; |
| 1016 |
else |
| 1017 |
eq_strategy = BTEqualStrategyNumber; |
| 1018 |
|
| 1019 |
ptkey_eqop = get_opfamily_member(key->partopfamily[i], |
| 1020 |
key->partopcintype[i], |
| 1021 |
key->partopcintype[i], |
| 1022 |
eq_strategy); |
| 1023 |
if (!OidIsValid(ptkey_eqop)) |
| 1024 |
elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u", |
| 1025 |
eq_strategy, key->partopcintype[i], key->partopcintype[i], |
| 1026 |
key->partopfamily[i]); |
| 1027 |
|
| 1028 |
/* |
| 1029 |
* It may be possible to support UNIQUE constraints when partition |
| 1030 |
* keys are expressions, but is it worth it? Give up for now. |
| 1031 |
*/ |
| 1032 |
if (key->partattrs[i] == 0) |
| 1033 |
ereport(ERROR, |
| 1034 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1035 |
errmsg("unsupported %s constraint with partition key definition", |
| 1036 |
constraint_type), |
| 1037 |
errdetail("%s constraints cannot be used when partition keys include expressions.", |
| 1038 |
constraint_type))); |
| 1039 |
|
| 1040 |
/* Search the index column(s) for a match */ |
| 1041 |
for (j = 0; j < indexInfo->ii_NumIndexKeyAttrs; j++) |
| 1042 |
{ |
| 1043 |
if (key->partattrs[i] == indexInfo->ii_IndexAttrNumbers[j]) |
| 1044 |
{ |
| 1045 |
/* |
| 1046 |
* Matched the column, now what about the collation and |
| 1047 |
* equality op? |
| 1048 |
*/ |
| 1049 |
Oid idx_opfamily; |
| 1050 |
Oid idx_opcintype; |
| 1051 |
|
| 1052 |
if (key->partcollation[i] != collationIds[j]) |
| 1053 |
continue; |
| 1054 |
|
| 1055 |
if (get_opclass_opfamily_and_input_type(opclassIds[j], |
| 1056 |
&idx_opfamily, |
| 1057 |
&idx_opcintype)) |
| 1058 |
{ |
| 1059 |
Oid idx_eqop = InvalidOid; |
| 1060 |
|
| 1061 |
if (stmt->unique && !stmt->iswithoutoverlaps) |
| 1062 |
idx_eqop = get_opfamily_member_for_cmptype(idx_opfamily, |
| 1063 |
idx_opcintype, |
| 1064 |
idx_opcintype, |
| 1065 |
COMPARE_EQ); |
| 1066 |
else if (exclusion) |
| 1067 |
idx_eqop = indexInfo->ii_ExclusionOps[j]; |
| 1068 |
|
| 1069 |
if (!idx_eqop) |
| 1070 |
ereport(ERROR, |
| 1071 |
errcode(ERRCODE_UNDEFINED_OBJECT), |
| 1072 |
errmsg("could not identify an equality operator for type %s", format_type_be(idx_opcintype)), |
| 1073 |
errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".", |
| 1074 |
get_opfamily_name(idx_opfamily, false), get_am_name(get_opfamily_method(idx_opfamily)))); |
| 1075 |
|
| 1076 |
if (ptkey_eqop == idx_eqop) |
| 1077 |
{ |
| 1078 |
found = true; |
| 1079 |
break; |
| 1080 |
} |
| 1081 |
else if (exclusion) |
| 1082 |
{ |
| 1083 |
/* |
| 1084 |
* We found a match, but it's not an equality |
| 1085 |
* operator. Instead of failing below with an |
| 1086 |
* error message about a missing column, fail now |
| 1087 |
* and explain that the operator is wrong. |
| 1088 |
*/ |
| 1089 |
Form_pg_attribute att = TupleDescAttr(RelationGetDescr(rel), key->partattrs[i] - 1); |
| 1090 |
|
| 1091 |
ereport(ERROR, |
| 1092 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1093 |
errmsg("cannot match partition key to index on column \"%s\" using non-equal operator \"%s\"", |
| 1094 |
NameStr(att->attname), |
| 1095 |
get_opname(indexInfo->ii_ExclusionOps[j])))); |
| 1096 |
} |
| 1097 |
} |
| 1098 |
} |
| 1099 |
} |
| 1100 |
|
| 1101 |
if (!found) |
| 1102 |
{ |
| 1103 |
Form_pg_attribute att; |
| 1104 |
|
| 1105 |
att = TupleDescAttr(RelationGetDescr(rel), |
| 1106 |
key->partattrs[i] - 1); |
| 1107 |
ereport(ERROR, |
| 1108 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1109 |
errmsg("unique constraint on partitioned table must include all partitioning columns"), |
| 1110 |
errdetail("%s constraint on table \"%s\" lacks column \"%s\" which is part of the partition key.", |
| 1111 |
constraint_type, RelationGetRelationName(rel), |
| 1112 |
NameStr(att->attname)))); |
| 1113 |
} |
| 1114 |
} |
| 1115 |
} |
| 1116 |
|
| 1117 |
|
| 1118 |
/* |
| 1119 |
* We disallow indexes on system columns. They would not necessarily get |
| 1120 |
* updated correctly, and they don't seem useful anyway. |
| 1121 |
* |
| 1122 |
* Also disallow virtual generated columns in indexes (use expression |
| 1123 |
* index instead). |
| 1124 |
*/ |
| 1125 |
for (int i = 0; i < indexInfo->ii_NumIndexAttrs; i++) |
| 1126 |
{ |
| 1127 |
AttrNumber attno = indexInfo->ii_IndexAttrNumbers[i]; |
| 1128 |
|
| 1129 |
if (attno < 0) |
| 1130 |
ereport(ERROR, |
| 1131 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1132 |
errmsg("index creation on system columns is not supported"))); |
| 1133 |
|
| 1134 |
|
| 1135 |
if (attno > 0 && |
| 1136 |
TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL) |
| 1137 |
ereport(ERROR, |
| 1138 |
errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1139 |
stmt->primary ? |
| 1140 |
errmsg("primary keys on virtual generated columns are not supported") : |
| 1141 |
stmt->isconstraint ? |
| 1142 |
errmsg("unique constraints on virtual generated columns are not supported") : |
| 1143 |
errmsg("indexes on virtual generated columns are not supported")); |
| 1144 |
} |
| 1145 |
|
| 1146 |
/* |
| 1147 |
* Also check for system and generated columns used in expressions or |
| 1148 |
* predicates. |
| 1149 |
*/ |
| 1150 |
if (indexInfo->ii_Expressions || indexInfo->ii_Predicate) |
| 1151 |
{ |
| 1152 |
Bitmapset *indexattrs = NULL; |
| 1153 |
int j; |
| 1154 |
|
| 1155 |
pull_varattnos((Node *) indexInfo->ii_Expressions, 1, &indexattrs); |
| 1156 |
pull_varattnos((Node *) indexInfo->ii_Predicate, 1, &indexattrs); |
| 1157 |
|
| 1158 |
for (int i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++) |
| 1159 |
{ |
| 1160 |
if (bms_is_member(i - FirstLowInvalidHeapAttributeNumber, |
| 1161 |
indexattrs)) |
| 1162 |
ereport(ERROR, |
| 1163 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1164 |
errmsg("index creation on system columns is not supported"))); |
| 1165 |
} |
| 1166 |
|
| 1167 |
/* |
| 1168 |
* XXX Virtual generated columns in index expressions or predicates |
| 1169 |
* could be supported, but it needs support in |
| 1170 |
* RelationGetIndexExpressions() and RelationGetIndexPredicate(). |
| 1171 |
*/ |
| 1172 |
j = -1; |
| 1173 |
while ((j = bms_next_member(indexattrs, j)) >= 0) |
| 1174 |
{ |
| 1175 |
AttrNumber attno = j + FirstLowInvalidHeapAttributeNumber; |
| 1176 |
|
| 1177 |
if (attno > 0 && |
| 1178 |
TupleDescAttr(RelationGetDescr(rel), attno - 1)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL) |
| 1179 |
ereport(ERROR, |
| 1180 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1181 |
stmt->isconstraint ? |
| 1182 |
errmsg("unique constraints on virtual generated columns are not supported") : |
| 1183 |
errmsg("indexes on virtual generated columns are not supported"))); |
| 1184 |
} |
| 1185 |
} |
| 1186 |
|
| 1187 |
/* Is index safe for others to ignore? See set_indexsafe_procflags() */ |
| 1188 |
safe_index = indexInfo->ii_Expressions == NIL && |
| 1189 |
indexInfo->ii_Predicate == NIL; |
| 1190 |
|
| 1191 |
/* |
| 1192 |
* Report index creation if appropriate (delay this till after most of the |
| 1193 |
* error checks) |
| 1194 |
*/ |
| 1195 |
if (stmt->isconstraint && !quiet) |
| 1196 |
{ |
| 1197 |
const char *constraint_type; |
| 1198 |
|
| 1199 |
if (stmt->primary) |
| 1200 |
constraint_type = "PRIMARY KEY"; |
| 1201 |
else if (stmt->unique) |
| 1202 |
constraint_type = "UNIQUE"; |
| 1203 |
else if (stmt->excludeOpNames) |
| 1204 |
constraint_type = "EXCLUDE"; |
| 1205 |
else |
| 1206 |
{ |
| 1207 |
elog(ERROR, "unknown constraint type"); |
| 1208 |
constraint_type = NULL; /* keep compiler quiet */ |
| 1209 |
} |
| 1210 |
|
| 1211 |
ereport(DEBUG1, |
| 1212 |
(errmsg_internal("%s %s will create implicit index \"%s\" for table \"%s\"", |
| 1213 |
is_alter_table ? "ALTER TABLE / ADD" : "CREATE TABLE /", |
| 1214 |
constraint_type, |
| 1215 |
indexRelationName, RelationGetRelationName(rel)))); |
| 1216 |
} |
| 1217 |
|
| 1218 |
/* |
| 1219 |
* A valid stmt->oldNumber implies that we already have a built form of |
| 1220 |
* the index. The caller should also decline any index build. |
| 1221 |
*/ |
| 1222 |
Assert(!RelFileNumberIsValid(stmt->oldNumber) || (skip_build && !concurrent)); |
| 1223 |
|
| 1224 |
/* |
| 1225 |
* Make the catalog entries for the index, including constraints. This |
| 1226 |
* step also actually builds the index, except if caller requested not to |
| 1227 |
* or in concurrent mode, in which case it'll be done later, or doing a |
| 1228 |
* partitioned index (because those don't have storage). |
| 1229 |
*/ |
| 1230 |
flags = constr_flags = 0; |
| 1231 |
if (stmt->isconstraint) |
| 1232 |
flags |= INDEX_CREATE_ADD_CONSTRAINT; |
| 1233 |
if (skip_build || concurrent || partitioned) |
| 1234 |
flags |= INDEX_CREATE_SKIP_BUILD; |
| 1235 |
if (stmt->if_not_exists) |
| 1236 |
flags |= INDEX_CREATE_IF_NOT_EXISTS; |
| 1237 |
if (concurrent) |
| 1238 |
flags |= INDEX_CREATE_CONCURRENT; |
| 1239 |
if (partitioned) |
| 1240 |
flags |= INDEX_CREATE_PARTITIONED; |
| 1241 |
if (stmt->primary) |
| 1242 |
flags |= INDEX_CREATE_IS_PRIMARY; |
| 1243 |
|
| 1244 |
/* |
| 1245 |
* If the table is partitioned, and recursion was declined but partitions |
| 1246 |
* exist, mark the index as invalid. |
| 1247 |
*/ |
| 1248 |
if (partitioned && stmt->relation && !stmt->relation->inh) |
| 1249 |
{ |
| 1250 |
PartitionDesc pd = RelationGetPartitionDesc(rel, true); |
| 1251 |
|
| 1252 |
if (pd->nparts != 0) |
| 1253 |
flags |= INDEX_CREATE_INVALID; |
| 1254 |
} |
| 1255 |
|
| 1256 |
if (stmt->deferrable) |
| 1257 |
constr_flags |= INDEX_CONSTR_CREATE_DEFERRABLE; |
| 1258 |
if (stmt->initdeferred) |
| 1259 |
constr_flags |= INDEX_CONSTR_CREATE_INIT_DEFERRED; |
| 1260 |
if (stmt->iswithoutoverlaps) |
| 1261 |
constr_flags |= INDEX_CONSTR_CREATE_WITHOUT_OVERLAPS; |
| 1262 |
|
| 1263 |
indexRelationId = |
| 1264 |
index_create(rel, indexRelationName, indexRelationId, parentIndexId, |
| 1265 |
parentConstraintId, |
| 1266 |
stmt->oldNumber, indexInfo, indexColNames, |
| 1267 |
accessMethodId, tablespaceId, |
| 1268 |
collationIds, opclassIds, opclassOptions, |
| 1269 |
coloptions, NULL, reloptions, |
| 1270 |
flags, constr_flags, |
| 1271 |
allowSystemTableMods, !check_rights, |
| 1272 |
&createdConstraintId); |
| 1273 |
|
| 1274 |
ObjectAddressSet(address, RelationRelationId, indexRelationId); |
| 1275 |
|
| 1276 |
if (!OidIsValid(indexRelationId)) |
| 1277 |
{ |
| 1278 |
/* |
| 1279 |
* Roll back any GUC changes executed by index functions. Also revert |
| 1280 |
* to original default_tablespace if we changed it above. |
| 1281 |
*/ |
| 1282 |
AtEOXact_GUC(false, root_save_nestlevel); |
| 1283 |
|
| 1284 |
/* Restore userid and security context */ |
| 1285 |
SetUserIdAndSecContext(root_save_userid, root_save_sec_context); |
| 1286 |
|
| 1287 |
table_close(rel, NoLock); |
| 1288 |
|
| 1289 |
/* If this is the top-level index, we're done */ |
| 1290 |
if (!OidIsValid(parentIndexId)) |
| 1291 |
pgstat_progress_end_command(); |
| 1292 |
|
| 1293 |
return address; |
| 1294 |
} |
| 1295 |
|
| 1296 |
/* |
| 1297 |
* Roll back any GUC changes executed by index functions, and keep |
| 1298 |
* subsequent changes local to this command. This is essential if some |
| 1299 |
* index function changed a behavior-affecting GUC, e.g. search_path. |
| 1300 |
*/ |
| 1301 |
AtEOXact_GUC(false, root_save_nestlevel); |
| 1302 |
root_save_nestlevel = NewGUCNestLevel(); |
| 1303 |
RestrictSearchPath(); |
| 1304 |
|
| 1305 |
/* Add any requested comment */ |
| 1306 |
if (stmt->idxcomment != NULL) |
| 1307 |
CreateComments(indexRelationId, RelationRelationId, 0, |
| 1308 |
stmt->idxcomment); |
| 1309 |
|
| 1310 |
if (partitioned) |
| 1311 |
{ |
| 1312 |
PartitionDesc partdesc; |
| 1313 |
|
| 1314 |
/* |
| 1315 |
* Unless caller specified to skip this step (via ONLY), process each |
| 1316 |
* partition to make sure they all contain a corresponding index. |
| 1317 |
* |
| 1318 |
* If we're called internally (no stmt->relation), recurse always. |
| 1319 |
*/ |
| 1320 |
partdesc = RelationGetPartitionDesc(rel, true); |
| 1321 |
if ((!stmt->relation || stmt->relation->inh) && partdesc->nparts > 0) |
| 1322 |
{ |
| 1323 |
int nparts = partdesc->nparts; |
| 1324 |
Oid *part_oids = palloc_array(Oid, nparts); |
| 1325 |
bool invalidate_parent = false; |
| 1326 |
Relation parentIndex; |
| 1327 |
TupleDesc parentDesc; |
| 1328 |
|
| 1329 |
/* |
| 1330 |
* Report the total number of partitions at the start of the |
| 1331 |
* command; don't update it when being called recursively. |
| 1332 |
*/ |
| 1333 |
if (!OidIsValid(parentIndexId)) |
| 1334 |
{ |
| 1335 |
/* |
| 1336 |
* When called by ProcessUtilitySlow, the number of partitions |
| 1337 |
* is passed in as an optimization; but other callers pass -1 |
| 1338 |
* since they don't have the value handy. This should count |
| 1339 |
* partitions the same way, ie one less than the number of |
| 1340 |
* relations find_all_inheritors reports. |
| 1341 |
* |
| 1342 |
* We assume we needn't ask find_all_inheritors to take locks, |
| 1343 |
* because that should have happened already for all callers. |
| 1344 |
* Even if it did not, this is safe as long as we don't try to |
| 1345 |
* touch the partitions here; the worst consequence would be a |
| 1346 |
* bogus progress-reporting total. |
| 1347 |
*/ |
| 1348 |
if (total_parts < 0) |
| 1349 |
{ |
| 1350 |
List *children = find_all_inheritors(tableId, NoLock, NULL); |
| 1351 |
|
| 1352 |
total_parts = list_length(children) - 1; |
| 1353 |
list_free(children); |
| 1354 |
} |
| 1355 |
|
| 1356 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PARTITIONS_TOTAL, |
| 1357 |
total_parts); |
| 1358 |
} |
| 1359 |
|
| 1360 |
/* Make a local copy of partdesc->oids[], just for safety */ |
| 1361 |
memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts); |
| 1362 |
|
| 1363 |
/* |
| 1364 |
* We'll need an IndexInfo describing the parent index. The one |
| 1365 |
* built above is almost good enough, but not quite, because (for |
| 1366 |
* example) its predicate expression if any hasn't been through |
| 1367 |
* expression preprocessing. The most reliable way to get an |
| 1368 |
* IndexInfo that will match those for child indexes is to build |
| 1369 |
* it the same way, using BuildIndexInfo(). |
| 1370 |
*/ |
| 1371 |
parentIndex = index_open(indexRelationId, lockmode); |
| 1372 |
indexInfo = BuildIndexInfo(parentIndex); |
| 1373 |
|
| 1374 |
parentDesc = RelationGetDescr(rel); |
| 1375 |
|
| 1376 |
/* |
| 1377 |
* For each partition, scan all existing indexes; if one matches |
| 1378 |
* our index definition and is not already attached to some other |
| 1379 |
* parent index, attach it to the one we just created. |
| 1380 |
* |
| 1381 |
* If none matches, build a new index by calling ourselves |
| 1382 |
* recursively with the same options (except for the index name). |
| 1383 |
*/ |
| 1384 |
for (int i = 0; i < nparts; i++) |
| 1385 |
{ |
| 1386 |
Oid childRelid = part_oids[i]; |
| 1387 |
Relation childrel; |
| 1388 |
Oid child_save_userid; |
| 1389 |
int child_save_sec_context; |
| 1390 |
int child_save_nestlevel; |
| 1391 |
List *childidxs; |
| 1392 |
ListCell *cell; |
| 1393 |
AttrMap *attmap; |
| 1394 |
bool found = false; |
| 1395 |
|
| 1396 |
childrel = table_open(childRelid, lockmode); |
| 1397 |
|
| 1398 |
GetUserIdAndSecContext(&child_save_userid, |
| 1399 |
&child_save_sec_context); |
| 1400 |
SetUserIdAndSecContext(childrel->rd_rel->relowner, |
| 1401 |
child_save_sec_context | SECURITY_RESTRICTED_OPERATION); |
| 1402 |
child_save_nestlevel = NewGUCNestLevel(); |
| 1403 |
RestrictSearchPath(); |
| 1404 |
|
| 1405 |
/* |
| 1406 |
* Don't try to create indexes on foreign tables, though. Skip |
| 1407 |
* those if a regular index, or fail if trying to create a |
| 1408 |
* constraint index. |
| 1409 |
*/ |
| 1410 |
if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE) |
| 1411 |
{ |
| 1412 |
if (stmt->unique || stmt->primary) |
| 1413 |
ereport(ERROR, |
| 1414 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 1415 |
errmsg("cannot create unique index on partitioned table \"%s\"", |
| 1416 |
RelationGetRelationName(rel)), |
| 1417 |
errdetail("Table \"%s\" contains partitions that are foreign tables.", |
| 1418 |
RelationGetRelationName(rel)))); |
| 1419 |
|
| 1420 |
AtEOXact_GUC(false, child_save_nestlevel); |
| 1421 |
SetUserIdAndSecContext(child_save_userid, |
| 1422 |
child_save_sec_context); |
| 1423 |
table_close(childrel, lockmode); |
| 1424 |
continue; |
| 1425 |
} |
| 1426 |
|
| 1427 |
childidxs = RelationGetIndexList(childrel); |
| 1428 |
attmap = |
| 1429 |
build_attrmap_by_name(RelationGetDescr(childrel), |
| 1430 |
parentDesc, |
| 1431 |
false); |
| 1432 |
|
| 1433 |
foreach(cell, childidxs) |
| 1434 |
{ |
| 1435 |
Oid cldidxid = lfirst_oid(cell); |
| 1436 |
Relation cldidx; |
| 1437 |
IndexInfo *cldIdxInfo; |
| 1438 |
|
| 1439 |
/* this index is already partition of another one */ |
| 1440 |
if (has_superclass(cldidxid)) |
| 1441 |
continue; |
| 1442 |
|
| 1443 |
cldidx = index_open(cldidxid, lockmode); |
| 1444 |
cldIdxInfo = BuildIndexInfo(cldidx); |
| 1445 |
if (CompareIndexInfo(cldIdxInfo, indexInfo, |
| 1446 |
cldidx->rd_indcollation, |
| 1447 |
parentIndex->rd_indcollation, |
| 1448 |
cldidx->rd_opfamily, |
| 1449 |
parentIndex->rd_opfamily, |
| 1450 |
attmap)) |
| 1451 |
{ |
| 1452 |
Oid cldConstrOid = InvalidOid; |
| 1453 |
|
| 1454 |
/* |
| 1455 |
* Found a match. |
| 1456 |
* |
| 1457 |
* If this index is being created in the parent |
| 1458 |
* because of a constraint, then the child needs to |
| 1459 |
* have a constraint also, so look for one. If there |
| 1460 |
* is no such constraint, this index is no good, so |
| 1461 |
* keep looking. |
| 1462 |
*/ |
| 1463 |
if (createdConstraintId != InvalidOid) |
| 1464 |
{ |
| 1465 |
cldConstrOid = |
| 1466 |
get_relation_idx_constraint_oid(childRelid, |
| 1467 |
cldidxid); |
| 1468 |
if (cldConstrOid == InvalidOid) |
| 1469 |
{ |
| 1470 |
index_close(cldidx, lockmode); |
| 1471 |
continue; |
| 1472 |
} |
| 1473 |
} |
| 1474 |
|
| 1475 |
/* Attach index to parent and we're done. */ |
| 1476 |
IndexSetParentIndex(cldidx, indexRelationId); |
| 1477 |
if (createdConstraintId != InvalidOid) |
| 1478 |
ConstraintSetParentConstraint(cldConstrOid, |
| 1479 |
createdConstraintId, |
| 1480 |
childRelid); |
| 1481 |
|
| 1482 |
if (!cldidx->rd_index->indisvalid) |
| 1483 |
invalidate_parent = true; |
| 1484 |
|
| 1485 |
found = true; |
| 1486 |
|
| 1487 |
/* |
| 1488 |
* Report this partition as processed. Note that if |
| 1489 |
* the partition has children itself, we'd ideally |
| 1490 |
* count the children and update the progress report |
| 1491 |
* for all of them; but that seems unduly expensive. |
| 1492 |
* Instead, the progress report will act like all such |
| 1493 |
* indirect children were processed in zero time at |
| 1494 |
* the end of the command. |
| 1495 |
*/ |
| 1496 |
pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1); |
| 1497 |
|
| 1498 |
/* keep lock till commit */ |
| 1499 |
index_close(cldidx, NoLock); |
| 1500 |
break; |
| 1501 |
} |
| 1502 |
|
| 1503 |
index_close(cldidx, lockmode); |
| 1504 |
} |
| 1505 |
|
| 1506 |
list_free(childidxs); |
| 1507 |
AtEOXact_GUC(false, child_save_nestlevel); |
| 1508 |
SetUserIdAndSecContext(child_save_userid, |
| 1509 |
child_save_sec_context); |
| 1510 |
table_close(childrel, NoLock); |
| 1511 |
|
| 1512 |
/* |
| 1513 |
* If no matching index was found, create our own. |
| 1514 |
*/ |
| 1515 |
if (!found) |
| 1516 |
{ |
| 1517 |
IndexStmt *childStmt; |
| 1518 |
ObjectAddress childAddr; |
| 1519 |
|
| 1520 |
/* |
| 1521 |
* Build an IndexStmt describing the desired child index |
| 1522 |
* in the same way that we do during ATTACH PARTITION. |
| 1523 |
* Notably, we rely on generateClonedIndexStmt to produce |
| 1524 |
* a search-path-independent representation, which the |
| 1525 |
* original IndexStmt might not be. |
| 1526 |
*/ |
| 1527 |
childStmt = generateClonedIndexStmt(NULL, |
| 1528 |
parentIndex, |
| 1529 |
attmap, |
| 1530 |
NULL); |
| 1531 |
|
| 1532 |
/* |
| 1533 |
* Recurse as the starting user ID. Callee will use that |
| 1534 |
* for permission checks, then switch again. |
| 1535 |
*/ |
| 1536 |
Assert(GetUserId() == child_save_userid); |
| 1537 |
SetUserIdAndSecContext(root_save_userid, |
| 1538 |
root_save_sec_context); |
| 1539 |
childAddr = |
| 1540 |
DefineIndex(childRelid, childStmt, |
| 1541 |
InvalidOid, /* no predefined OID */ |
| 1542 |
indexRelationId, /* this is our child */ |
| 1543 |
createdConstraintId, |
| 1544 |
-1, |
| 1545 |
is_alter_table, check_rights, |
| 1546 |
check_not_in_use, |
| 1547 |
skip_build, quiet); |
| 1548 |
SetUserIdAndSecContext(child_save_userid, |
| 1549 |
child_save_sec_context); |
| 1550 |
|
| 1551 |
/* |
| 1552 |
* Check if the index just created is valid or not, as it |
| 1553 |
* could be possible that it has been switched as invalid |
| 1554 |
* when recursing across multiple partition levels. |
| 1555 |
*/ |
| 1556 |
if (!get_index_isvalid(childAddr.objectId)) |
| 1557 |
invalidate_parent = true; |
| 1558 |
} |
| 1559 |
|
| 1560 |
free_attrmap(attmap); |
| 1561 |
} |
| 1562 |
|
| 1563 |
index_close(parentIndex, lockmode); |
| 1564 |
|
| 1565 |
/* |
| 1566 |
* The pg_index row we inserted for this index was marked |
| 1567 |
* indisvalid=true. But if we attached an existing index that is |
| 1568 |
* invalid, this is incorrect, so update our row to invalid too. |
| 1569 |
*/ |
| 1570 |
if (invalidate_parent) |
| 1571 |
{ |
| 1572 |
Relation pg_index = table_open(IndexRelationId, RowExclusiveLock); |
| 1573 |
HeapTuple tup, |
| 1574 |
newtup; |
| 1575 |
|
| 1576 |
tup = SearchSysCache1(INDEXRELID, |
| 1577 |
ObjectIdGetDatum(indexRelationId)); |
| 1578 |
if (!HeapTupleIsValid(tup)) |
| 1579 |
elog(ERROR, "cache lookup failed for index %u", |
| 1580 |
indexRelationId); |
| 1581 |
newtup = heap_copytuple(tup); |
| 1582 |
((Form_pg_index) GETSTRUCT(newtup))->indisvalid = false; |
| 1583 |
CatalogTupleUpdate(pg_index, &tup->t_self, newtup); |
| 1584 |
ReleaseSysCache(tup); |
| 1585 |
table_close(pg_index, RowExclusiveLock); |
| 1586 |
heap_freetuple(newtup); |
| 1587 |
|
| 1588 |
/* |
| 1589 |
* CCI here to make this update visible, in case this recurses |
| 1590 |
* across multiple partition levels. |
| 1591 |
*/ |
| 1592 |
CommandCounterIncrement(); |
| 1593 |
} |
| 1594 |
} |
| 1595 |
|
| 1596 |
/* |
| 1597 |
* Indexes on partitioned tables are not themselves built, so we're |
| 1598 |
* done here. |
| 1599 |
*/ |
| 1600 |
AtEOXact_GUC(false, root_save_nestlevel); |
| 1601 |
SetUserIdAndSecContext(root_save_userid, root_save_sec_context); |
| 1602 |
table_close(rel, NoLock); |
| 1603 |
if (!OidIsValid(parentIndexId)) |
| 1604 |
pgstat_progress_end_command(); |
| 1605 |
else |
| 1606 |
{ |
| 1607 |
/* Update progress for an intermediate partitioned index itself */ |
| 1608 |
pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1); |
| 1609 |
} |
| 1610 |
|
| 1611 |
return address; |
| 1612 |
} |
| 1613 |
|
| 1614 |
AtEOXact_GUC(false, root_save_nestlevel); |
| 1615 |
SetUserIdAndSecContext(root_save_userid, root_save_sec_context); |
| 1616 |
|
| 1617 |
if (!concurrent) |
| 1618 |
{ |
| 1619 |
/* Close the heap and we're done, in the non-concurrent case */ |
| 1620 |
table_close(rel, NoLock); |
| 1621 |
|
| 1622 |
/* |
| 1623 |
* If this is the top-level index, the command is done overall; |
| 1624 |
* otherwise, increment progress to report one child index is done. |
| 1625 |
*/ |
| 1626 |
if (!OidIsValid(parentIndexId)) |
| 1627 |
pgstat_progress_end_command(); |
| 1628 |
else |
| 1629 |
pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1); |
| 1630 |
|
| 1631 |
return address; |
| 1632 |
} |
| 1633 |
|
| 1634 |
/* save lockrelid and locktag for below, then close rel */ |
| 1635 |
heaprelid = rel->rd_lockInfo.lockRelId; |
| 1636 |
SET_LOCKTAG_RELATION(heaplocktag, heaprelid.dbId, heaprelid.relId); |
| 1637 |
table_close(rel, NoLock); |
| 1638 |
|
| 1639 |
/* |
| 1640 |
* For a concurrent build, it's important to make the catalog entries |
| 1641 |
* visible to other transactions before we start to build the index. That |
| 1642 |
* will prevent them from making incompatible HOT updates. The new index |
| 1643 |
* will be marked not indisready and not indisvalid, so that no one else |
| 1644 |
* tries to either insert into it or use it for queries. |
| 1645 |
* |
| 1646 |
* We must commit our current transaction so that the index becomes |
| 1647 |
* visible; then start another. Note that all the data structures we just |
| 1648 |
* built are lost in the commit. The only data we keep past here are the |
| 1649 |
* relation IDs. |
| 1650 |
* |
| 1651 |
* Before committing, get a session-level lock on the table, to ensure |
| 1652 |
* that neither it nor the index can be dropped before we finish. This |
| 1653 |
* cannot block, even if someone else is waiting for access, because we |
| 1654 |
* already have the same lock within our transaction. |
| 1655 |
* |
| 1656 |
* Note: we don't currently bother with a session lock on the index, |
| 1657 |
* because there are no operations that could change its state while we |
| 1658 |
* hold lock on the parent table. This might need to change later. |
| 1659 |
*/ |
| 1660 |
LockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock); |
| 1661 |
|
| 1662 |
PopActiveSnapshot(); |
| 1663 |
CommitTransactionCommand(); |
| 1664 |
StartTransactionCommand(); |
| 1665 |
|
| 1666 |
/* Tell concurrent index builds to ignore us, if index qualifies */ |
| 1667 |
if (safe_index) |
| 1668 |
set_indexsafe_procflags(); |
| 1669 |
|
| 1670 |
/* |
| 1671 |
* The index is now visible, so we can report the OID. While on it, |
| 1672 |
* include the report for the beginning of phase 2. |
| 1673 |
*/ |
| 1674 |
{ |
| 1675 |
const int progress_cols[] = { |
| 1676 |
PROGRESS_CREATEIDX_INDEX_OID, |
| 1677 |
PROGRESS_CREATEIDX_PHASE |
| 1678 |
}; |
| 1679 |
const int64 progress_vals[] = { |
| 1680 |
indexRelationId, |
| 1681 |
PROGRESS_CREATEIDX_PHASE_WAIT_1 |
| 1682 |
}; |
| 1683 |
|
| 1684 |
pgstat_progress_update_multi_param(2, progress_cols, progress_vals); |
| 1685 |
} |
| 1686 |
|
| 1687 |
/* |
| 1688 |
* Phase 2 of concurrent index build (see comments for validate_index() |
| 1689 |
* for an overview of how this works) |
| 1690 |
* |
| 1691 |
* Now we must wait until no running transaction could have the table open |
| 1692 |
* with the old list of indexes. Use ShareLock to consider running |
| 1693 |
* transactions that hold locks that permit writing to the table. Note we |
| 1694 |
* do not need to worry about xacts that open the table for writing after |
| 1695 |
* this point; they will see the new index when they open it. |
| 1696 |
* |
| 1697 |
* Note: the reason we use actual lock acquisition here, rather than just |
| 1698 |
* checking the ProcArray and sleeping, is that deadlock is possible if |
| 1699 |
* one of the transactions in question is blocked trying to acquire an |
| 1700 |
* exclusive lock on our table. The lock code will detect deadlock and |
| 1701 |
* error out properly. |
| 1702 |
*/ |
| 1703 |
WaitForLockers(heaplocktag, ShareLock, true); |
| 1704 |
|
| 1705 |
/* |
| 1706 |
* At this moment we are sure that there are no transactions with the |
| 1707 |
* table open for write that don't have this new index in their list of |
| 1708 |
* indexes. We have waited out all the existing transactions and any new |
| 1709 |
* transaction will have the new index in its list, but the index is still |
| 1710 |
* marked as "not-ready-for-inserts". The index is consulted while |
| 1711 |
* deciding HOT-safety though. This arrangement ensures that no new HOT |
| 1712 |
* chains can be created where the new tuple and the old tuple in the |
| 1713 |
* chain have different index keys. |
| 1714 |
* |
| 1715 |
* We now take a new snapshot, and build the index using all tuples that |
| 1716 |
* are visible in this snapshot. We can be sure that any HOT updates to |
| 1717 |
* these tuples will be compatible with the index, since any updates made |
| 1718 |
* by transactions that didn't know about the index are now committed or |
| 1719 |
* rolled back. Thus, each visible tuple is either the end of its |
| 1720 |
* HOT-chain or the extension of the chain is HOT-safe for this index. |
| 1721 |
*/ |
| 1722 |
|
| 1723 |
/* Set ActiveSnapshot since functions in the indexes may need it */ |
| 1724 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 1725 |
|
| 1726 |
/* Perform concurrent build of index */ |
| 1727 |
index_concurrently_build(tableId, indexRelationId); |
| 1728 |
|
| 1729 |
/* we can do away with our snapshot */ |
| 1730 |
PopActiveSnapshot(); |
| 1731 |
|
| 1732 |
/* |
| 1733 |
* Commit this transaction to make the indisready update visible. |
| 1734 |
*/ |
| 1735 |
CommitTransactionCommand(); |
| 1736 |
StartTransactionCommand(); |
| 1737 |
|
| 1738 |
/* Tell concurrent index builds to ignore us, if index qualifies */ |
| 1739 |
if (safe_index) |
| 1740 |
set_indexsafe_procflags(); |
| 1741 |
|
| 1742 |
/* |
| 1743 |
* Phase 3 of concurrent index build |
| 1744 |
* |
| 1745 |
* We once again wait until no transaction can have the table open with |
| 1746 |
* the index marked as read-only for updates. |
| 1747 |
*/ |
| 1748 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 1749 |
PROGRESS_CREATEIDX_PHASE_WAIT_2); |
| 1750 |
WaitForLockers(heaplocktag, ShareLock, true); |
| 1751 |
|
| 1752 |
/* |
| 1753 |
* Now take the "reference snapshot" that will be used by validate_index() |
| 1754 |
* to filter candidate tuples. Beware! There might still be snapshots in |
| 1755 |
* use that treat some transaction as in-progress that our reference |
| 1756 |
* snapshot treats as committed. If such a recently-committed transaction |
| 1757 |
* deleted tuples in the table, we will not include them in the index; yet |
| 1758 |
* those transactions which see the deleting one as still-in-progress will |
| 1759 |
* expect such tuples to be there once we mark the index as valid. |
| 1760 |
* |
| 1761 |
* We solve this by waiting for all endangered transactions to exit before |
| 1762 |
* we mark the index as valid. |
| 1763 |
* |
| 1764 |
* We also set ActiveSnapshot to this snap, since functions in indexes may |
| 1765 |
* need a snapshot. |
| 1766 |
*/ |
| 1767 |
snapshot = RegisterSnapshot(GetTransactionSnapshot()); |
| 1768 |
PushActiveSnapshot(snapshot); |
| 1769 |
|
| 1770 |
/* |
| 1771 |
* Scan the index and the heap, insert any missing index entries. |
| 1772 |
*/ |
| 1773 |
validate_index(tableId, indexRelationId, snapshot); |
| 1774 |
|
| 1775 |
/* |
| 1776 |
* Drop the reference snapshot. We must do this before waiting out other |
| 1777 |
* snapshot holders, else we will deadlock against other processes also |
| 1778 |
* doing CREATE INDEX CONCURRENTLY, which would see our snapshot as one |
| 1779 |
* they must wait for. But first, save the snapshot's xmin to use as |
| 1780 |
* limitXmin for GetCurrentVirtualXIDs(). |
| 1781 |
*/ |
| 1782 |
limitXmin = snapshot->xmin; |
| 1783 |
|
| 1784 |
PopActiveSnapshot(); |
| 1785 |
UnregisterSnapshot(snapshot); |
| 1786 |
|
| 1787 |
/* |
| 1788 |
* The snapshot subsystem could still contain registered snapshots that |
| 1789 |
* are holding back our process's advertised xmin; in particular, if |
| 1790 |
* default_transaction_isolation = serializable, there is a transaction |
| 1791 |
* snapshot that is still active. The CatalogSnapshot is likewise a |
| 1792 |
* hazard. To ensure no deadlocks, we must commit and start yet another |
| 1793 |
* transaction, and do our wait before any snapshot has been taken in it. |
| 1794 |
*/ |
| 1795 |
CommitTransactionCommand(); |
| 1796 |
StartTransactionCommand(); |
| 1797 |
|
| 1798 |
/* Tell concurrent index builds to ignore us, if index qualifies */ |
| 1799 |
if (safe_index) |
| 1800 |
set_indexsafe_procflags(); |
| 1801 |
|
| 1802 |
/* We should now definitely not be advertising any xmin. */ |
| 1803 |
Assert(MyProc->xmin == InvalidTransactionId); |
| 1804 |
|
| 1805 |
/* |
| 1806 |
* The index is now valid in the sense that it contains all currently |
| 1807 |
* interesting tuples. But since it might not contain tuples deleted just |
| 1808 |
* before the reference snap was taken, we have to wait out any |
| 1809 |
* transactions that might have older snapshots. |
| 1810 |
*/ |
| 1811 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 1812 |
PROGRESS_CREATEIDX_PHASE_WAIT_3); |
| 1813 |
WaitForOlderSnapshots(limitXmin, true); |
| 1814 |
|
| 1815 |
/* |
| 1816 |
* Updating pg_index might involve TOAST table access, so ensure we have a |
| 1817 |
* valid snapshot. |
| 1818 |
*/ |
| 1819 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 1820 |
|
| 1821 |
/* |
| 1822 |
* Index can now be marked valid -- update its pg_index entry |
| 1823 |
*/ |
| 1824 |
index_set_state_flags(indexRelationId, INDEX_CREATE_SET_VALID); |
| 1825 |
|
| 1826 |
PopActiveSnapshot(); |
| 1827 |
|
| 1828 |
/* |
| 1829 |
* The pg_index update will cause backends (including this one) to update |
| 1830 |
* relcache entries for the index itself, but we should also send a |
| 1831 |
* relcache inval on the parent table to force replanning of cached plans. |
| 1832 |
* Otherwise existing sessions might fail to use the new index where it |
| 1833 |
* would be useful. (Note that our earlier commits did not create reasons |
| 1834 |
* to replan; so relcache flush on the index itself was sufficient.) |
| 1835 |
*/ |
| 1836 |
CacheInvalidateRelcacheByRelid(heaprelid.relId); |
| 1837 |
|
| 1838 |
/* |
| 1839 |
* Last thing to do is release the session-level lock on the parent table. |
| 1840 |
*/ |
| 1841 |
UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock); |
| 1842 |
|
| 1843 |
pgstat_progress_end_command(); |
| 1844 |
|
| 1845 |
return address; |
| 1846 |
} |
| 1847 |
|
| 1848 |
|
| 1849 |
/* |
| 1850 |
* CheckPredicate |
| 1851 |
* Checks that the given partial-index predicate is valid. |
| 1852 |
* |
| 1853 |
* This used to also constrain the form of the predicate to forms that |
| 1854 |
* indxpath.c could do something with. However, that seems overly |
| 1855 |
* restrictive. One useful application of partial indexes is to apply |
| 1856 |
* a UNIQUE constraint across a subset of a table, and in that scenario |
| 1857 |
* any evaluable predicate will work. So accept any predicate here |
| 1858 |
* (except ones requiring a plan), and let indxpath.c fend for itself. |
| 1859 |
*/ |
| 1860 |
static void |
| 1861 |
CheckPredicate(Expr *predicate) |
| 1862 |
{ |
| 1863 |
/* |
| 1864 |
* transformExpr() should have already rejected subqueries, aggregates, |
| 1865 |
* and window functions, based on the EXPR_KIND_ for a predicate. |
| 1866 |
*/ |
| 1867 |
|
| 1868 |
/* |
| 1869 |
* A predicate using mutable functions is probably wrong, for the same |
| 1870 |
* reasons that we don't allow an index expression to use one. |
| 1871 |
*/ |
| 1872 |
if (contain_mutable_functions_after_planning(predicate)) |
| 1873 |
ereport(ERROR, |
| 1874 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 1875 |
errmsg("functions in index predicate must be marked IMMUTABLE"))); |
| 1876 |
} |
| 1877 |
|
| 1878 |
/* |
| 1879 |
* Compute per-index-column information, including indexed column numbers |
| 1880 |
* or index expressions, opclasses and their options. Note, all output vectors |
| 1881 |
* should be allocated for all columns, including "including" ones. |
| 1882 |
* |
| 1883 |
* If the caller switched to the table owner, ddl_userid is the role for ACL |
| 1884 |
* checks reached without traversing opaque expressions. Otherwise, it's |
| 1885 |
* InvalidOid, and other ddl_* arguments are undefined. |
| 1886 |
*/ |
| 1887 |
static void |
| 1888 |
ComputeIndexAttrs(IndexInfo *indexInfo, |
| 1889 |
Oid *typeOids, |
| 1890 |
Oid *collationOids, |
| 1891 |
Oid *opclassOids, |
| 1892 |
Datum *opclassOptions, |
| 1893 |
int16 *colOptions, |
| 1894 |
const List *attList, /* list of IndexElem's */ |
| 1895 |
const List *exclusionOpNames, |
| 1896 |
Oid relId, |
| 1897 |
const char *accessMethodName, |
| 1898 |
Oid accessMethodId, |
| 1899 |
bool amcanorder, |
| 1900 |
bool isconstraint, |
| 1901 |
bool iswithoutoverlaps, |
| 1902 |
Oid ddl_userid, |
| 1903 |
int ddl_sec_context, |
| 1904 |
int *ddl_save_nestlevel) |
| 1905 |
{ |
| 1906 |
ListCell *nextExclOp; |
| 1907 |
ListCell *lc; |
| 1908 |
int attn; |
| 1909 |
int nkeycols = indexInfo->ii_NumIndexKeyAttrs; |
| 1910 |
Oid save_userid; |
| 1911 |
int save_sec_context; |
| 1912 |
|
| 1913 |
/* Allocate space for exclusion operator info, if needed */ |
| 1914 |
if (exclusionOpNames) |
| 1915 |
{ |
| 1916 |
Assert(list_length(exclusionOpNames) == nkeycols); |
| 1917 |
indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols); |
| 1918 |
indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols); |
| 1919 |
indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols); |
| 1920 |
nextExclOp = list_head(exclusionOpNames); |
| 1921 |
} |
| 1922 |
else |
| 1923 |
nextExclOp = NULL; |
| 1924 |
|
| 1925 |
/* |
| 1926 |
* If this is a WITHOUT OVERLAPS constraint, we need space for exclusion |
| 1927 |
* ops, but we don't need to parse anything, so we can let nextExclOp be |
| 1928 |
* NULL. Note that for partitions/inheriting/LIKE, exclusionOpNames will |
| 1929 |
* be set, so we already allocated above. |
| 1930 |
*/ |
| 1931 |
if (iswithoutoverlaps) |
| 1932 |
{ |
| 1933 |
if (exclusionOpNames == NIL) |
| 1934 |
{ |
| 1935 |
indexInfo->ii_ExclusionOps = palloc_array(Oid, nkeycols); |
| 1936 |
indexInfo->ii_ExclusionProcs = palloc_array(Oid, nkeycols); |
| 1937 |
indexInfo->ii_ExclusionStrats = palloc_array(uint16, nkeycols); |
| 1938 |
} |
| 1939 |
nextExclOp = NULL; |
| 1940 |
} |
| 1941 |
|
| 1942 |
if (OidIsValid(ddl_userid)) |
| 1943 |
GetUserIdAndSecContext(&save_userid, &save_sec_context); |
| 1944 |
|
| 1945 |
/* |
| 1946 |
* process attributeList |
| 1947 |
*/ |
| 1948 |
attn = 0; |
| 1949 |
foreach(lc, attList) |
| 1950 |
{ |
| 1951 |
IndexElem *attribute = (IndexElem *) lfirst(lc); |
| 1952 |
Oid atttype; |
| 1953 |
Oid attcollation; |
| 1954 |
|
| 1955 |
/* |
| 1956 |
* Process the column-or-expression to be indexed. |
| 1957 |
*/ |
| 1958 |
if (attribute->name != NULL) |
| 1959 |
{ |
| 1960 |
/* Simple index attribute */ |
| 1961 |
HeapTuple atttuple; |
| 1962 |
Form_pg_attribute attform; |
| 1963 |
|
| 1964 |
Assert(attribute->expr == NULL); |
| 1965 |
atttuple = SearchSysCacheAttName(relId, attribute->name); |
| 1966 |
if (!HeapTupleIsValid(atttuple)) |
| 1967 |
{ |
| 1968 |
/* difference in error message spellings is historical */ |
| 1969 |
if (isconstraint) |
| 1970 |
ereport(ERROR, |
| 1971 |
(errcode(ERRCODE_UNDEFINED_COLUMN), |
| 1972 |
errmsg("column \"%s\" named in key does not exist", |
| 1973 |
attribute->name))); |
| 1974 |
else |
| 1975 |
ereport(ERROR, |
| 1976 |
(errcode(ERRCODE_UNDEFINED_COLUMN), |
| 1977 |
errmsg("column \"%s\" does not exist", |
| 1978 |
attribute->name))); |
| 1979 |
} |
| 1980 |
attform = (Form_pg_attribute) GETSTRUCT(atttuple); |
| 1981 |
indexInfo->ii_IndexAttrNumbers[attn] = attform->attnum; |
| 1982 |
atttype = attform->atttypid; |
| 1983 |
attcollation = attform->attcollation; |
| 1984 |
ReleaseSysCache(atttuple); |
| 1985 |
} |
| 1986 |
else |
| 1987 |
{ |
| 1988 |
/* Index expression */ |
| 1989 |
Node *expr = attribute->expr; |
| 1990 |
|
| 1991 |
Assert(expr != NULL); |
| 1992 |
|
| 1993 |
if (attn >= nkeycols) |
| 1994 |
ereport(ERROR, |
| 1995 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 1996 |
errmsg("expressions are not supported in included columns"))); |
| 1997 |
atttype = exprType(expr); |
| 1998 |
attcollation = exprCollation(expr); |
| 1999 |
|
| 2000 |
/* |
| 2001 |
* Strip any top-level COLLATE clause. This ensures that we treat |
| 2002 |
* "x COLLATE y" and "(x COLLATE y)" alike. |
| 2003 |
*/ |
| 2004 |
while (IsA(expr, CollateExpr)) |
| 2005 |
expr = (Node *) ((CollateExpr *) expr)->arg; |
| 2006 |
|
| 2007 |
if (IsA(expr, Var) && |
| 2008 |
((Var *) expr)->varattno != InvalidAttrNumber) |
| 2009 |
{ |
| 2010 |
/* |
| 2011 |
* User wrote "(column)" or "(column COLLATE something)". |
| 2012 |
* Treat it like simple attribute anyway. |
| 2013 |
*/ |
| 2014 |
indexInfo->ii_IndexAttrNumbers[attn] = ((Var *) expr)->varattno; |
| 2015 |
} |
| 2016 |
else |
| 2017 |
{ |
| 2018 |
indexInfo->ii_IndexAttrNumbers[attn] = 0; /* marks expression */ |
| 2019 |
indexInfo->ii_Expressions = lappend(indexInfo->ii_Expressions, |
| 2020 |
expr); |
| 2021 |
|
| 2022 |
/* |
| 2023 |
* transformExpr() should have already rejected subqueries, |
| 2024 |
* aggregates, and window functions, based on the EXPR_KIND_ |
| 2025 |
* for an index expression. |
| 2026 |
*/ |
| 2027 |
|
| 2028 |
/* |
| 2029 |
* An expression using mutable functions is probably wrong, |
| 2030 |
* since if you aren't going to get the same result for the |
| 2031 |
* same data every time, it's not clear what the index entries |
| 2032 |
* mean at all. |
| 2033 |
*/ |
| 2034 |
if (contain_mutable_functions_after_planning((Expr *) expr)) |
| 2035 |
ereport(ERROR, |
| 2036 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 2037 |
errmsg("functions in index expression must be marked IMMUTABLE"))); |
| 2038 |
} |
| 2039 |
} |
| 2040 |
|
| 2041 |
typeOids[attn] = atttype; |
| 2042 |
|
| 2043 |
/* |
| 2044 |
* Included columns have no collation, no opclass and no ordering |
| 2045 |
* options. |
| 2046 |
*/ |
| 2047 |
if (attn >= nkeycols) |
| 2048 |
{ |
| 2049 |
if (attribute->collation) |
| 2050 |
ereport(ERROR, |
| 2051 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 2052 |
errmsg("including column does not support a collation"))); |
| 2053 |
if (attribute->opclass) |
| 2054 |
ereport(ERROR, |
| 2055 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 2056 |
errmsg("including column does not support an operator class"))); |
| 2057 |
if (attribute->ordering != SORTBY_DEFAULT) |
| 2058 |
ereport(ERROR, |
| 2059 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 2060 |
errmsg("including column does not support ASC/DESC options"))); |
| 2061 |
if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT) |
| 2062 |
ereport(ERROR, |
| 2063 |
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION), |
| 2064 |
errmsg("including column does not support NULLS FIRST/LAST options"))); |
| 2065 |
|
| 2066 |
opclassOids[attn] = InvalidOid; |
| 2067 |
opclassOptions[attn] = (Datum) 0; |
| 2068 |
colOptions[attn] = 0; |
| 2069 |
collationOids[attn] = InvalidOid; |
| 2070 |
attn++; |
| 2071 |
|
| 2072 |
continue; |
| 2073 |
} |
| 2074 |
|
| 2075 |
/* |
| 2076 |
* Apply collation override if any. Use of ddl_userid is necessary |
| 2077 |
* due to ACL checks therein, and it's safe because collations don't |
| 2078 |
* contain opaque expressions (or non-opaque expressions). |
| 2079 |
*/ |
| 2080 |
if (attribute->collation) |
| 2081 |
{ |
| 2082 |
if (OidIsValid(ddl_userid)) |
| 2083 |
{ |
| 2084 |
AtEOXact_GUC(false, *ddl_save_nestlevel); |
| 2085 |
SetUserIdAndSecContext(ddl_userid, ddl_sec_context); |
| 2086 |
} |
| 2087 |
attcollation = get_collation_oid(attribute->collation, false); |
| 2088 |
if (OidIsValid(ddl_userid)) |
| 2089 |
{ |
| 2090 |
SetUserIdAndSecContext(save_userid, save_sec_context); |
| 2091 |
*ddl_save_nestlevel = NewGUCNestLevel(); |
| 2092 |
RestrictSearchPath(); |
| 2093 |
} |
| 2094 |
} |
| 2095 |
|
| 2096 |
/* |
| 2097 |
* Check we have a collation iff it's a collatable type. The only |
| 2098 |
* expected failures here are (1) COLLATE applied to a noncollatable |
| 2099 |
* type, or (2) index expression had an unresolved collation. But we |
| 2100 |
* might as well code this to be a complete consistency check. |
| 2101 |
*/ |
| 2102 |
if (type_is_collatable(atttype)) |
| 2103 |
{ |
| 2104 |
if (!OidIsValid(attcollation)) |
| 2105 |
ereport(ERROR, |
| 2106 |
(errcode(ERRCODE_INDETERMINATE_COLLATION), |
| 2107 |
errmsg("could not determine which collation to use for index expression"), |
| 2108 |
errhint("Use the COLLATE clause to set the collation explicitly."))); |
| 2109 |
} |
| 2110 |
else |
| 2111 |
{ |
| 2112 |
if (OidIsValid(attcollation)) |
| 2113 |
ereport(ERROR, |
| 2114 |
(errcode(ERRCODE_DATATYPE_MISMATCH), |
| 2115 |
errmsg("collations are not supported by type %s", |
| 2116 |
format_type_be(atttype)))); |
| 2117 |
} |
| 2118 |
|
| 2119 |
collationOids[attn] = attcollation; |
| 2120 |
|
| 2121 |
/* |
| 2122 |
* Identify the opclass to use. Use of ddl_userid is necessary due to |
| 2123 |
* ACL checks therein. This is safe despite opclasses containing |
| 2124 |
* opaque expressions (specifically, functions), because only |
| 2125 |
* superusers can define opclasses. |
| 2126 |
*/ |
| 2127 |
if (OidIsValid(ddl_userid)) |
| 2128 |
{ |
| 2129 |
AtEOXact_GUC(false, *ddl_save_nestlevel); |
| 2130 |
SetUserIdAndSecContext(ddl_userid, ddl_sec_context); |
| 2131 |
} |
| 2132 |
opclassOids[attn] = ResolveOpClass(attribute->opclass, |
| 2133 |
atttype, |
| 2134 |
accessMethodName, |
| 2135 |
accessMethodId); |
| 2136 |
if (OidIsValid(ddl_userid)) |
| 2137 |
{ |
| 2138 |
SetUserIdAndSecContext(save_userid, save_sec_context); |
| 2139 |
*ddl_save_nestlevel = NewGUCNestLevel(); |
| 2140 |
RestrictSearchPath(); |
| 2141 |
} |
| 2142 |
|
| 2143 |
/* |
| 2144 |
* Identify the exclusion operator, if any. |
| 2145 |
*/ |
| 2146 |
if (nextExclOp) |
| 2147 |
{ |
| 2148 |
List *opname = (List *) lfirst(nextExclOp); |
| 2149 |
Oid opid; |
| 2150 |
Oid opfamily; |
| 2151 |
int strat; |
| 2152 |
|
| 2153 |
/* |
| 2154 |
* Find the operator --- it must accept the column datatype |
| 2155 |
* without runtime coercion (but binary compatibility is OK). |
| 2156 |
* Operators contain opaque expressions (specifically, functions). |
| 2157 |
* compatible_oper_opid() boils down to oper() and |
| 2158 |
* IsBinaryCoercible(). PostgreSQL would have security problems |
| 2159 |
* elsewhere if oper() started calling opaque expressions. |
| 2160 |
*/ |
| 2161 |
if (OidIsValid(ddl_userid)) |
| 2162 |
{ |
| 2163 |
AtEOXact_GUC(false, *ddl_save_nestlevel); |
| 2164 |
SetUserIdAndSecContext(ddl_userid, ddl_sec_context); |
| 2165 |
} |
| 2166 |
opid = compatible_oper_opid(opname, atttype, atttype, false); |
| 2167 |
if (OidIsValid(ddl_userid)) |
| 2168 |
{ |
| 2169 |
SetUserIdAndSecContext(save_userid, save_sec_context); |
| 2170 |
*ddl_save_nestlevel = NewGUCNestLevel(); |
| 2171 |
RestrictSearchPath(); |
| 2172 |
} |
| 2173 |
|
| 2174 |
/* |
| 2175 |
* Only allow commutative operators to be used in exclusion |
| 2176 |
* constraints. If X conflicts with Y, but Y does not conflict |
| 2177 |
* with X, bad things will happen. |
| 2178 |
*/ |
| 2179 |
if (get_commutator(opid) != opid) |
| 2180 |
ereport(ERROR, |
| 2181 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 2182 |
errmsg("operator %s is not commutative", |
| 2183 |
format_operator(opid)), |
| 2184 |
errdetail("Only commutative operators can be used in exclusion constraints."))); |
| 2185 |
|
| 2186 |
/* |
| 2187 |
* Operator must be a member of the right opfamily, too |
| 2188 |
*/ |
| 2189 |
opfamily = get_opclass_family(opclassOids[attn]); |
| 2190 |
strat = get_op_opfamily_strategy(opid, opfamily); |
| 2191 |
if (strat == 0) |
| 2192 |
ereport(ERROR, |
| 2193 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 2194 |
errmsg("operator %s is not a member of operator family \"%s\"", |
| 2195 |
format_operator(opid), |
| 2196 |
get_opfamily_name(opfamily, false)), |
| 2197 |
errdetail("The exclusion operator must be related to the index operator class for the constraint."))); |
| 2198 |
|
| 2199 |
indexInfo->ii_ExclusionOps[attn] = opid; |
| 2200 |
indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid); |
| 2201 |
indexInfo->ii_ExclusionStrats[attn] = strat; |
| 2202 |
nextExclOp = lnext(exclusionOpNames, nextExclOp); |
| 2203 |
} |
| 2204 |
else if (iswithoutoverlaps) |
| 2205 |
{ |
| 2206 |
CompareType cmptype; |
| 2207 |
StrategyNumber strat; |
| 2208 |
Oid opid; |
| 2209 |
|
| 2210 |
if (attn == nkeycols - 1) |
| 2211 |
cmptype = COMPARE_OVERLAP; |
| 2212 |
else |
| 2213 |
cmptype = COMPARE_EQ; |
| 2214 |
GetOperatorFromCompareType(opclassOids[attn], InvalidOid, cmptype, &opid, &strat); |
| 2215 |
indexInfo->ii_ExclusionOps[attn] = opid; |
| 2216 |
indexInfo->ii_ExclusionProcs[attn] = get_opcode(opid); |
| 2217 |
indexInfo->ii_ExclusionStrats[attn] = strat; |
| 2218 |
} |
| 2219 |
|
| 2220 |
/* |
| 2221 |
* Set up the per-column options (indoption field). For now, this is |
| 2222 |
* zero for any un-ordered index, while ordered indexes have DESC and |
| 2223 |
* NULLS FIRST/LAST options. |
| 2224 |
*/ |
| 2225 |
colOptions[attn] = 0; |
| 2226 |
if (amcanorder) |
| 2227 |
{ |
| 2228 |
/* default ordering is ASC */ |
| 2229 |
if (attribute->ordering == SORTBY_DESC) |
| 2230 |
colOptions[attn] |= INDOPTION_DESC; |
| 2231 |
/* default null ordering is LAST for ASC, FIRST for DESC */ |
| 2232 |
if (attribute->nulls_ordering == SORTBY_NULLS_DEFAULT) |
| 2233 |
{ |
| 2234 |
if (attribute->ordering == SORTBY_DESC) |
| 2235 |
colOptions[attn] |= INDOPTION_NULLS_FIRST; |
| 2236 |
} |
| 2237 |
else if (attribute->nulls_ordering == SORTBY_NULLS_FIRST) |
| 2238 |
colOptions[attn] |= INDOPTION_NULLS_FIRST; |
| 2239 |
} |
| 2240 |
else |
| 2241 |
{ |
| 2242 |
/* index AM does not support ordering */ |
| 2243 |
if (attribute->ordering != SORTBY_DEFAULT) |
| 2244 |
ereport(ERROR, |
| 2245 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 2246 |
errmsg("access method \"%s\" does not support ASC/DESC options", |
| 2247 |
accessMethodName))); |
| 2248 |
if (attribute->nulls_ordering != SORTBY_NULLS_DEFAULT) |
| 2249 |
ereport(ERROR, |
| 2250 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 2251 |
errmsg("access method \"%s\" does not support NULLS FIRST/LAST options", |
| 2252 |
accessMethodName))); |
| 2253 |
} |
| 2254 |
|
| 2255 |
/* Set up the per-column opclass options (attoptions field). */ |
| 2256 |
if (attribute->opclassopts) |
| 2257 |
{ |
| 2258 |
Assert(attn < nkeycols); |
| 2259 |
|
| 2260 |
opclassOptions[attn] = |
| 2261 |
transformRelOptions((Datum) 0, attribute->opclassopts, |
| 2262 |
NULL, NULL, false, false); |
| 2263 |
} |
| 2264 |
else |
| 2265 |
opclassOptions[attn] = (Datum) 0; |
| 2266 |
|
| 2267 |
attn++; |
| 2268 |
} |
| 2269 |
} |
| 2270 |
|
| 2271 |
/* |
| 2272 |
* Resolve possibly-defaulted operator class specification |
| 2273 |
* |
| 2274 |
* Note: This is used to resolve operator class specifications in index and |
| 2275 |
* partition key definitions. |
| 2276 |
*/ |
| 2277 |
Oid |
| 2278 |
ResolveOpClass(const List *opclass, Oid attrType, |
| 2279 |
const char *accessMethodName, Oid accessMethodId) |
| 2280 |
{ |
| 2281 |
char *schemaname; |
| 2282 |
char *opcname; |
| 2283 |
HeapTuple tuple; |
| 2284 |
Form_pg_opclass opform; |
| 2285 |
Oid opClassId, |
| 2286 |
opInputType; |
| 2287 |
|
| 2288 |
if (opclass == NIL) |
| 2289 |
{ |
| 2290 |
/* no operator class specified, so find the default */ |
| 2291 |
opClassId = GetDefaultOpClass(attrType, accessMethodId); |
| 2292 |
if (!OidIsValid(opClassId)) |
| 2293 |
ereport(ERROR, |
| 2294 |
(errcode(ERRCODE_UNDEFINED_OBJECT), |
| 2295 |
errmsg("data type %s has no default operator class for access method \"%s\"", |
| 2296 |
format_type_be(attrType), accessMethodName), |
| 2297 |
errhint("You must specify an operator class for the index or define a default operator class for the data type."))); |
| 2298 |
return opClassId; |
| 2299 |
} |
| 2300 |
|
| 2301 |
/* |
| 2302 |
* Specific opclass name given, so look up the opclass. |
| 2303 |
*/ |
| 2304 |
|
| 2305 |
/* deconstruct the name list */ |
| 2306 |
DeconstructQualifiedName(opclass, &schemaname, &opcname); |
| 2307 |
|
| 2308 |
if (schemaname) |
| 2309 |
{ |
| 2310 |
/* Look in specific schema only */ |
| 2311 |
Oid namespaceId; |
| 2312 |
|
| 2313 |
namespaceId = LookupExplicitNamespace(schemaname, false); |
| 2314 |
tuple = SearchSysCache3(CLAAMNAMENSP, |
| 2315 |
ObjectIdGetDatum(accessMethodId), |
| 2316 |
PointerGetDatum(opcname), |
| 2317 |
ObjectIdGetDatum(namespaceId)); |
| 2318 |
} |
| 2319 |
else |
| 2320 |
{ |
| 2321 |
/* Unqualified opclass name, so search the search path */ |
| 2322 |
opClassId = OpclassnameGetOpcid(accessMethodId, opcname); |
| 2323 |
if (!OidIsValid(opClassId)) |
| 2324 |
ereport(ERROR, |
| 2325 |
(errcode(ERRCODE_UNDEFINED_OBJECT), |
| 2326 |
errmsg("operator class \"%s\" does not exist for access method \"%s\"", |
| 2327 |
opcname, accessMethodName))); |
| 2328 |
tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opClassId)); |
| 2329 |
} |
| 2330 |
|
| 2331 |
if (!HeapTupleIsValid(tuple)) |
| 2332 |
ereport(ERROR, |
| 2333 |
(errcode(ERRCODE_UNDEFINED_OBJECT), |
| 2334 |
errmsg("operator class \"%s\" does not exist for access method \"%s\"", |
| 2335 |
NameListToString(opclass), accessMethodName))); |
| 2336 |
|
| 2337 |
/* |
| 2338 |
* Verify that the index operator class accepts this datatype. Note we |
| 2339 |
* will accept binary compatibility. |
| 2340 |
*/ |
| 2341 |
opform = (Form_pg_opclass) GETSTRUCT(tuple); |
| 2342 |
opClassId = opform->oid; |
| 2343 |
opInputType = opform->opcintype; |
| 2344 |
|
| 2345 |
if (!IsBinaryCoercible(attrType, opInputType)) |
| 2346 |
ereport(ERROR, |
| 2347 |
(errcode(ERRCODE_DATATYPE_MISMATCH), |
| 2348 |
errmsg("operator class \"%s\" does not accept data type %s", |
| 2349 |
NameListToString(opclass), format_type_be(attrType)))); |
| 2350 |
|
| 2351 |
ReleaseSysCache(tuple); |
| 2352 |
|
| 2353 |
return opClassId; |
| 2354 |
} |
| 2355 |
|
| 2356 |
/* |
| 2357 |
* GetDefaultOpClass |
| 2358 |
* |
| 2359 |
* Given the OIDs of a datatype and an access method, find the default |
| 2360 |
* operator class, if any. Returns InvalidOid if there is none. |
| 2361 |
*/ |
| 2362 |
Oid |
| 2363 |
GetDefaultOpClass(Oid type_id, Oid am_id) |
| 2364 |
{ |
| 2365 |
Oid result = InvalidOid; |
| 2366 |
int nexact = 0; |
| 2367 |
int ncompatible = 0; |
| 2368 |
int ncompatiblepreferred = 0; |
| 2369 |
Relation rel; |
| 2370 |
ScanKeyData skey[1]; |
| 2371 |
SysScanDesc scan; |
| 2372 |
HeapTuple tup; |
| 2373 |
TYPCATEGORY tcategory; |
| 2374 |
|
| 2375 |
/* If it's a domain, look at the base type instead */ |
| 2376 |
type_id = getBaseType(type_id); |
| 2377 |
|
| 2378 |
tcategory = TypeCategory(type_id); |
| 2379 |
|
| 2380 |
/* |
| 2381 |
* We scan through all the opclasses available for the access method, |
| 2382 |
* looking for one that is marked default and matches the target type |
| 2383 |
* (either exactly or binary-compatibly, but prefer an exact match). |
| 2384 |
* |
| 2385 |
* We could find more than one binary-compatible match. If just one is |
| 2386 |
* for a preferred type, use that one; otherwise we fail, forcing the user |
| 2387 |
* to specify which one he wants. (The preferred-type special case is a |
| 2388 |
* kluge for varchar: it's binary-compatible to both text and bpchar, so |
| 2389 |
* we need a tiebreaker.) If we find more than one exact match, then |
| 2390 |
* someone put bogus entries in pg_opclass. |
| 2391 |
*/ |
| 2392 |
rel = table_open(OperatorClassRelationId, AccessShareLock); |
| 2393 |
|
| 2394 |
ScanKeyInit(&skey[0], |
| 2395 |
Anum_pg_opclass_opcmethod, |
| 2396 |
BTEqualStrategyNumber, F_OIDEQ, |
| 2397 |
ObjectIdGetDatum(am_id)); |
| 2398 |
|
| 2399 |
scan = systable_beginscan(rel, OpclassAmNameNspIndexId, true, |
| 2400 |
NULL, 1, skey); |
| 2401 |
|
| 2402 |
while (HeapTupleIsValid(tup = systable_getnext(scan))) |
| 2403 |
{ |
| 2404 |
Form_pg_opclass opclass = (Form_pg_opclass) GETSTRUCT(tup); |
| 2405 |
|
| 2406 |
/* ignore altogether if not a default opclass */ |
| 2407 |
if (!opclass->opcdefault) |
| 2408 |
continue; |
| 2409 |
if (opclass->opcintype == type_id) |
| 2410 |
{ |
| 2411 |
nexact++; |
| 2412 |
result = opclass->oid; |
| 2413 |
} |
| 2414 |
else if (nexact == 0 && |
| 2415 |
IsBinaryCoercible(type_id, opclass->opcintype)) |
| 2416 |
{ |
| 2417 |
if (IsPreferredType(tcategory, opclass->opcintype)) |
| 2418 |
{ |
| 2419 |
ncompatiblepreferred++; |
| 2420 |
result = opclass->oid; |
| 2421 |
} |
| 2422 |
else if (ncompatiblepreferred == 0) |
| 2423 |
{ |
| 2424 |
ncompatible++; |
| 2425 |
result = opclass->oid; |
| 2426 |
} |
| 2427 |
} |
| 2428 |
} |
| 2429 |
|
| 2430 |
systable_endscan(scan); |
| 2431 |
|
| 2432 |
table_close(rel, AccessShareLock); |
| 2433 |
|
| 2434 |
/* raise error if pg_opclass contains inconsistent data */ |
| 2435 |
if (nexact > 1) |
| 2436 |
ereport(ERROR, |
| 2437 |
(errcode(ERRCODE_DUPLICATE_OBJECT), |
| 2438 |
errmsg("there are multiple default operator classes for data type %s", |
| 2439 |
format_type_be(type_id)))); |
| 2440 |
|
| 2441 |
if (nexact == 1 || |
| 2442 |
ncompatiblepreferred == 1 || |
| 2443 |
(ncompatiblepreferred == 0 && ncompatible == 1)) |
| 2444 |
return result; |
| 2445 |
|
| 2446 |
return InvalidOid; |
| 2447 |
} |
| 2448 |
|
| 2449 |
/* |
| 2450 |
* GetOperatorFromCompareType |
| 2451 |
* |
| 2452 |
* opclass - the opclass to use |
| 2453 |
* rhstype - the type for the right-hand side, or InvalidOid to use the type of the given opclass. |
| 2454 |
* cmptype - kind of operator to find |
| 2455 |
* opid - holds the operator we found |
| 2456 |
* strat - holds the output strategy number |
| 2457 |
* |
| 2458 |
* Finds an operator from a CompareType. This is used for temporal index |
| 2459 |
* constraints (and other temporal features) to look up equality and overlaps |
| 2460 |
* operators. We ask an opclass support function to translate from the |
| 2461 |
* compare type to the internal strategy numbers. Raises ERROR on search |
| 2462 |
* failure. |
| 2463 |
*/ |
| 2464 |
void |
| 2465 |
GetOperatorFromCompareType(Oid opclass, Oid rhstype, CompareType cmptype, |
| 2466 |
Oid *opid, StrategyNumber *strat) |
| 2467 |
{ |
| 2468 |
Oid amid; |
| 2469 |
Oid opfamily; |
| 2470 |
Oid opcintype; |
| 2471 |
|
| 2472 |
Assert(cmptype == COMPARE_EQ || cmptype == COMPARE_OVERLAP || cmptype == COMPARE_CONTAINED_BY); |
| 2473 |
|
| 2474 |
amid = get_opclass_method(opclass); |
| 2475 |
|
| 2476 |
*opid = InvalidOid; |
| 2477 |
|
| 2478 |
if (get_opclass_opfamily_and_input_type(opclass, &opfamily, &opcintype)) |
| 2479 |
{ |
| 2480 |
/* |
| 2481 |
* Ask the index AM to translate to its internal stratnum |
| 2482 |
*/ |
| 2483 |
*strat = IndexAmTranslateCompareType(cmptype, amid, opfamily, true); |
| 2484 |
if (*strat == InvalidStrategy) |
| 2485 |
ereport(ERROR, |
| 2486 |
errcode(ERRCODE_UNDEFINED_OBJECT), |
| 2487 |
cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) : |
| 2488 |
cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) : |
| 2489 |
cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0, |
| 2490 |
errdetail("Could not translate compare type %d for operator family \"%s\" of access method \"%s\".", |
| 2491 |
cmptype, get_opfamily_name(opfamily, false), get_am_name(amid))); |
| 2492 |
|
| 2493 |
/* |
| 2494 |
* We parameterize rhstype so foreign keys can ask for a <@ operator |
| 2495 |
* whose rhs matches the aggregate function. For example range_agg |
| 2496 |
* returns anymultirange. |
| 2497 |
*/ |
| 2498 |
if (!OidIsValid(rhstype)) |
| 2499 |
rhstype = opcintype; |
| 2500 |
*opid = get_opfamily_member(opfamily, opcintype, rhstype, *strat); |
| 2501 |
} |
| 2502 |
|
| 2503 |
if (!OidIsValid(*opid)) |
| 2504 |
ereport(ERROR, |
| 2505 |
errcode(ERRCODE_UNDEFINED_OBJECT), |
| 2506 |
cmptype == COMPARE_EQ ? errmsg("could not identify an equality operator for type %s", format_type_be(opcintype)) : |
| 2507 |
cmptype == COMPARE_OVERLAP ? errmsg("could not identify an overlaps operator for type %s", format_type_be(opcintype)) : |
| 2508 |
cmptype == COMPARE_CONTAINED_BY ? errmsg("could not identify a contained-by operator for type %s", format_type_be(opcintype)) : 0, |
| 2509 |
errdetail("There is no suitable operator in operator family \"%s\" for access method \"%s\".", |
| 2510 |
get_opfamily_name(opfamily, false), get_am_name(amid))); |
| 2511 |
} |
| 2512 |
|
| 2513 |
/* |
| 2514 |
* makeObjectName() |
| 2515 |
* |
| 2516 |
* Create a name for an implicitly created index, sequence, constraint, |
| 2517 |
* extended statistics, etc. |
| 2518 |
* |
| 2519 |
* The parameters are typically: the original table name, the original field |
| 2520 |
* name, and a "type" string (such as "seq" or "pkey"). The field name |
| 2521 |
* and/or type can be NULL if not relevant. |
| 2522 |
* |
| 2523 |
* The result is a palloc'd string. |
| 2524 |
* |
| 2525 |
* The basic result we want is "name1_name2_label", omitting "_name2" or |
| 2526 |
* "_label" when those parameters are NULL. However, we must generate |
| 2527 |
* a name with less than NAMEDATALEN characters! So, we truncate one or |
| 2528 |
* both names if necessary to make a short-enough string. The label part |
| 2529 |
* is never truncated (so it had better be reasonably short). |
| 2530 |
* |
| 2531 |
* The caller is responsible for checking uniqueness of the generated |
| 2532 |
* name and retrying as needed; retrying will be done by altering the |
| 2533 |
* "label" string (which is why we never truncate that part). |
| 2534 |
*/ |
| 2535 |
char * |
| 2536 |
makeObjectName(const char *name1, const char *name2, const char *label) |
| 2537 |
{ |
| 2538 |
char *name; |
| 2539 |
int overhead = 0; /* chars needed for label and underscores */ |
| 2540 |
int availchars; /* chars available for name(s) */ |
| 2541 |
int name1chars; /* chars allocated to name1 */ |
| 2542 |
int name2chars; /* chars allocated to name2 */ |
| 2543 |
int ndx; |
| 2544 |
|
| 2545 |
name1chars = strlen(name1); |
| 2546 |
if (name2) |
| 2547 |
{ |
| 2548 |
name2chars = strlen(name2); |
| 2549 |
overhead++; /* allow for separating underscore */ |
| 2550 |
} |
| 2551 |
else |
| 2552 |
name2chars = 0; |
| 2553 |
if (label) |
| 2554 |
overhead += strlen(label) + 1; |
| 2555 |
|
| 2556 |
availchars = NAMEDATALEN - 1 - overhead; |
| 2557 |
Assert(availchars > 0); /* else caller chose a bad label */ |
| 2558 |
|
| 2559 |
/* |
| 2560 |
* If we must truncate, preferentially truncate the longer name. This |
| 2561 |
* logic could be expressed without a loop, but it's simple and obvious as |
| 2562 |
* a loop. |
| 2563 |
*/ |
| 2564 |
while (name1chars + name2chars > availchars) |
| 2565 |
{ |
| 2566 |
if (name1chars > name2chars) |
| 2567 |
name1chars--; |
| 2568 |
else |
| 2569 |
name2chars--; |
| 2570 |
} |
| 2571 |
|
| 2572 |
name1chars = pg_mbcliplen(name1, name1chars, name1chars); |
| 2573 |
if (name2) |
| 2574 |
name2chars = pg_mbcliplen(name2, name2chars, name2chars); |
| 2575 |
|
| 2576 |
/* Now construct the string using the chosen lengths */ |
| 2577 |
name = palloc(name1chars + name2chars + overhead + 1); |
| 2578 |
memcpy(name, name1, name1chars); |
| 2579 |
ndx = name1chars; |
| 2580 |
if (name2) |
| 2581 |
{ |
| 2582 |
name[ndx++] = '_'; |
| 2583 |
memcpy(name + ndx, name2, name2chars); |
| 2584 |
ndx += name2chars; |
| 2585 |
} |
| 2586 |
if (label) |
| 2587 |
{ |
| 2588 |
name[ndx++] = '_'; |
| 2589 |
strcpy(name + ndx, label); |
| 2590 |
} |
| 2591 |
else |
| 2592 |
name[ndx] = '\0'; |
| 2593 |
|
| 2594 |
return name; |
| 2595 |
} |
| 2596 |
|
| 2597 |
/* |
| 2598 |
* Select a nonconflicting name for a new relation. This is ordinarily |
| 2599 |
* used to choose index names (which is why it's here) but it can also |
| 2600 |
* be used for sequences, or any autogenerated relation kind. |
| 2601 |
* |
| 2602 |
* name1, name2, and label are used the same way as for makeObjectName(), |
| 2603 |
* except that the label can't be NULL; digits will be appended to the label |
| 2604 |
* if needed to create a name that is unique within the specified namespace. |
| 2605 |
* |
| 2606 |
* If isconstraint is true, we also avoid choosing a name matching any |
| 2607 |
* existing constraint in the same namespace. (This is stricter than what |
| 2608 |
* Postgres itself requires, but the SQL standard says that constraint names |
| 2609 |
* should be unique within schemas, so we follow that for autogenerated |
| 2610 |
* constraint names.) |
| 2611 |
* |
| 2612 |
* Note: it is theoretically possible to get a collision anyway, if someone |
| 2613 |
* else chooses the same name concurrently. We shorten the race condition |
| 2614 |
* window by checking for conflicting relations using SnapshotDirty, but |
| 2615 |
* that doesn't close the window entirely. This is fairly unlikely to be |
| 2616 |
* a problem in practice, especially if one is holding an exclusive lock on |
| 2617 |
* the relation identified by name1. However, if choosing multiple names |
| 2618 |
* within a single command, you'd better create the new object and do |
| 2619 |
* CommandCounterIncrement before choosing the next one! |
| 2620 |
* |
| 2621 |
* Returns a palloc'd string. |
| 2622 |
*/ |
| 2623 |
char * |
| 2624 |
ChooseRelationName(const char *name1, const char *name2, |
| 2625 |
const char *label, Oid namespaceid, |
| 2626 |
bool isconstraint) |
| 2627 |
{ |
| 2628 |
int pass = 0; |
| 2629 |
char *relname = NULL; |
| 2630 |
char modlabel[NAMEDATALEN]; |
| 2631 |
SnapshotData SnapshotDirty; |
| 2632 |
Relation pgclassrel; |
| 2633 |
|
| 2634 |
/* prepare to search pg_class with a dirty snapshot */ |
| 2635 |
InitDirtySnapshot(SnapshotDirty); |
| 2636 |
pgclassrel = table_open(RelationRelationId, AccessShareLock); |
| 2637 |
|
| 2638 |
/* try the unmodified label first */ |
| 2639 |
strlcpy(modlabel, label, sizeof(modlabel)); |
| 2640 |
|
| 2641 |
for (;;) |
| 2642 |
{ |
| 2643 |
ScanKeyData key[2]; |
| 2644 |
SysScanDesc scan; |
| 2645 |
bool collides; |
| 2646 |
|
| 2647 |
relname = makeObjectName(name1, name2, modlabel); |
| 2648 |
|
| 2649 |
/* is there any conflicting relation name? */ |
| 2650 |
ScanKeyInit(&key[0], |
| 2651 |
Anum_pg_class_relname, |
| 2652 |
BTEqualStrategyNumber, F_NAMEEQ, |
| 2653 |
CStringGetDatum(relname)); |
| 2654 |
ScanKeyInit(&key[1], |
| 2655 |
Anum_pg_class_relnamespace, |
| 2656 |
BTEqualStrategyNumber, F_OIDEQ, |
| 2657 |
ObjectIdGetDatum(namespaceid)); |
| 2658 |
|
| 2659 |
scan = systable_beginscan(pgclassrel, ClassNameNspIndexId, |
| 2660 |
true /* indexOK */ , |
| 2661 |
&SnapshotDirty, |
| 2662 |
2, key); |
| 2663 |
|
| 2664 |
collides = HeapTupleIsValid(systable_getnext(scan)); |
| 2665 |
|
| 2666 |
systable_endscan(scan); |
| 2667 |
|
| 2668 |
/* break out of loop if no conflict */ |
| 2669 |
if (!collides) |
| 2670 |
{ |
| 2671 |
if (!isconstraint || |
| 2672 |
!ConstraintNameExists(relname, namespaceid)) |
| 2673 |
break; |
| 2674 |
} |
| 2675 |
|
| 2676 |
/* found a conflict, so try a new name component */ |
| 2677 |
pfree(relname); |
| 2678 |
snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass); |
| 2679 |
} |
| 2680 |
|
| 2681 |
table_close(pgclassrel, AccessShareLock); |
| 2682 |
|
| 2683 |
return relname; |
| 2684 |
} |
| 2685 |
|
| 2686 |
/* |
| 2687 |
* Select the name to be used for an index. |
| 2688 |
* |
| 2689 |
* The argument list is pretty ad-hoc :-( |
| 2690 |
*/ |
| 2691 |
static char * |
| 2692 |
ChooseIndexName(const char *tabname, Oid namespaceId, |
| 2693 |
const List *colnames, const List *exclusionOpNames, |
| 2694 |
bool primary, bool isconstraint) |
| 2695 |
{ |
| 2696 |
char *indexname; |
| 2697 |
|
| 2698 |
if (primary) |
| 2699 |
{ |
| 2700 |
/* the primary key's name does not depend on the specific column(s) */ |
| 2701 |
indexname = ChooseRelationName(tabname, |
| 2702 |
NULL, |
| 2703 |
"pkey", |
| 2704 |
namespaceId, |
| 2705 |
true); |
| 2706 |
} |
| 2707 |
else if (exclusionOpNames != NIL) |
| 2708 |
{ |
| 2709 |
indexname = ChooseRelationName(tabname, |
| 2710 |
ChooseIndexNameAddition(colnames), |
| 2711 |
"excl", |
| 2712 |
namespaceId, |
| 2713 |
true); |
| 2714 |
} |
| 2715 |
else if (isconstraint) |
| 2716 |
{ |
| 2717 |
indexname = ChooseRelationName(tabname, |
| 2718 |
ChooseIndexNameAddition(colnames), |
| 2719 |
"key", |
| 2720 |
namespaceId, |
| 2721 |
true); |
| 2722 |
} |
| 2723 |
else |
| 2724 |
{ |
| 2725 |
indexname = ChooseRelationName(tabname, |
| 2726 |
ChooseIndexNameAddition(colnames), |
| 2727 |
"idx", |
| 2728 |
namespaceId, |
| 2729 |
false); |
| 2730 |
} |
| 2731 |
|
| 2732 |
return indexname; |
| 2733 |
} |
| 2734 |
|
| 2735 |
/* |
| 2736 |
* Generate "name2" for a new index given the list of column names for it |
| 2737 |
* (as produced by ChooseIndexColumnNames). This will be passed to |
| 2738 |
* ChooseRelationName along with the parent table name and a suitable label. |
| 2739 |
* |
| 2740 |
* We know that less than NAMEDATALEN characters will actually be used, |
| 2741 |
* so we can truncate the result once we've generated that many. |
| 2742 |
* |
| 2743 |
* XXX See also ChooseForeignKeyConstraintNameAddition and |
| 2744 |
* ChooseExtendedStatisticNameAddition. |
| 2745 |
*/ |
| 2746 |
static char * |
| 2747 |
ChooseIndexNameAddition(const List *colnames) |
| 2748 |
{ |
| 2749 |
char buf[NAMEDATALEN * 2]; |
| 2750 |
int buflen = 0; |
| 2751 |
ListCell *lc; |
| 2752 |
|
| 2753 |
buf[0] = '\0'; |
| 2754 |
foreach(lc, colnames) |
| 2755 |
{ |
| 2756 |
const char *name = (const char *) lfirst(lc); |
| 2757 |
|
| 2758 |
if (buflen > 0) |
| 2759 |
buf[buflen++] = '_'; /* insert _ between names */ |
| 2760 |
|
| 2761 |
/* |
| 2762 |
* At this point we have buflen <= NAMEDATALEN. name should be less |
| 2763 |
* than NAMEDATALEN already, but use strlcpy for paranoia. |
| 2764 |
*/ |
| 2765 |
strlcpy(buf + buflen, name, NAMEDATALEN); |
| 2766 |
buflen += strlen(buf + buflen); |
| 2767 |
if (buflen >= NAMEDATALEN) |
| 2768 |
break; |
| 2769 |
} |
| 2770 |
return pstrdup(buf); |
| 2771 |
} |
| 2772 |
|
| 2773 |
/* |
| 2774 |
* Select the actual names to be used for the columns of an index, given the |
| 2775 |
* list of IndexElems for the columns. This is mostly about ensuring the |
| 2776 |
* names are unique so we don't get a conflicting-attribute-names error. |
| 2777 |
* |
| 2778 |
* Returns a List of plain strings (char *, not String nodes). |
| 2779 |
*/ |
| 2780 |
static List * |
| 2781 |
ChooseIndexColumnNames(const List *indexElems) |
| 2782 |
{ |
| 2783 |
List *result = NIL; |
| 2784 |
ListCell *lc; |
| 2785 |
|
| 2786 |
foreach(lc, indexElems) |
| 2787 |
{ |
| 2788 |
IndexElem *ielem = (IndexElem *) lfirst(lc); |
| 2789 |
const char *origname; |
| 2790 |
const char *curname; |
| 2791 |
int i; |
| 2792 |
char buf[NAMEDATALEN]; |
| 2793 |
|
| 2794 |
/* Get the preliminary name from the IndexElem */ |
| 2795 |
if (ielem->indexcolname) |
| 2796 |
origname = ielem->indexcolname; /* caller-specified name */ |
| 2797 |
else if (ielem->name) |
| 2798 |
origname = ielem->name; /* simple column reference */ |
| 2799 |
else |
| 2800 |
origname = "expr"; /* default name for expression */ |
| 2801 |
|
| 2802 |
/* If it conflicts with any previous column, tweak it */ |
| 2803 |
curname = origname; |
| 2804 |
for (i = 1;; i++) |
| 2805 |
{ |
| 2806 |
ListCell *lc2; |
| 2807 |
char nbuf[32]; |
| 2808 |
int nlen; |
| 2809 |
|
| 2810 |
foreach(lc2, result) |
| 2811 |
{ |
| 2812 |
if (strcmp(curname, (char *) lfirst(lc2)) == 0) |
| 2813 |
break; |
| 2814 |
} |
| 2815 |
if (lc2 == NULL) |
| 2816 |
break; /* found nonconflicting name */ |
| 2817 |
|
| 2818 |
sprintf(nbuf, "%d", i); |
| 2819 |
|
| 2820 |
/* Ensure generated names are shorter than NAMEDATALEN */ |
| 2821 |
nlen = pg_mbcliplen(origname, strlen(origname), |
| 2822 |
NAMEDATALEN - 1 - strlen(nbuf)); |
| 2823 |
memcpy(buf, origname, nlen); |
| 2824 |
strcpy(buf + nlen, nbuf); |
| 2825 |
curname = buf; |
| 2826 |
} |
| 2827 |
|
| 2828 |
/* And attach to the result list */ |
| 2829 |
result = lappend(result, pstrdup(curname)); |
| 2830 |
} |
| 2831 |
return result; |
| 2832 |
} |
| 2833 |
|
| 2834 |
/* |
| 2835 |
* ExecReindex |
| 2836 |
* |
| 2837 |
* Primary entry point for manual REINDEX commands. This is mainly a |
| 2838 |
* preparation wrapper for the real operations that will happen in |
| 2839 |
* each subroutine of REINDEX. |
| 2840 |
*/ |
| 2841 |
void |
| 2842 |
ExecReindex(ParseState *pstate, const ReindexStmt *stmt, bool isTopLevel) |
| 2843 |
{ |
| 2844 |
ReindexParams params = {0}; |
| 2845 |
ListCell *lc; |
| 2846 |
bool concurrently = false; |
| 2847 |
bool verbose = false; |
| 2848 |
char *tablespacename = NULL; |
| 2849 |
|
| 2850 |
/* Parse option list */ |
| 2851 |
foreach(lc, stmt->params) |
| 2852 |
{ |
| 2853 |
DefElem *opt = (DefElem *) lfirst(lc); |
| 2854 |
|
| 2855 |
if (strcmp(opt->defname, "verbose") == 0) |
| 2856 |
verbose = defGetBoolean(opt); |
| 2857 |
else if (strcmp(opt->defname, "concurrently") == 0) |
| 2858 |
concurrently = defGetBoolean(opt); |
| 2859 |
else if (strcmp(opt->defname, "tablespace") == 0) |
| 2860 |
tablespacename = defGetString(opt); |
| 2861 |
else |
| 2862 |
ereport(ERROR, |
| 2863 |
(errcode(ERRCODE_SYNTAX_ERROR), |
| 2864 |
errmsg("unrecognized %s option \"%s\"", |
| 2865 |
"REINDEX", opt->defname), |
| 2866 |
parser_errposition(pstate, opt->location))); |
| 2867 |
} |
| 2868 |
|
| 2869 |
if (concurrently) |
| 2870 |
PreventInTransactionBlock(isTopLevel, |
| 2871 |
"REINDEX CONCURRENTLY"); |
| 2872 |
|
| 2873 |
params.options = |
| 2874 |
(verbose ? REINDEXOPT_VERBOSE : 0) | |
| 2875 |
(concurrently ? REINDEXOPT_CONCURRENTLY : 0); |
| 2876 |
|
| 2877 |
/* |
| 2878 |
* Assign the tablespace OID to move indexes to, with InvalidOid to do |
| 2879 |
* nothing. |
| 2880 |
*/ |
| 2881 |
if (tablespacename != NULL) |
| 2882 |
{ |
| 2883 |
params.tablespaceOid = get_tablespace_oid(tablespacename, false); |
| 2884 |
|
| 2885 |
/* Check permissions except when moving to database's default */ |
| 2886 |
if (OidIsValid(params.tablespaceOid) && |
| 2887 |
params.tablespaceOid != MyDatabaseTableSpace) |
| 2888 |
{ |
| 2889 |
AclResult aclresult; |
| 2890 |
|
| 2891 |
aclresult = object_aclcheck(TableSpaceRelationId, params.tablespaceOid, |
| 2892 |
GetUserId(), ACL_CREATE); |
| 2893 |
if (aclresult != ACLCHECK_OK) |
| 2894 |
aclcheck_error(aclresult, OBJECT_TABLESPACE, |
| 2895 |
get_tablespace_name(params.tablespaceOid)); |
| 2896 |
} |
| 2897 |
} |
| 2898 |
else |
| 2899 |
params.tablespaceOid = InvalidOid; |
| 2900 |
|
| 2901 |
switch (stmt->kind) |
| 2902 |
{ |
| 2903 |
case REINDEX_OBJECT_INDEX: |
| 2904 |
ReindexIndex(stmt, ¶ms, isTopLevel); |
| 2905 |
break; |
| 2906 |
case REINDEX_OBJECT_TABLE: |
| 2907 |
ReindexTable(stmt, ¶ms, isTopLevel); |
| 2908 |
break; |
| 2909 |
case REINDEX_OBJECT_SCHEMA: |
| 2910 |
case REINDEX_OBJECT_SYSTEM: |
| 2911 |
case REINDEX_OBJECT_DATABASE: |
| 2912 |
|
| 2913 |
/* |
| 2914 |
* This cannot run inside a user transaction block; if we were |
| 2915 |
* inside a transaction, then its commit- and |
| 2916 |
* start-transaction-command calls would not have the intended |
| 2917 |
* effect! |
| 2918 |
*/ |
| 2919 |
PreventInTransactionBlock(isTopLevel, |
| 2920 |
(stmt->kind == REINDEX_OBJECT_SCHEMA) ? "REINDEX SCHEMA" : |
| 2921 |
(stmt->kind == REINDEX_OBJECT_SYSTEM) ? "REINDEX SYSTEM" : |
| 2922 |
"REINDEX DATABASE"); |
| 2923 |
ReindexMultipleTables(stmt, ¶ms); |
| 2924 |
break; |
| 2925 |
default: |
| 2926 |
elog(ERROR, "unrecognized object type: %d", |
| 2927 |
(int) stmt->kind); |
| 2928 |
break; |
| 2929 |
} |
| 2930 |
} |
| 2931 |
|
| 2932 |
/* |
| 2933 |
* ReindexIndex |
| 2934 |
* Recreate a specific index. |
| 2935 |
*/ |
| 2936 |
static void |
| 2937 |
ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel) |
| 2938 |
{ |
| 2939 |
const RangeVar *indexRelation = stmt->relation; |
| 2940 |
struct ReindexIndexCallbackState state; |
| 2941 |
Oid indOid; |
| 2942 |
char persistence; |
| 2943 |
char relkind; |
| 2944 |
|
| 2945 |
/* |
| 2946 |
* Find and lock index, and check permissions on table; use callback to |
| 2947 |
* obtain lock on table first, to avoid deadlock hazard. The lock level |
| 2948 |
* used here must match the index lock obtained in reindex_index(). |
| 2949 |
* |
| 2950 |
* If it's a temporary index, we will perform a non-concurrent reindex, |
| 2951 |
* even if CONCURRENTLY was requested. In that case, reindex_index() will |
| 2952 |
* upgrade the lock, but that's OK, because other sessions can't hold |
| 2953 |
* locks on our temporary table. |
| 2954 |
*/ |
| 2955 |
state.params = *params; |
| 2956 |
state.locked_table_oid = InvalidOid; |
| 2957 |
indOid = RangeVarGetRelidExtended(indexRelation, |
| 2958 |
(params->options & REINDEXOPT_CONCURRENTLY) != 0 ? |
| 2959 |
ShareUpdateExclusiveLock : AccessExclusiveLock, |
| 2960 |
0, |
| 2961 |
RangeVarCallbackForReindexIndex, |
| 2962 |
&state); |
| 2963 |
|
| 2964 |
/* |
| 2965 |
* Obtain the current persistence and kind of the existing index. We |
| 2966 |
* already hold a lock on the index. |
| 2967 |
*/ |
| 2968 |
persistence = get_rel_persistence(indOid); |
| 2969 |
relkind = get_rel_relkind(indOid); |
| 2970 |
|
| 2971 |
if (relkind == RELKIND_PARTITIONED_INDEX) |
| 2972 |
ReindexPartitions(stmt, indOid, params, isTopLevel); |
| 2973 |
else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 && |
| 2974 |
persistence != RELPERSISTENCE_TEMP) |
| 2975 |
ReindexRelationConcurrently(stmt, indOid, params); |
| 2976 |
else |
| 2977 |
{ |
| 2978 |
ReindexParams newparams = *params; |
| 2979 |
|
| 2980 |
newparams.options |= REINDEXOPT_REPORT_PROGRESS; |
| 2981 |
reindex_index(stmt, indOid, false, persistence, &newparams); |
| 2982 |
} |
| 2983 |
} |
| 2984 |
|
| 2985 |
/* |
| 2986 |
* Check permissions on table before acquiring relation lock; also lock |
| 2987 |
* the heap before the RangeVarGetRelidExtended takes the index lock, to avoid |
| 2988 |
* deadlocks. |
| 2989 |
*/ |
| 2990 |
static void |
| 2991 |
RangeVarCallbackForReindexIndex(const RangeVar *relation, |
| 2992 |
Oid relId, Oid oldRelId, void *arg) |
| 2993 |
{ |
| 2994 |
char relkind; |
| 2995 |
struct ReindexIndexCallbackState *state = arg; |
| 2996 |
LOCKMODE table_lockmode; |
| 2997 |
Oid table_oid; |
| 2998 |
|
| 2999 |
/* |
| 3000 |
* Lock level here should match table lock in reindex_index() for |
| 3001 |
* non-concurrent case and table locks used by index_concurrently_*() for |
| 3002 |
* concurrent case. |
| 3003 |
*/ |
| 3004 |
table_lockmode = (state->params.options & REINDEXOPT_CONCURRENTLY) != 0 ? |
| 3005 |
ShareUpdateExclusiveLock : ShareLock; |
| 3006 |
|
| 3007 |
/* |
| 3008 |
* If we previously locked some other index's heap, and the name we're |
| 3009 |
* looking up no longer refers to that relation, release the now-useless |
| 3010 |
* lock. |
| 3011 |
*/ |
| 3012 |
if (relId != oldRelId && OidIsValid(oldRelId)) |
| 3013 |
{ |
| 3014 |
UnlockRelationOid(state->locked_table_oid, table_lockmode); |
| 3015 |
state->locked_table_oid = InvalidOid; |
| 3016 |
} |
| 3017 |
|
| 3018 |
/* If the relation does not exist, there's nothing more to do. */ |
| 3019 |
if (!OidIsValid(relId)) |
| 3020 |
return; |
| 3021 |
|
| 3022 |
/* |
| 3023 |
* If the relation does exist, check whether it's an index. But note that |
| 3024 |
* the relation might have been dropped between the time we did the name |
| 3025 |
* lookup and now. In that case, there's nothing to do. |
| 3026 |
*/ |
| 3027 |
relkind = get_rel_relkind(relId); |
| 3028 |
if (!relkind) |
| 3029 |
return; |
| 3030 |
if (relkind != RELKIND_INDEX && |
| 3031 |
relkind != RELKIND_PARTITIONED_INDEX) |
| 3032 |
ereport(ERROR, |
| 3033 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 3034 |
errmsg("\"%s\" is not an index", relation->relname))); |
| 3035 |
|
| 3036 |
/* Check permissions */ |
| 3037 |
table_oid = IndexGetRelation(relId, true); |
| 3038 |
if (OidIsValid(table_oid)) |
| 3039 |
{ |
| 3040 |
AclResult aclresult; |
| 3041 |
|
| 3042 |
aclresult = pg_class_aclcheck(table_oid, GetUserId(), ACL_MAINTAIN); |
| 3043 |
if (aclresult != ACLCHECK_OK) |
| 3044 |
aclcheck_error(aclresult, OBJECT_INDEX, relation->relname); |
| 3045 |
} |
| 3046 |
|
| 3047 |
/* Lock heap before index to avoid deadlock. */ |
| 3048 |
if (relId != oldRelId) |
| 3049 |
{ |
| 3050 |
/* |
| 3051 |
* If the OID isn't valid, it means the index was concurrently |
| 3052 |
* dropped, which is not a problem for us; just return normally. |
| 3053 |
*/ |
| 3054 |
if (OidIsValid(table_oid)) |
| 3055 |
{ |
| 3056 |
LockRelationOid(table_oid, table_lockmode); |
| 3057 |
state->locked_table_oid = table_oid; |
| 3058 |
} |
| 3059 |
} |
| 3060 |
} |
| 3061 |
|
| 3062 |
/* |
| 3063 |
* ReindexTable |
| 3064 |
* Recreate all indexes of a table (and of its toast table, if any) |
| 3065 |
*/ |
| 3066 |
static Oid |
| 3067 |
ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLevel) |
| 3068 |
{ |
| 3069 |
Oid heapOid; |
| 3070 |
bool result; |
| 3071 |
const RangeVar *relation = stmt->relation; |
| 3072 |
|
| 3073 |
/* |
| 3074 |
* The lock level used here should match reindex_relation(). |
| 3075 |
* |
| 3076 |
* If it's a temporary table, we will perform a non-concurrent reindex, |
| 3077 |
* even if CONCURRENTLY was requested. In that case, reindex_relation() |
| 3078 |
* will upgrade the lock, but that's OK, because other sessions can't hold |
| 3079 |
* locks on our temporary table. |
| 3080 |
*/ |
| 3081 |
heapOid = RangeVarGetRelidExtended(relation, |
| 3082 |
(params->options & REINDEXOPT_CONCURRENTLY) != 0 ? |
| 3083 |
ShareUpdateExclusiveLock : ShareLock, |
| 3084 |
0, |
| 3085 |
RangeVarCallbackMaintainsTable, NULL); |
| 3086 |
|
| 3087 |
if (get_rel_relkind(heapOid) == RELKIND_PARTITIONED_TABLE) |
| 3088 |
ReindexPartitions(stmt, heapOid, params, isTopLevel); |
| 3089 |
else if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 && |
| 3090 |
get_rel_persistence(heapOid) != RELPERSISTENCE_TEMP) |
| 3091 |
{ |
| 3092 |
result = ReindexRelationConcurrently(stmt, heapOid, params); |
| 3093 |
|
| 3094 |
if (!result) |
| 3095 |
ereport(NOTICE, |
| 3096 |
(errmsg("table \"%s\" has no indexes that can be reindexed concurrently", |
| 3097 |
relation->relname))); |
| 3098 |
} |
| 3099 |
else |
| 3100 |
{ |
| 3101 |
ReindexParams newparams = *params; |
| 3102 |
|
| 3103 |
newparams.options |= REINDEXOPT_REPORT_PROGRESS; |
| 3104 |
result = reindex_relation(stmt, heapOid, |
| 3105 |
REINDEX_REL_PROCESS_TOAST | |
| 3106 |
REINDEX_REL_CHECK_CONSTRAINTS, |
| 3107 |
&newparams); |
| 3108 |
if (!result) |
| 3109 |
ereport(NOTICE, |
| 3110 |
(errmsg("table \"%s\" has no indexes to reindex", |
| 3111 |
relation->relname))); |
| 3112 |
} |
| 3113 |
|
| 3114 |
return heapOid; |
| 3115 |
} |
| 3116 |
|
| 3117 |
/* |
| 3118 |
* ReindexMultipleTables |
| 3119 |
* Recreate indexes of tables selected by objectName/objectKind. |
| 3120 |
* |
| 3121 |
* To reduce the probability of deadlocks, each table is reindexed in a |
| 3122 |
* separate transaction, so we can release the lock on it right away. |
| 3123 |
* That means this must not be called within a user transaction block! |
| 3124 |
*/ |
| 3125 |
static void |
| 3126 |
ReindexMultipleTables(const ReindexStmt *stmt, const ReindexParams *params) |
| 3127 |
{ |
| 3128 |
|
| 3129 |
Oid objectOid; |
| 3130 |
Relation relationRelation; |
| 3131 |
TableScanDesc scan; |
| 3132 |
ScanKeyData scan_keys[1]; |
| 3133 |
HeapTuple tuple; |
| 3134 |
MemoryContext private_context; |
| 3135 |
MemoryContext old; |
| 3136 |
List *relids = NIL; |
| 3137 |
int num_keys; |
| 3138 |
bool concurrent_warning = false; |
| 3139 |
bool tablespace_warning = false; |
| 3140 |
const char *objectName = stmt->name; |
| 3141 |
const ReindexObjectType objectKind = stmt->kind; |
| 3142 |
|
| 3143 |
Assert(objectKind == REINDEX_OBJECT_SCHEMA || |
| 3144 |
objectKind == REINDEX_OBJECT_SYSTEM || |
| 3145 |
objectKind == REINDEX_OBJECT_DATABASE); |
| 3146 |
|
| 3147 |
/* |
| 3148 |
* This matches the options enforced by the grammar, where the object name |
| 3149 |
* is optional for DATABASE and SYSTEM. |
| 3150 |
*/ |
| 3151 |
Assert(objectName || objectKind != REINDEX_OBJECT_SCHEMA); |
| 3152 |
|
| 3153 |
if (objectKind == REINDEX_OBJECT_SYSTEM && |
| 3154 |
(params->options & REINDEXOPT_CONCURRENTLY) != 0) |
| 3155 |
ereport(ERROR, |
| 3156 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3157 |
errmsg("cannot reindex system catalogs concurrently"))); |
| 3158 |
|
| 3159 |
/* |
| 3160 |
* Get OID of object to reindex, being the database currently being used |
| 3161 |
* by session for a database or for system catalogs, or the schema defined |
| 3162 |
* by caller. At the same time do permission checks that need different |
| 3163 |
* processing depending on the object type. |
| 3164 |
*/ |
| 3165 |
if (objectKind == REINDEX_OBJECT_SCHEMA) |
| 3166 |
{ |
| 3167 |
objectOid = get_namespace_oid(objectName, false); |
| 3168 |
|
| 3169 |
if (!object_ownercheck(NamespaceRelationId, objectOid, GetUserId()) && |
| 3170 |
!has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN)) |
| 3171 |
aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SCHEMA, |
| 3172 |
objectName); |
| 3173 |
} |
| 3174 |
else |
| 3175 |
{ |
| 3176 |
objectOid = MyDatabaseId; |
| 3177 |
|
| 3178 |
if (objectName && strcmp(objectName, get_database_name(objectOid)) != 0) |
| 3179 |
ereport(ERROR, |
| 3180 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3181 |
errmsg("can only reindex the currently open database"))); |
| 3182 |
if (!object_ownercheck(DatabaseRelationId, objectOid, GetUserId()) && |
| 3183 |
!has_privs_of_role(GetUserId(), ROLE_PG_MAINTAIN)) |
| 3184 |
aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_DATABASE, |
| 3185 |
get_database_name(objectOid)); |
| 3186 |
} |
| 3187 |
|
| 3188 |
/* |
| 3189 |
* Create a memory context that will survive forced transaction commits we |
| 3190 |
* do below. Since it is a child of PortalContext, it will go away |
| 3191 |
* eventually even if we suffer an error; there's no need for special |
| 3192 |
* abort cleanup logic. |
| 3193 |
*/ |
| 3194 |
private_context = AllocSetContextCreate(PortalContext, |
| 3195 |
"ReindexMultipleTables", |
| 3196 |
ALLOCSET_SMALL_SIZES); |
| 3197 |
|
| 3198 |
/* |
| 3199 |
* Define the search keys to find the objects to reindex. For a schema, we |
| 3200 |
* select target relations using relnamespace, something not necessary for |
| 3201 |
* a database-wide operation. |
| 3202 |
*/ |
| 3203 |
if (objectKind == REINDEX_OBJECT_SCHEMA) |
| 3204 |
{ |
| 3205 |
num_keys = 1; |
| 3206 |
ScanKeyInit(&scan_keys[0], |
| 3207 |
Anum_pg_class_relnamespace, |
| 3208 |
BTEqualStrategyNumber, F_OIDEQ, |
| 3209 |
ObjectIdGetDatum(objectOid)); |
| 3210 |
} |
| 3211 |
else |
| 3212 |
num_keys = 0; |
| 3213 |
|
| 3214 |
/* |
| 3215 |
* Scan pg_class to build a list of the relations we need to reindex. |
| 3216 |
* |
| 3217 |
* We only consider plain relations and materialized views here (toast |
| 3218 |
* rels will be processed indirectly by reindex_relation). |
| 3219 |
*/ |
| 3220 |
relationRelation = table_open(RelationRelationId, AccessShareLock); |
| 3221 |
scan = table_beginscan_catalog(relationRelation, num_keys, scan_keys); |
| 3222 |
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) |
| 3223 |
{ |
| 3224 |
Form_pg_class classtuple = (Form_pg_class) GETSTRUCT(tuple); |
| 3225 |
Oid relid = classtuple->oid; |
| 3226 |
|
| 3227 |
/* |
| 3228 |
* Only regular tables and matviews can have indexes, so ignore any |
| 3229 |
* other kind of relation. |
| 3230 |
* |
| 3231 |
* Partitioned tables/indexes are skipped but matching leaf partitions |
| 3232 |
* are processed. |
| 3233 |
*/ |
| 3234 |
if (classtuple->relkind != RELKIND_RELATION && |
| 3235 |
classtuple->relkind != RELKIND_MATVIEW) |
| 3236 |
continue; |
| 3237 |
|
| 3238 |
/* Skip temp tables of other backends; we can't reindex them at all */ |
| 3239 |
if (classtuple->relpersistence == RELPERSISTENCE_TEMP && |
| 3240 |
!isTempNamespace(classtuple->relnamespace)) |
| 3241 |
continue; |
| 3242 |
|
| 3243 |
/* |
| 3244 |
* Check user/system classification. SYSTEM processes all the |
| 3245 |
* catalogs, and DATABASE processes everything that's not a catalog. |
| 3246 |
*/ |
| 3247 |
if (objectKind == REINDEX_OBJECT_SYSTEM && |
| 3248 |
!IsCatalogRelationOid(relid)) |
| 3249 |
continue; |
| 3250 |
else if (objectKind == REINDEX_OBJECT_DATABASE && |
| 3251 |
IsCatalogRelationOid(relid)) |
| 3252 |
continue; |
| 3253 |
|
| 3254 |
/* |
| 3255 |
* We already checked privileges on the database or schema, but we |
| 3256 |
* further restrict reindexing shared catalogs to roles with the |
| 3257 |
* MAINTAIN privilege on the relation. |
| 3258 |
*/ |
| 3259 |
if (classtuple->relisshared && |
| 3260 |
pg_class_aclcheck(relid, GetUserId(), ACL_MAINTAIN) != ACLCHECK_OK) |
| 3261 |
continue; |
| 3262 |
|
| 3263 |
/* |
| 3264 |
* Skip system tables, since index_create() would reject indexing them |
| 3265 |
* concurrently (and it would likely fail if we tried). |
| 3266 |
*/ |
| 3267 |
if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 && |
| 3268 |
IsCatalogRelationOid(relid)) |
| 3269 |
{ |
| 3270 |
if (!concurrent_warning) |
| 3271 |
ereport(WARNING, |
| 3272 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3273 |
errmsg("cannot reindex system catalogs concurrently, skipping all"))); |
| 3274 |
concurrent_warning = true; |
| 3275 |
continue; |
| 3276 |
} |
| 3277 |
|
| 3278 |
/* |
| 3279 |
* If a new tablespace is set, check if this relation has to be |
| 3280 |
* skipped. |
| 3281 |
*/ |
| 3282 |
if (OidIsValid(params->tablespaceOid)) |
| 3283 |
{ |
| 3284 |
bool skip_rel = false; |
| 3285 |
|
| 3286 |
/* |
| 3287 |
* Mapped relations cannot be moved to different tablespaces (in |
| 3288 |
* particular this eliminates all shared catalogs.). |
| 3289 |
*/ |
| 3290 |
if (RELKIND_HAS_STORAGE(classtuple->relkind) && |
| 3291 |
!RelFileNumberIsValid(classtuple->relfilenode)) |
| 3292 |
skip_rel = true; |
| 3293 |
|
| 3294 |
/* |
| 3295 |
* A system relation is always skipped, even with |
| 3296 |
* allow_system_table_mods enabled. |
| 3297 |
*/ |
| 3298 |
if (IsSystemClass(relid, classtuple)) |
| 3299 |
skip_rel = true; |
| 3300 |
|
| 3301 |
if (skip_rel) |
| 3302 |
{ |
| 3303 |
if (!tablespace_warning) |
| 3304 |
ereport(WARNING, |
| 3305 |
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), |
| 3306 |
errmsg("cannot move system relations, skipping all"))); |
| 3307 |
tablespace_warning = true; |
| 3308 |
continue; |
| 3309 |
} |
| 3310 |
} |
| 3311 |
|
| 3312 |
/* Save the list of relation OIDs in private context */ |
| 3313 |
old = MemoryContextSwitchTo(private_context); |
| 3314 |
|
| 3315 |
/* |
| 3316 |
* We always want to reindex pg_class first if it's selected to be |
| 3317 |
* reindexed. This ensures that if there is any corruption in |
| 3318 |
* pg_class' indexes, they will be fixed before we process any other |
| 3319 |
* tables. This is critical because reindexing itself will try to |
| 3320 |
* update pg_class. |
| 3321 |
*/ |
| 3322 |
if (relid == RelationRelationId) |
| 3323 |
relids = lcons_oid(relid, relids); |
| 3324 |
else |
| 3325 |
relids = lappend_oid(relids, relid); |
| 3326 |
|
| 3327 |
MemoryContextSwitchTo(old); |
| 3328 |
} |
| 3329 |
table_endscan(scan); |
| 3330 |
table_close(relationRelation, AccessShareLock); |
| 3331 |
|
| 3332 |
/* |
| 3333 |
* Process each relation listed in a separate transaction. Note that this |
| 3334 |
* commits and then starts a new transaction immediately. |
| 3335 |
*/ |
| 3336 |
ReindexMultipleInternal(stmt, relids, params); |
| 3337 |
|
| 3338 |
MemoryContextDelete(private_context); |
| 3339 |
} |
| 3340 |
|
| 3341 |
/* |
| 3342 |
* Error callback specific to ReindexPartitions(). |
| 3343 |
*/ |
| 3344 |
static void |
| 3345 |
reindex_error_callback(void *arg) |
| 3346 |
{ |
| 3347 |
ReindexErrorInfo *errinfo = (ReindexErrorInfo *) arg; |
| 3348 |
|
| 3349 |
Assert(RELKIND_HAS_PARTITIONS(errinfo->relkind)); |
| 3350 |
|
| 3351 |
if (errinfo->relkind == RELKIND_PARTITIONED_TABLE) |
| 3352 |
errcontext("while reindexing partitioned table \"%s.%s\"", |
| 3353 |
errinfo->relnamespace, errinfo->relname); |
| 3354 |
else if (errinfo->relkind == RELKIND_PARTITIONED_INDEX) |
| 3355 |
errcontext("while reindexing partitioned index \"%s.%s\"", |
| 3356 |
errinfo->relnamespace, errinfo->relname); |
| 3357 |
} |
| 3358 |
|
| 3359 |
/* |
| 3360 |
* ReindexPartitions |
| 3361 |
* |
| 3362 |
* Reindex a set of partitions, per the partitioned index or table given |
| 3363 |
* by the caller. |
| 3364 |
*/ |
| 3365 |
static void |
| 3366 |
ReindexPartitions(const ReindexStmt *stmt, Oid relid, const ReindexParams *params, bool isTopLevel) |
| 3367 |
{ |
| 3368 |
List *partitions = NIL; |
| 3369 |
char relkind = get_rel_relkind(relid); |
| 3370 |
char *relname = get_rel_name(relid); |
| 3371 |
char *relnamespace = get_namespace_name(get_rel_namespace(relid)); |
| 3372 |
MemoryContext reindex_context; |
| 3373 |
List *inhoids; |
| 3374 |
ListCell *lc; |
| 3375 |
ErrorContextCallback errcallback; |
| 3376 |
ReindexErrorInfo errinfo; |
| 3377 |
|
| 3378 |
Assert(RELKIND_HAS_PARTITIONS(relkind)); |
| 3379 |
|
| 3380 |
/* |
| 3381 |
* Check if this runs in a transaction block, with an error callback to |
| 3382 |
* provide more context under which a problem happens. |
| 3383 |
*/ |
| 3384 |
errinfo.relname = pstrdup(relname); |
| 3385 |
errinfo.relnamespace = pstrdup(relnamespace); |
| 3386 |
errinfo.relkind = relkind; |
| 3387 |
errcallback.callback = reindex_error_callback; |
| 3388 |
errcallback.arg = &errinfo; |
| 3389 |
errcallback.previous = error_context_stack; |
| 3390 |
error_context_stack = &errcallback; |
| 3391 |
|
| 3392 |
PreventInTransactionBlock(isTopLevel, |
| 3393 |
relkind == RELKIND_PARTITIONED_TABLE ? |
| 3394 |
"REINDEX TABLE" : "REINDEX INDEX"); |
| 3395 |
|
| 3396 |
/* Pop the error context stack */ |
| 3397 |
error_context_stack = errcallback.previous; |
| 3398 |
|
| 3399 |
/* |
| 3400 |
* Create special memory context for cross-transaction storage. |
| 3401 |
* |
| 3402 |
* Since it is a child of PortalContext, it will go away eventually even |
| 3403 |
* if we suffer an error so there is no need for special abort cleanup |
| 3404 |
* logic. |
| 3405 |
*/ |
| 3406 |
reindex_context = AllocSetContextCreate(PortalContext, "Reindex", |
| 3407 |
ALLOCSET_DEFAULT_SIZES); |
| 3408 |
|
| 3409 |
/* ShareLock is enough to prevent schema modifications */ |
| 3410 |
inhoids = find_all_inheritors(relid, ShareLock, NULL); |
| 3411 |
|
| 3412 |
/* |
| 3413 |
* The list of relations to reindex are the physical partitions of the |
| 3414 |
* tree so discard any partitioned table or index. |
| 3415 |
*/ |
| 3416 |
foreach(lc, inhoids) |
| 3417 |
{ |
| 3418 |
Oid partoid = lfirst_oid(lc); |
| 3419 |
char partkind = get_rel_relkind(partoid); |
| 3420 |
MemoryContext old_context; |
| 3421 |
|
| 3422 |
/* |
| 3423 |
* This discards partitioned tables, partitioned indexes and foreign |
| 3424 |
* tables. |
| 3425 |
*/ |
| 3426 |
if (!RELKIND_HAS_STORAGE(partkind)) |
| 3427 |
continue; |
| 3428 |
|
| 3429 |
Assert(partkind == RELKIND_INDEX || |
| 3430 |
partkind == RELKIND_RELATION); |
| 3431 |
|
| 3432 |
/* Save partition OID */ |
| 3433 |
old_context = MemoryContextSwitchTo(reindex_context); |
| 3434 |
partitions = lappend_oid(partitions, partoid); |
| 3435 |
MemoryContextSwitchTo(old_context); |
| 3436 |
} |
| 3437 |
|
| 3438 |
/* |
| 3439 |
* Process each partition listed in a separate transaction. Note that |
| 3440 |
* this commits and then starts a new transaction immediately. |
| 3441 |
*/ |
| 3442 |
ReindexMultipleInternal(stmt, partitions, params); |
| 3443 |
|
| 3444 |
/* |
| 3445 |
* Clean up working storage --- note we must do this after |
| 3446 |
* StartTransactionCommand, else we might be trying to delete the active |
| 3447 |
* context! |
| 3448 |
*/ |
| 3449 |
MemoryContextDelete(reindex_context); |
| 3450 |
} |
| 3451 |
|
| 3452 |
/* |
| 3453 |
* ReindexMultipleInternal |
| 3454 |
* |
| 3455 |
* Reindex a list of relations, each one being processed in its own |
| 3456 |
* transaction. This commits the existing transaction immediately, |
| 3457 |
* and starts a new transaction when finished. |
| 3458 |
*/ |
| 3459 |
static void |
| 3460 |
ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const ReindexParams *params) |
| 3461 |
{ |
| 3462 |
ListCell *l; |
| 3463 |
|
| 3464 |
PopActiveSnapshot(); |
| 3465 |
CommitTransactionCommand(); |
| 3466 |
|
| 3467 |
foreach(l, relids) |
| 3468 |
{ |
| 3469 |
Oid relid = lfirst_oid(l); |
| 3470 |
char relkind; |
| 3471 |
char relpersistence; |
| 3472 |
|
| 3473 |
StartTransactionCommand(); |
| 3474 |
|
| 3475 |
/* functions in indexes may want a snapshot set */ |
| 3476 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 3477 |
|
| 3478 |
/* check if the relation still exists */ |
| 3479 |
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid))) |
| 3480 |
{ |
| 3481 |
PopActiveSnapshot(); |
| 3482 |
CommitTransactionCommand(); |
| 3483 |
continue; |
| 3484 |
} |
| 3485 |
|
| 3486 |
/* |
| 3487 |
* Check permissions except when moving to database's default if a new |
| 3488 |
* tablespace is chosen. Note that this check also happens in |
| 3489 |
* ExecReindex(), but we do an extra check here as this runs across |
| 3490 |
* multiple transactions. |
| 3491 |
*/ |
| 3492 |
if (OidIsValid(params->tablespaceOid) && |
| 3493 |
params->tablespaceOid != MyDatabaseTableSpace) |
| 3494 |
{ |
| 3495 |
AclResult aclresult; |
| 3496 |
|
| 3497 |
aclresult = object_aclcheck(TableSpaceRelationId, params->tablespaceOid, |
| 3498 |
GetUserId(), ACL_CREATE); |
| 3499 |
if (aclresult != ACLCHECK_OK) |
| 3500 |
aclcheck_error(aclresult, OBJECT_TABLESPACE, |
| 3501 |
get_tablespace_name(params->tablespaceOid)); |
| 3502 |
} |
| 3503 |
|
| 3504 |
relkind = get_rel_relkind(relid); |
| 3505 |
relpersistence = get_rel_persistence(relid); |
| 3506 |
|
| 3507 |
/* |
| 3508 |
* Partitioned tables and indexes can never be processed directly, and |
| 3509 |
* a list of their leaves should be built first. |
| 3510 |
*/ |
| 3511 |
Assert(!RELKIND_HAS_PARTITIONS(relkind)); |
| 3512 |
|
| 3513 |
if ((params->options & REINDEXOPT_CONCURRENTLY) != 0 && |
| 3514 |
relpersistence != RELPERSISTENCE_TEMP) |
| 3515 |
{ |
| 3516 |
ReindexParams newparams = *params; |
| 3517 |
|
| 3518 |
newparams.options |= REINDEXOPT_MISSING_OK; |
| 3519 |
(void) ReindexRelationConcurrently(stmt, relid, &newparams); |
| 3520 |
if (ActiveSnapshotSet()) |
| 3521 |
PopActiveSnapshot(); |
| 3522 |
/* ReindexRelationConcurrently() does the verbose output */ |
| 3523 |
} |
| 3524 |
else if (relkind == RELKIND_INDEX) |
| 3525 |
{ |
| 3526 |
ReindexParams newparams = *params; |
| 3527 |
|
| 3528 |
newparams.options |= |
| 3529 |
REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK; |
| 3530 |
reindex_index(stmt, relid, false, relpersistence, &newparams); |
| 3531 |
PopActiveSnapshot(); |
| 3532 |
/* reindex_index() does the verbose output */ |
| 3533 |
} |
| 3534 |
else |
| 3535 |
{ |
| 3536 |
bool result; |
| 3537 |
ReindexParams newparams = *params; |
| 3538 |
|
| 3539 |
newparams.options |= |
| 3540 |
REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK; |
| 3541 |
result = reindex_relation(stmt, relid, |
| 3542 |
REINDEX_REL_PROCESS_TOAST | |
| 3543 |
REINDEX_REL_CHECK_CONSTRAINTS, |
| 3544 |
&newparams); |
| 3545 |
|
| 3546 |
if (result && (params->options & REINDEXOPT_VERBOSE) != 0) |
| 3547 |
ereport(INFO, |
| 3548 |
(errmsg("table \"%s.%s\" was reindexed", |
| 3549 |
get_namespace_name(get_rel_namespace(relid)), |
| 3550 |
get_rel_name(relid)))); |
| 3551 |
|
| 3552 |
PopActiveSnapshot(); |
| 3553 |
} |
| 3554 |
|
| 3555 |
CommitTransactionCommand(); |
| 3556 |
} |
| 3557 |
|
| 3558 |
StartTransactionCommand(); |
| 3559 |
} |
| 3560 |
|
| 3561 |
|
| 3562 |
/* |
| 3563 |
* ReindexRelationConcurrently - process REINDEX CONCURRENTLY for given |
| 3564 |
* relation OID |
| 3565 |
* |
| 3566 |
* 'relationOid' can either belong to an index, a table or a materialized |
| 3567 |
* view. For tables and materialized views, all its indexes will be rebuilt, |
| 3568 |
* excluding invalid indexes and any indexes used in exclusion constraints, |
| 3569 |
* but including its associated toast table indexes. For indexes, the index |
| 3570 |
* itself will be rebuilt. |
| 3571 |
* |
| 3572 |
* The locks taken on parent tables and involved indexes are kept until the |
| 3573 |
* transaction is committed, at which point a session lock is taken on each |
| 3574 |
* relation. Both of these protect against concurrent schema changes. |
| 3575 |
* |
| 3576 |
* Returns true if any indexes have been rebuilt (including toast table's |
| 3577 |
* indexes, when relevant), otherwise returns false. |
| 3578 |
* |
| 3579 |
* NOTE: This cannot be used on temporary relations. A concurrent build would |
| 3580 |
* cause issues with ON COMMIT actions triggered by the transactions of the |
| 3581 |
* concurrent build. Temporary relations are not subject to concurrent |
| 3582 |
* concerns, so there's no need for the more complicated concurrent build, |
| 3583 |
* anyway, and a non-concurrent reindex is more efficient. |
| 3584 |
*/ |
| 3585 |
static bool |
| 3586 |
ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const ReindexParams *params) |
| 3587 |
{ |
| 3588 |
typedef struct ReindexIndexInfo |
| 3589 |
{ |
| 3590 |
Oid indexId; |
| 3591 |
Oid tableId; |
| 3592 |
Oid amId; |
| 3593 |
bool safe; /* for set_indexsafe_procflags */ |
| 3594 |
} ReindexIndexInfo; |
| 3595 |
List *heapRelationIds = NIL; |
| 3596 |
List *indexIds = NIL; |
| 3597 |
List *newIndexIds = NIL; |
| 3598 |
List *relationLocks = NIL; |
| 3599 |
List *lockTags = NIL; |
| 3600 |
ListCell *lc, |
| 3601 |
*lc2; |
| 3602 |
MemoryContext private_context; |
| 3603 |
MemoryContext oldcontext; |
| 3604 |
char relkind; |
| 3605 |
char *relationName = NULL; |
| 3606 |
char *relationNamespace = NULL; |
| 3607 |
PGRUsage ru0; |
| 3608 |
const int progress_index[] = { |
| 3609 |
PROGRESS_CREATEIDX_COMMAND, |
| 3610 |
PROGRESS_CREATEIDX_PHASE, |
| 3611 |
PROGRESS_CREATEIDX_INDEX_OID, |
| 3612 |
PROGRESS_CREATEIDX_ACCESS_METHOD_OID |
| 3613 |
}; |
| 3614 |
int64 progress_vals[4]; |
| 3615 |
|
| 3616 |
/* |
| 3617 |
* Create a memory context that will survive forced transaction commits we |
| 3618 |
* do below. Since it is a child of PortalContext, it will go away |
| 3619 |
* eventually even if we suffer an error; there's no need for special |
| 3620 |
* abort cleanup logic. |
| 3621 |
*/ |
| 3622 |
private_context = AllocSetContextCreate(PortalContext, |
| 3623 |
"ReindexConcurrent", |
| 3624 |
ALLOCSET_SMALL_SIZES); |
| 3625 |
|
| 3626 |
if ((params->options & REINDEXOPT_VERBOSE) != 0) |
| 3627 |
{ |
| 3628 |
/* Save data needed by REINDEX VERBOSE in private context */ |
| 3629 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3630 |
|
| 3631 |
relationName = get_rel_name(relationOid); |
| 3632 |
relationNamespace = get_namespace_name(get_rel_namespace(relationOid)); |
| 3633 |
|
| 3634 |
pg_rusage_init(&ru0); |
| 3635 |
|
| 3636 |
MemoryContextSwitchTo(oldcontext); |
| 3637 |
} |
| 3638 |
|
| 3639 |
relkind = get_rel_relkind(relationOid); |
| 3640 |
|
| 3641 |
/* |
| 3642 |
* Extract the list of indexes that are going to be rebuilt based on the |
| 3643 |
* relation Oid given by caller. |
| 3644 |
*/ |
| 3645 |
switch (relkind) |
| 3646 |
{ |
| 3647 |
case RELKIND_RELATION: |
| 3648 |
case RELKIND_MATVIEW: |
| 3649 |
case RELKIND_TOASTVALUE: |
| 3650 |
{ |
| 3651 |
/* |
| 3652 |
* In the case of a relation, find all its indexes including |
| 3653 |
* toast indexes. |
| 3654 |
*/ |
| 3655 |
Relation heapRelation; |
| 3656 |
|
| 3657 |
/* Save the list of relation OIDs in private context */ |
| 3658 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3659 |
|
| 3660 |
/* Track this relation for session locks */ |
| 3661 |
heapRelationIds = lappend_oid(heapRelationIds, relationOid); |
| 3662 |
|
| 3663 |
MemoryContextSwitchTo(oldcontext); |
| 3664 |
|
| 3665 |
if (IsCatalogRelationOid(relationOid)) |
| 3666 |
ereport(ERROR, |
| 3667 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3668 |
errmsg("cannot reindex system catalogs concurrently"))); |
| 3669 |
|
| 3670 |
/* Open relation to get its indexes */ |
| 3671 |
if ((params->options & REINDEXOPT_MISSING_OK) != 0) |
| 3672 |
{ |
| 3673 |
heapRelation = try_table_open(relationOid, |
| 3674 |
ShareUpdateExclusiveLock); |
| 3675 |
/* leave if relation does not exist */ |
| 3676 |
if (!heapRelation) |
| 3677 |
break; |
| 3678 |
} |
| 3679 |
else |
| 3680 |
heapRelation = table_open(relationOid, |
| 3681 |
ShareUpdateExclusiveLock); |
| 3682 |
|
| 3683 |
if (OidIsValid(params->tablespaceOid) && |
| 3684 |
IsSystemRelation(heapRelation)) |
| 3685 |
ereport(ERROR, |
| 3686 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3687 |
errmsg("cannot move system relation \"%s\"", |
| 3688 |
RelationGetRelationName(heapRelation)))); |
| 3689 |
|
| 3690 |
/* Add all the valid indexes of relation to list */ |
| 3691 |
foreach(lc, RelationGetIndexList(heapRelation)) |
| 3692 |
{ |
| 3693 |
Oid cellOid = lfirst_oid(lc); |
| 3694 |
Relation indexRelation = index_open(cellOid, |
| 3695 |
ShareUpdateExclusiveLock); |
| 3696 |
|
| 3697 |
if (!indexRelation->rd_index->indisvalid) |
| 3698 |
ereport(WARNING, |
| 3699 |
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
| 3700 |
errmsg("skipping reindex of invalid index \"%s.%s\"", |
| 3701 |
get_namespace_name(get_rel_namespace(cellOid)), |
| 3702 |
get_rel_name(cellOid)), |
| 3703 |
errhint("Use DROP INDEX or REINDEX INDEX."))); |
| 3704 |
else if (indexRelation->rd_index->indisexclusion) |
| 3705 |
ereport(WARNING, |
| 3706 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3707 |
errmsg("cannot reindex exclusion constraint index \"%s.%s\" concurrently, skipping", |
| 3708 |
get_namespace_name(get_rel_namespace(cellOid)), |
| 3709 |
get_rel_name(cellOid)))); |
| 3710 |
else |
| 3711 |
{ |
| 3712 |
ReindexIndexInfo *idx; |
| 3713 |
|
| 3714 |
/* Save the list of relation OIDs in private context */ |
| 3715 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3716 |
|
| 3717 |
idx = palloc_object(ReindexIndexInfo); |
| 3718 |
idx->indexId = cellOid; |
| 3719 |
/* other fields set later */ |
| 3720 |
|
| 3721 |
indexIds = lappend(indexIds, idx); |
| 3722 |
|
| 3723 |
MemoryContextSwitchTo(oldcontext); |
| 3724 |
} |
| 3725 |
|
| 3726 |
index_close(indexRelation, NoLock); |
| 3727 |
} |
| 3728 |
|
| 3729 |
/* Also add the toast indexes */ |
| 3730 |
if (OidIsValid(heapRelation->rd_rel->reltoastrelid)) |
| 3731 |
{ |
| 3732 |
Oid toastOid = heapRelation->rd_rel->reltoastrelid; |
| 3733 |
Relation toastRelation = table_open(toastOid, |
| 3734 |
ShareUpdateExclusiveLock); |
| 3735 |
|
| 3736 |
/* Save the list of relation OIDs in private context */ |
| 3737 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3738 |
|
| 3739 |
/* Track this relation for session locks */ |
| 3740 |
heapRelationIds = lappend_oid(heapRelationIds, toastOid); |
| 3741 |
|
| 3742 |
MemoryContextSwitchTo(oldcontext); |
| 3743 |
|
| 3744 |
foreach(lc2, RelationGetIndexList(toastRelation)) |
| 3745 |
{ |
| 3746 |
Oid cellOid = lfirst_oid(lc2); |
| 3747 |
Relation indexRelation = index_open(cellOid, |
| 3748 |
ShareUpdateExclusiveLock); |
| 3749 |
|
| 3750 |
if (!indexRelation->rd_index->indisvalid) |
| 3751 |
ereport(WARNING, |
| 3752 |
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
| 3753 |
errmsg("skipping reindex of invalid index \"%s.%s\"", |
| 3754 |
get_namespace_name(get_rel_namespace(cellOid)), |
| 3755 |
get_rel_name(cellOid)), |
| 3756 |
errhint("Use DROP INDEX or REINDEX INDEX."))); |
| 3757 |
else |
| 3758 |
{ |
| 3759 |
ReindexIndexInfo *idx; |
| 3760 |
|
| 3761 |
/* |
| 3762 |
* Save the list of relation OIDs in private |
| 3763 |
* context |
| 3764 |
*/ |
| 3765 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3766 |
|
| 3767 |
idx = palloc_object(ReindexIndexInfo); |
| 3768 |
idx->indexId = cellOid; |
| 3769 |
indexIds = lappend(indexIds, idx); |
| 3770 |
/* other fields set later */ |
| 3771 |
|
| 3772 |
MemoryContextSwitchTo(oldcontext); |
| 3773 |
} |
| 3774 |
|
| 3775 |
index_close(indexRelation, NoLock); |
| 3776 |
} |
| 3777 |
|
| 3778 |
table_close(toastRelation, NoLock); |
| 3779 |
} |
| 3780 |
|
| 3781 |
table_close(heapRelation, NoLock); |
| 3782 |
break; |
| 3783 |
} |
| 3784 |
case RELKIND_INDEX: |
| 3785 |
{ |
| 3786 |
Oid heapId = IndexGetRelation(relationOid, |
| 3787 |
(params->options & REINDEXOPT_MISSING_OK) != 0); |
| 3788 |
Relation heapRelation; |
| 3789 |
ReindexIndexInfo *idx; |
| 3790 |
|
| 3791 |
/* if relation is missing, leave */ |
| 3792 |
if (!OidIsValid(heapId)) |
| 3793 |
break; |
| 3794 |
|
| 3795 |
if (IsCatalogRelationOid(heapId)) |
| 3796 |
ereport(ERROR, |
| 3797 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3798 |
errmsg("cannot reindex system catalogs concurrently"))); |
| 3799 |
|
| 3800 |
/* |
| 3801 |
* Don't allow reindex for an invalid index on TOAST table, as |
| 3802 |
* if rebuilt it would not be possible to drop it. Match |
| 3803 |
* error message in reindex_index(). |
| 3804 |
*/ |
| 3805 |
if (IsToastNamespace(get_rel_namespace(relationOid)) && |
| 3806 |
!get_index_isvalid(relationOid)) |
| 3807 |
ereport(ERROR, |
| 3808 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3809 |
errmsg("cannot reindex invalid index on TOAST table"))); |
| 3810 |
|
| 3811 |
/* |
| 3812 |
* Check if parent relation can be locked and if it exists, |
| 3813 |
* this needs to be done at this stage as the list of indexes |
| 3814 |
* to rebuild is not complete yet, and REINDEXOPT_MISSING_OK |
| 3815 |
* should not be used once all the session locks are taken. |
| 3816 |
*/ |
| 3817 |
if ((params->options & REINDEXOPT_MISSING_OK) != 0) |
| 3818 |
{ |
| 3819 |
heapRelation = try_table_open(heapId, |
| 3820 |
ShareUpdateExclusiveLock); |
| 3821 |
/* leave if relation does not exist */ |
| 3822 |
if (!heapRelation) |
| 3823 |
break; |
| 3824 |
} |
| 3825 |
else |
| 3826 |
heapRelation = table_open(heapId, |
| 3827 |
ShareUpdateExclusiveLock); |
| 3828 |
|
| 3829 |
if (OidIsValid(params->tablespaceOid) && |
| 3830 |
IsSystemRelation(heapRelation)) |
| 3831 |
ereport(ERROR, |
| 3832 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3833 |
errmsg("cannot move system relation \"%s\"", |
| 3834 |
get_rel_name(relationOid)))); |
| 3835 |
|
| 3836 |
table_close(heapRelation, NoLock); |
| 3837 |
|
| 3838 |
/* Save the list of relation OIDs in private context */ |
| 3839 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3840 |
|
| 3841 |
/* Track the heap relation of this index for session locks */ |
| 3842 |
heapRelationIds = list_make1_oid(heapId); |
| 3843 |
|
| 3844 |
/* |
| 3845 |
* Save the list of relation OIDs in private context. Note |
| 3846 |
* that invalid indexes are allowed here. |
| 3847 |
*/ |
| 3848 |
idx = palloc_object(ReindexIndexInfo); |
| 3849 |
idx->indexId = relationOid; |
| 3850 |
indexIds = lappend(indexIds, idx); |
| 3851 |
/* other fields set later */ |
| 3852 |
|
| 3853 |
MemoryContextSwitchTo(oldcontext); |
| 3854 |
break; |
| 3855 |
} |
| 3856 |
|
| 3857 |
case RELKIND_PARTITIONED_TABLE: |
| 3858 |
case RELKIND_PARTITIONED_INDEX: |
| 3859 |
default: |
| 3860 |
/* Return error if type of relation is not supported */ |
| 3861 |
ereport(ERROR, |
| 3862 |
(errcode(ERRCODE_WRONG_OBJECT_TYPE), |
| 3863 |
errmsg("cannot reindex this type of relation concurrently"))); |
| 3864 |
break; |
| 3865 |
} |
| 3866 |
|
| 3867 |
/* |
| 3868 |
* Definitely no indexes, so leave. Any checks based on |
| 3869 |
* REINDEXOPT_MISSING_OK should be done only while the list of indexes to |
| 3870 |
* work on is built as the session locks taken before this transaction |
| 3871 |
* commits will make sure that they cannot be dropped by a concurrent |
| 3872 |
* session until this operation completes. |
| 3873 |
*/ |
| 3874 |
if (indexIds == NIL) |
| 3875 |
return false; |
| 3876 |
|
| 3877 |
/* It's not a shared catalog, so refuse to move it to shared tablespace */ |
| 3878 |
if (params->tablespaceOid == GLOBALTABLESPACE_OID) |
| 3879 |
ereport(ERROR, |
| 3880 |
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 3881 |
errmsg("cannot move non-shared relation to tablespace \"%s\"", |
| 3882 |
get_tablespace_name(params->tablespaceOid)))); |
| 3883 |
|
| 3884 |
Assert(heapRelationIds != NIL); |
| 3885 |
|
| 3886 |
/*----- |
| 3887 |
* Now we have all the indexes we want to process in indexIds. |
| 3888 |
* |
| 3889 |
* The phases now are: |
| 3890 |
* |
| 3891 |
* 1. create new indexes in the catalog |
| 3892 |
* 2. build new indexes |
| 3893 |
* 3. let new indexes catch up with tuples inserted in the meantime |
| 3894 |
* 4. swap index names |
| 3895 |
* 5. mark old indexes as dead |
| 3896 |
* 6. drop old indexes |
| 3897 |
* |
| 3898 |
* We process each phase for all indexes before moving to the next phase, |
| 3899 |
* for efficiency. |
| 3900 |
*/ |
| 3901 |
|
| 3902 |
/* |
| 3903 |
* Phase 1 of REINDEX CONCURRENTLY |
| 3904 |
* |
| 3905 |
* Create a new index with the same properties as the old one, but it is |
| 3906 |
* only registered in catalogs and will be built later. Then get session |
| 3907 |
* locks on all involved tables. See analogous code in DefineIndex() for |
| 3908 |
* more detailed comments. |
| 3909 |
*/ |
| 3910 |
|
| 3911 |
foreach(lc, indexIds) |
| 3912 |
{ |
| 3913 |
char *concurrentName; |
| 3914 |
ReindexIndexInfo *idx = lfirst(lc); |
| 3915 |
ReindexIndexInfo *newidx; |
| 3916 |
Oid newIndexId; |
| 3917 |
Relation indexRel; |
| 3918 |
Relation heapRel; |
| 3919 |
Oid save_userid; |
| 3920 |
int save_sec_context; |
| 3921 |
int save_nestlevel; |
| 3922 |
Relation newIndexRel; |
| 3923 |
LockRelId *lockrelid; |
| 3924 |
Oid tablespaceid; |
| 3925 |
|
| 3926 |
indexRel = index_open(idx->indexId, ShareUpdateExclusiveLock); |
| 3927 |
heapRel = table_open(indexRel->rd_index->indrelid, |
| 3928 |
ShareUpdateExclusiveLock); |
| 3929 |
|
| 3930 |
/* |
| 3931 |
* Switch to the table owner's userid, so that any index functions are |
| 3932 |
* run as that user. Also lock down security-restricted operations |
| 3933 |
* and arrange to make GUC variable changes local to this command. |
| 3934 |
*/ |
| 3935 |
GetUserIdAndSecContext(&save_userid, &save_sec_context); |
| 3936 |
SetUserIdAndSecContext(heapRel->rd_rel->relowner, |
| 3937 |
save_sec_context | SECURITY_RESTRICTED_OPERATION); |
| 3938 |
save_nestlevel = NewGUCNestLevel(); |
| 3939 |
RestrictSearchPath(); |
| 3940 |
|
| 3941 |
/* determine safety of this index for set_indexsafe_procflags */ |
| 3942 |
idx->safe = (RelationGetIndexExpressions(indexRel) == NIL && |
| 3943 |
RelationGetIndexPredicate(indexRel) == NIL); |
| 3944 |
|
| 3945 |
#ifdef USE_INJECTION_POINTS |
| 3946 |
if (idx->safe) |
| 3947 |
INJECTION_POINT("reindex-conc-index-safe", NULL); |
| 3948 |
else |
| 3949 |
INJECTION_POINT("reindex-conc-index-not-safe", NULL); |
| 3950 |
#endif |
| 3951 |
|
| 3952 |
idx->tableId = RelationGetRelid(heapRel); |
| 3953 |
idx->amId = indexRel->rd_rel->relam; |
| 3954 |
|
| 3955 |
/* This function shouldn't be called for temporary relations. */ |
| 3956 |
if (indexRel->rd_rel->relpersistence == RELPERSISTENCE_TEMP) |
| 3957 |
elog(ERROR, "cannot reindex a temporary table concurrently"); |
| 3958 |
|
| 3959 |
pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, idx->tableId); |
| 3960 |
|
| 3961 |
progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY; |
| 3962 |
progress_vals[1] = 0; /* initializing */ |
| 3963 |
progress_vals[2] = idx->indexId; |
| 3964 |
progress_vals[3] = idx->amId; |
| 3965 |
pgstat_progress_update_multi_param(4, progress_index, progress_vals); |
| 3966 |
|
| 3967 |
/* Choose a temporary relation name for the new index */ |
| 3968 |
concurrentName = ChooseRelationName(get_rel_name(idx->indexId), |
| 3969 |
NULL, |
| 3970 |
"ccnew", |
| 3971 |
get_rel_namespace(indexRel->rd_index->indrelid), |
| 3972 |
false); |
| 3973 |
|
| 3974 |
/* Choose the new tablespace, indexes of toast tables are not moved */ |
| 3975 |
if (OidIsValid(params->tablespaceOid) && |
| 3976 |
heapRel->rd_rel->relkind != RELKIND_TOASTVALUE) |
| 3977 |
tablespaceid = params->tablespaceOid; |
| 3978 |
else |
| 3979 |
tablespaceid = indexRel->rd_rel->reltablespace; |
| 3980 |
|
| 3981 |
/* Create new index definition based on given index */ |
| 3982 |
newIndexId = index_concurrently_create_copy(heapRel, |
| 3983 |
idx->indexId, |
| 3984 |
tablespaceid, |
| 3985 |
concurrentName); |
| 3986 |
|
| 3987 |
/* |
| 3988 |
* Now open the relation of the new index, a session-level lock is |
| 3989 |
* also needed on it. |
| 3990 |
*/ |
| 3991 |
newIndexRel = index_open(newIndexId, ShareUpdateExclusiveLock); |
| 3992 |
|
| 3993 |
/* |
| 3994 |
* Save the list of OIDs and locks in private context |
| 3995 |
*/ |
| 3996 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 3997 |
|
| 3998 |
newidx = palloc_object(ReindexIndexInfo); |
| 3999 |
newidx->indexId = newIndexId; |
| 4000 |
newidx->safe = idx->safe; |
| 4001 |
newidx->tableId = idx->tableId; |
| 4002 |
newidx->amId = idx->amId; |
| 4003 |
|
| 4004 |
newIndexIds = lappend(newIndexIds, newidx); |
| 4005 |
|
| 4006 |
/* |
| 4007 |
* Save lockrelid to protect each relation from drop then close |
| 4008 |
* relations. The lockrelid on parent relation is not taken here to |
| 4009 |
* avoid multiple locks taken on the same relation, instead we rely on |
| 4010 |
* parentRelationIds built earlier. |
| 4011 |
*/ |
| 4012 |
lockrelid = palloc_object(LockRelId); |
| 4013 |
*lockrelid = indexRel->rd_lockInfo.lockRelId; |
| 4014 |
relationLocks = lappend(relationLocks, lockrelid); |
| 4015 |
lockrelid = palloc_object(LockRelId); |
| 4016 |
*lockrelid = newIndexRel->rd_lockInfo.lockRelId; |
| 4017 |
relationLocks = lappend(relationLocks, lockrelid); |
| 4018 |
|
| 4019 |
MemoryContextSwitchTo(oldcontext); |
| 4020 |
|
| 4021 |
index_close(indexRel, NoLock); |
| 4022 |
index_close(newIndexRel, NoLock); |
| 4023 |
|
| 4024 |
/* Roll back any GUC changes executed by index functions */ |
| 4025 |
AtEOXact_GUC(false, save_nestlevel); |
| 4026 |
|
| 4027 |
/* Restore userid and security context */ |
| 4028 |
SetUserIdAndSecContext(save_userid, save_sec_context); |
| 4029 |
|
| 4030 |
table_close(heapRel, NoLock); |
| 4031 |
|
| 4032 |
/* |
| 4033 |
* If a statement is available, telling that this comes from a REINDEX |
| 4034 |
* command, collect the new index for event triggers. |
| 4035 |
*/ |
| 4036 |
if (stmt) |
| 4037 |
{ |
| 4038 |
ObjectAddress address; |
| 4039 |
|
| 4040 |
ObjectAddressSet(address, RelationRelationId, newIndexId); |
| 4041 |
EventTriggerCollectSimpleCommand(address, |
| 4042 |
InvalidObjectAddress, |
| 4043 |
(Node *) stmt); |
| 4044 |
} |
| 4045 |
} |
| 4046 |
|
| 4047 |
/* |
| 4048 |
* Save the heap lock for following visibility checks with other backends |
| 4049 |
* might conflict with this session. |
| 4050 |
*/ |
| 4051 |
foreach(lc, heapRelationIds) |
| 4052 |
{ |
| 4053 |
Relation heapRelation = table_open(lfirst_oid(lc), ShareUpdateExclusiveLock); |
| 4054 |
LockRelId *lockrelid; |
| 4055 |
LOCKTAG *heaplocktag; |
| 4056 |
|
| 4057 |
/* Save the list of locks in private context */ |
| 4058 |
oldcontext = MemoryContextSwitchTo(private_context); |
| 4059 |
|
| 4060 |
/* Add lockrelid of heap relation to the list of locked relations */ |
| 4061 |
lockrelid = palloc_object(LockRelId); |
| 4062 |
*lockrelid = heapRelation->rd_lockInfo.lockRelId; |
| 4063 |
relationLocks = lappend(relationLocks, lockrelid); |
| 4064 |
|
| 4065 |
heaplocktag = palloc_object(LOCKTAG); |
| 4066 |
|
| 4067 |
/* Save the LOCKTAG for this parent relation for the wait phase */ |
| 4068 |
SET_LOCKTAG_RELATION(*heaplocktag, lockrelid->dbId, lockrelid->relId); |
| 4069 |
lockTags = lappend(lockTags, heaplocktag); |
| 4070 |
|
| 4071 |
MemoryContextSwitchTo(oldcontext); |
| 4072 |
|
| 4073 |
/* Close heap relation */ |
| 4074 |
table_close(heapRelation, NoLock); |
| 4075 |
} |
| 4076 |
|
| 4077 |
/* Get a session-level lock on each table. */ |
| 4078 |
foreach(lc, relationLocks) |
| 4079 |
{ |
| 4080 |
LockRelId *lockrelid = (LockRelId *) lfirst(lc); |
| 4081 |
|
| 4082 |
LockRelationIdForSession(lockrelid, ShareUpdateExclusiveLock); |
| 4083 |
} |
| 4084 |
|
| 4085 |
PopActiveSnapshot(); |
| 4086 |
CommitTransactionCommand(); |
| 4087 |
StartTransactionCommand(); |
| 4088 |
|
| 4089 |
/* |
| 4090 |
* Because we don't take a snapshot in this transaction, there's no need |
| 4091 |
* to set the PROC_IN_SAFE_IC flag here. |
| 4092 |
*/ |
| 4093 |
|
| 4094 |
/* |
| 4095 |
* Phase 2 of REINDEX CONCURRENTLY |
| 4096 |
* |
| 4097 |
* Build the new indexes in a separate transaction for each index to avoid |
| 4098 |
* having open transactions for an unnecessary long time. But before |
| 4099 |
* doing that, wait until no running transactions could have the table of |
| 4100 |
* the index open with the old list of indexes. See "phase 2" in |
| 4101 |
* DefineIndex() for more details. |
| 4102 |
*/ |
| 4103 |
|
| 4104 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 4105 |
PROGRESS_CREATEIDX_PHASE_WAIT_1); |
| 4106 |
WaitForLockersMultiple(lockTags, ShareLock, true); |
| 4107 |
CommitTransactionCommand(); |
| 4108 |
|
| 4109 |
foreach(lc, newIndexIds) |
| 4110 |
{ |
| 4111 |
ReindexIndexInfo *newidx = lfirst(lc); |
| 4112 |
|
| 4113 |
/* Start new transaction for this index's concurrent build */ |
| 4114 |
StartTransactionCommand(); |
| 4115 |
|
| 4116 |
/* |
| 4117 |
* Check for user-requested abort. This is inside a transaction so as |
| 4118 |
* xact.c does not issue a useless WARNING, and ensures that |
| 4119 |
* session-level locks are cleaned up on abort. |
| 4120 |
*/ |
| 4121 |
CHECK_FOR_INTERRUPTS(); |
| 4122 |
|
| 4123 |
/* Tell concurrent indexing to ignore us, if index qualifies */ |
| 4124 |
if (newidx->safe) |
| 4125 |
set_indexsafe_procflags(); |
| 4126 |
|
| 4127 |
/* Set ActiveSnapshot since functions in the indexes may need it */ |
| 4128 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 4129 |
|
| 4130 |
/* |
| 4131 |
* Update progress for the index to build, with the correct parent |
| 4132 |
* table involved. |
| 4133 |
*/ |
| 4134 |
pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, newidx->tableId); |
| 4135 |
progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY; |
| 4136 |
progress_vals[1] = PROGRESS_CREATEIDX_PHASE_BUILD; |
| 4137 |
progress_vals[2] = newidx->indexId; |
| 4138 |
progress_vals[3] = newidx->amId; |
| 4139 |
pgstat_progress_update_multi_param(4, progress_index, progress_vals); |
| 4140 |
|
| 4141 |
/* Perform concurrent build of new index */ |
| 4142 |
index_concurrently_build(newidx->tableId, newidx->indexId); |
| 4143 |
|
| 4144 |
PopActiveSnapshot(); |
| 4145 |
CommitTransactionCommand(); |
| 4146 |
} |
| 4147 |
|
| 4148 |
INJECTION_POINT("reindex-conc-index-built", NULL); |
| 4149 |
|
| 4150 |
StartTransactionCommand(); |
| 4151 |
|
| 4152 |
/* |
| 4153 |
* Because we don't take a snapshot or Xid in this transaction, there's no |
| 4154 |
* need to set the PROC_IN_SAFE_IC flag here. |
| 4155 |
*/ |
| 4156 |
|
| 4157 |
/* |
| 4158 |
* Phase 3 of REINDEX CONCURRENTLY |
| 4159 |
* |
| 4160 |
* During this phase the old indexes catch up with any new tuples that |
| 4161 |
* were created during the previous phase. See "phase 3" in DefineIndex() |
| 4162 |
* for more details. |
| 4163 |
*/ |
| 4164 |
|
| 4165 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 4166 |
PROGRESS_CREATEIDX_PHASE_WAIT_2); |
| 4167 |
WaitForLockersMultiple(lockTags, ShareLock, true); |
| 4168 |
CommitTransactionCommand(); |
| 4169 |
|
| 4170 |
foreach(lc, newIndexIds) |
| 4171 |
{ |
| 4172 |
ReindexIndexInfo *newidx = lfirst(lc); |
| 4173 |
TransactionId limitXmin; |
| 4174 |
Snapshot snapshot; |
| 4175 |
|
| 4176 |
StartTransactionCommand(); |
| 4177 |
|
| 4178 |
/* |
| 4179 |
* Check for user-requested abort. This is inside a transaction so as |
| 4180 |
* xact.c does not issue a useless WARNING, and ensures that |
| 4181 |
* session-level locks are cleaned up on abort. |
| 4182 |
*/ |
| 4183 |
CHECK_FOR_INTERRUPTS(); |
| 4184 |
|
| 4185 |
/* Tell concurrent indexing to ignore us, if index qualifies */ |
| 4186 |
if (newidx->safe) |
| 4187 |
set_indexsafe_procflags(); |
| 4188 |
|
| 4189 |
/* |
| 4190 |
* Take the "reference snapshot" that will be used by validate_index() |
| 4191 |
* to filter candidate tuples. |
| 4192 |
*/ |
| 4193 |
snapshot = RegisterSnapshot(GetTransactionSnapshot()); |
| 4194 |
PushActiveSnapshot(snapshot); |
| 4195 |
|
| 4196 |
/* |
| 4197 |
* Update progress for the index to build, with the correct parent |
| 4198 |
* table involved. |
| 4199 |
*/ |
| 4200 |
pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, newidx->tableId); |
| 4201 |
progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY; |
| 4202 |
progress_vals[1] = PROGRESS_CREATEIDX_PHASE_VALIDATE_IDXSCAN; |
| 4203 |
progress_vals[2] = newidx->indexId; |
| 4204 |
progress_vals[3] = newidx->amId; |
| 4205 |
pgstat_progress_update_multi_param(4, progress_index, progress_vals); |
| 4206 |
|
| 4207 |
validate_index(newidx->tableId, newidx->indexId, snapshot); |
| 4208 |
|
| 4209 |
/* |
| 4210 |
* We can now do away with our active snapshot, we still need to save |
| 4211 |
* the xmin limit to wait for older snapshots. |
| 4212 |
*/ |
| 4213 |
limitXmin = snapshot->xmin; |
| 4214 |
|
| 4215 |
PopActiveSnapshot(); |
| 4216 |
UnregisterSnapshot(snapshot); |
| 4217 |
|
| 4218 |
/* |
| 4219 |
* To ensure no deadlocks, we must commit and start yet another |
| 4220 |
* transaction, and do our wait before any snapshot has been taken in |
| 4221 |
* it. |
| 4222 |
*/ |
| 4223 |
CommitTransactionCommand(); |
| 4224 |
StartTransactionCommand(); |
| 4225 |
|
| 4226 |
/* |
| 4227 |
* The index is now valid in the sense that it contains all currently |
| 4228 |
* interesting tuples. But since it might not contain tuples deleted |
| 4229 |
* just before the reference snap was taken, we have to wait out any |
| 4230 |
* transactions that might have older snapshots. |
| 4231 |
* |
| 4232 |
* Because we don't take a snapshot or Xid in this transaction, |
| 4233 |
* there's no need to set the PROC_IN_SAFE_IC flag here. |
| 4234 |
*/ |
| 4235 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 4236 |
PROGRESS_CREATEIDX_PHASE_WAIT_3); |
| 4237 |
WaitForOlderSnapshots(limitXmin, true); |
| 4238 |
|
| 4239 |
CommitTransactionCommand(); |
| 4240 |
} |
| 4241 |
|
| 4242 |
/* |
| 4243 |
* Phase 4 of REINDEX CONCURRENTLY |
| 4244 |
* |
| 4245 |
* Now that the new indexes have been validated, swap each new index with |
| 4246 |
* its corresponding old index. |
| 4247 |
* |
| 4248 |
* We mark the new indexes as valid and the old indexes as not valid at |
| 4249 |
* the same time to make sure we only get constraint violations from the |
| 4250 |
* indexes with the correct names. |
| 4251 |
*/ |
| 4252 |
|
| 4253 |
StartTransactionCommand(); |
| 4254 |
|
| 4255 |
/* |
| 4256 |
* Because this transaction only does catalog manipulations and doesn't do |
| 4257 |
* any index operations, we can set the PROC_IN_SAFE_IC flag here |
| 4258 |
* unconditionally. |
| 4259 |
*/ |
| 4260 |
set_indexsafe_procflags(); |
| 4261 |
|
| 4262 |
forboth(lc, indexIds, lc2, newIndexIds) |
| 4263 |
{ |
| 4264 |
ReindexIndexInfo *oldidx = lfirst(lc); |
| 4265 |
ReindexIndexInfo *newidx = lfirst(lc2); |
| 4266 |
char *oldName; |
| 4267 |
|
| 4268 |
/* |
| 4269 |
* Check for user-requested abort. This is inside a transaction so as |
| 4270 |
* xact.c does not issue a useless WARNING, and ensures that |
| 4271 |
* session-level locks are cleaned up on abort. |
| 4272 |
*/ |
| 4273 |
CHECK_FOR_INTERRUPTS(); |
| 4274 |
|
| 4275 |
/* Choose a relation name for old index */ |
| 4276 |
oldName = ChooseRelationName(get_rel_name(oldidx->indexId), |
| 4277 |
NULL, |
| 4278 |
"ccold", |
| 4279 |
get_rel_namespace(oldidx->tableId), |
| 4280 |
false); |
| 4281 |
|
| 4282 |
/* |
| 4283 |
* Swapping the indexes might involve TOAST table access, so ensure we |
| 4284 |
* have a valid snapshot. |
| 4285 |
*/ |
| 4286 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 4287 |
|
| 4288 |
/* |
| 4289 |
* Swap old index with the new one. This also marks the new one as |
| 4290 |
* valid and the old one as not valid. |
| 4291 |
*/ |
| 4292 |
index_concurrently_swap(newidx->indexId, oldidx->indexId, oldName); |
| 4293 |
|
| 4294 |
PopActiveSnapshot(); |
| 4295 |
|
| 4296 |
/* |
| 4297 |
* Invalidate the relcache for the table, so that after this commit |
| 4298 |
* all sessions will refresh any cached plans that might reference the |
| 4299 |
* index. |
| 4300 |
*/ |
| 4301 |
CacheInvalidateRelcacheByRelid(oldidx->tableId); |
| 4302 |
|
| 4303 |
/* |
| 4304 |
* CCI here so that subsequent iterations see the oldName in the |
| 4305 |
* catalog and can choose a nonconflicting name for their oldName. |
| 4306 |
* Otherwise, this could lead to conflicts if a table has two indexes |
| 4307 |
* whose names are equal for the first NAMEDATALEN-minus-a-few |
| 4308 |
* characters. |
| 4309 |
*/ |
| 4310 |
CommandCounterIncrement(); |
| 4311 |
} |
| 4312 |
|
| 4313 |
/* Commit this transaction and make index swaps visible */ |
| 4314 |
CommitTransactionCommand(); |
| 4315 |
StartTransactionCommand(); |
| 4316 |
|
| 4317 |
/* |
| 4318 |
* While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no |
| 4319 |
* real need for that, because we only acquire an Xid after the wait is |
| 4320 |
* done, and that lasts for a very short period. |
| 4321 |
*/ |
| 4322 |
|
| 4323 |
/* |
| 4324 |
* Phase 5 of REINDEX CONCURRENTLY |
| 4325 |
* |
| 4326 |
* Mark the old indexes as dead. First we must wait until no running |
| 4327 |
* transaction could be using the index for a query. See also |
| 4328 |
* index_drop() for more details. |
| 4329 |
*/ |
| 4330 |
|
| 4331 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 4332 |
PROGRESS_CREATEIDX_PHASE_WAIT_4); |
| 4333 |
WaitForLockersMultiple(lockTags, AccessExclusiveLock, true); |
| 4334 |
|
| 4335 |
foreach(lc, indexIds) |
| 4336 |
{ |
| 4337 |
ReindexIndexInfo *oldidx = lfirst(lc); |
| 4338 |
|
| 4339 |
/* |
| 4340 |
* Check for user-requested abort. This is inside a transaction so as |
| 4341 |
* xact.c does not issue a useless WARNING, and ensures that |
| 4342 |
* session-level locks are cleaned up on abort. |
| 4343 |
*/ |
| 4344 |
CHECK_FOR_INTERRUPTS(); |
| 4345 |
|
| 4346 |
/* |
| 4347 |
* Updating pg_index might involve TOAST table access, so ensure we |
| 4348 |
* have a valid snapshot. |
| 4349 |
*/ |
| 4350 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 4351 |
|
| 4352 |
index_concurrently_set_dead(oldidx->tableId, oldidx->indexId); |
| 4353 |
|
| 4354 |
PopActiveSnapshot(); |
| 4355 |
} |
| 4356 |
|
| 4357 |
/* Commit this transaction to make the updates visible. */ |
| 4358 |
CommitTransactionCommand(); |
| 4359 |
StartTransactionCommand(); |
| 4360 |
|
| 4361 |
/* |
| 4362 |
* While we could set PROC_IN_SAFE_IC if all indexes qualified, there's no |
| 4363 |
* real need for that, because we only acquire an Xid after the wait is |
| 4364 |
* done, and that lasts for a very short period. |
| 4365 |
*/ |
| 4366 |
|
| 4367 |
/* |
| 4368 |
* Phase 6 of REINDEX CONCURRENTLY |
| 4369 |
* |
| 4370 |
* Drop the old indexes. |
| 4371 |
*/ |
| 4372 |
|
| 4373 |
pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE, |
| 4374 |
PROGRESS_CREATEIDX_PHASE_WAIT_5); |
| 4375 |
WaitForLockersMultiple(lockTags, AccessExclusiveLock, true); |
| 4376 |
|
| 4377 |
PushActiveSnapshot(GetTransactionSnapshot()); |
| 4378 |
|
| 4379 |
{ |
| 4380 |
ObjectAddresses *objects = new_object_addresses(); |
| 4381 |
|
| 4382 |
foreach(lc, indexIds) |
| 4383 |
{ |
| 4384 |
ReindexIndexInfo *idx = lfirst(lc); |
| 4385 |
ObjectAddress object; |
| 4386 |
|
| 4387 |
object.classId = RelationRelationId; |
| 4388 |
object.objectId = idx->indexId; |
| 4389 |
object.objectSubId = 0; |
| 4390 |
|
| 4391 |
add_exact_object_address(&object, objects); |
| 4392 |
} |
| 4393 |
|
| 4394 |
/* |
| 4395 |
* Use PERFORM_DELETION_CONCURRENT_LOCK so that index_drop() uses the |
| 4396 |
* right lock level. |
| 4397 |
*/ |
| 4398 |
performMultipleDeletions(objects, DROP_RESTRICT, |
| 4399 |
PERFORM_DELETION_CONCURRENT_LOCK | PERFORM_DELETION_INTERNAL); |
| 4400 |
} |
| 4401 |
|
| 4402 |
PopActiveSnapshot(); |
| 4403 |
CommitTransactionCommand(); |
| 4404 |
|
| 4405 |
/* |
| 4406 |
* Finally, release the session-level lock on the table. |
| 4407 |
*/ |
| 4408 |
foreach(lc, relationLocks) |
| 4409 |
{ |
| 4410 |
LockRelId *lockrelid = (LockRelId *) lfirst(lc); |
| 4411 |
|
| 4412 |
UnlockRelationIdForSession(lockrelid, ShareUpdateExclusiveLock); |
| 4413 |
} |
| 4414 |
|
| 4415 |
/* Start a new transaction to finish process properly */ |
| 4416 |
StartTransactionCommand(); |
| 4417 |
|
| 4418 |
/* Log what we did */ |
| 4419 |
if ((params->options & REINDEXOPT_VERBOSE) != 0) |
| 4420 |
{ |
| 4421 |
if (relkind == RELKIND_INDEX) |
| 4422 |
ereport(INFO, |
| 4423 |
(errmsg("index \"%s.%s\" was reindexed", |
| 4424 |
relationNamespace, relationName), |
| 4425 |
errdetail("%s.", |
| 4426 |
pg_rusage_show(&ru0)))); |
| 4427 |
else |
| 4428 |
{ |
| 4429 |
foreach(lc, newIndexIds) |
| 4430 |
{ |
| 4431 |
ReindexIndexInfo *idx = lfirst(lc); |
| 4432 |
Oid indOid = idx->indexId; |
| 4433 |
|
| 4434 |
ereport(INFO, |
| 4435 |
(errmsg("index \"%s.%s\" was reindexed", |
| 4436 |
get_namespace_name(get_rel_namespace(indOid)), |
| 4437 |
get_rel_name(indOid)))); |
| 4438 |
/* Don't show rusage here, since it's not per index. */ |
| 4439 |
} |
| 4440 |
|
| 4441 |
ereport(INFO, |
| 4442 |
(errmsg("table \"%s.%s\" was reindexed", |
| 4443 |
relationNamespace, relationName), |
| 4444 |
errdetail("%s.", |
| 4445 |
pg_rusage_show(&ru0)))); |
| 4446 |
} |
| 4447 |
} |
| 4448 |
|
| 4449 |
MemoryContextDelete(private_context); |
| 4450 |
|
| 4451 |
pgstat_progress_end_command(); |
| 4452 |
|
| 4453 |
return true; |
| 4454 |
} |
| 4455 |
|
| 4456 |
/* |
| 4457 |
* Insert or delete an appropriate pg_inherits tuple to make the given index |
| 4458 |
* be a partition of the indicated parent index. |
| 4459 |
* |
| 4460 |
* This also corrects the pg_depend information for the affected index. |
| 4461 |
*/ |
| 4462 |
void |
| 4463 |
IndexSetParentIndex(Relation partitionIdx, Oid parentOid) |
| 4464 |
{ |
| 4465 |
Relation pg_inherits; |
| 4466 |
ScanKeyData key[2]; |
| 4467 |
SysScanDesc scan; |
| 4468 |
Oid partRelid = RelationGetRelid(partitionIdx); |
| 4469 |
HeapTuple tuple; |
| 4470 |
bool fix_dependencies; |
| 4471 |
|
| 4472 |
/* Make sure this is an index */ |
| 4473 |
Assert(partitionIdx->rd_rel->relkind == RELKIND_INDEX || |
| 4474 |
partitionIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX); |
| 4475 |
|
| 4476 |
/* |
| 4477 |
* Scan pg_inherits for rows linking our index to some parent. |
| 4478 |
*/ |
| 4479 |
pg_inherits = relation_open(InheritsRelationId, RowExclusiveLock); |
| 4480 |
ScanKeyInit(&key[0], |
| 4481 |
Anum_pg_inherits_inhrelid, |
| 4482 |
BTEqualStrategyNumber, F_OIDEQ, |
| 4483 |
ObjectIdGetDatum(partRelid)); |
| 4484 |
ScanKeyInit(&key[1], |
| 4485 |
Anum_pg_inherits_inhseqno, |
| 4486 |
BTEqualStrategyNumber, F_INT4EQ, |
| 4487 |
Int32GetDatum(1)); |
| 4488 |
scan = systable_beginscan(pg_inherits, InheritsRelidSeqnoIndexId, true, |
| 4489 |
NULL, 2, key); |
| 4490 |
tuple = systable_getnext(scan); |
| 4491 |
|
| 4492 |
if (!HeapTupleIsValid(tuple)) |
| 4493 |
{ |
| 4494 |
if (parentOid == InvalidOid) |
| 4495 |
{ |
| 4496 |
/* |
| 4497 |
* No pg_inherits row, and no parent wanted: nothing to do in this |
| 4498 |
* case. |
| 4499 |
*/ |
| 4500 |
fix_dependencies = false; |
| 4501 |
} |
| 4502 |
else |
| 4503 |
{ |
| 4504 |
StoreSingleInheritance(partRelid, parentOid, 1); |
| 4505 |
fix_dependencies = true; |
| 4506 |
} |
| 4507 |
} |
| 4508 |
else |
| 4509 |
{ |
| 4510 |
Form_pg_inherits inhForm = (Form_pg_inherits) GETSTRUCT(tuple); |
| 4511 |
|
| 4512 |
if (parentOid == InvalidOid) |
| 4513 |
{ |
| 4514 |
/* |
| 4515 |
* There exists a pg_inherits row, which we want to clear; do so. |
| 4516 |
*/ |
| 4517 |
CatalogTupleDelete(pg_inherits, &tuple->t_self); |
| 4518 |
fix_dependencies = true; |
| 4519 |
} |
| 4520 |
else |
| 4521 |
{ |
| 4522 |
/* |
| 4523 |
* A pg_inherits row exists. If it's the same we want, then we're |
| 4524 |
* good; if it differs, that amounts to a corrupt catalog and |
| 4525 |
* should not happen. |
| 4526 |
*/ |
| 4527 |
if (inhForm->inhparent != parentOid) |
| 4528 |
{ |
| 4529 |
/* unexpected: we should not get called in this case */ |
| 4530 |
elog(ERROR, "bogus pg_inherit row: inhrelid %u inhparent %u", |
| 4531 |
inhForm->inhrelid, inhForm->inhparent); |
| 4532 |
} |
| 4533 |
|
| 4534 |
/* already in the right state */ |
| 4535 |
fix_dependencies = false; |
| 4536 |
} |
| 4537 |
} |
| 4538 |
|
| 4539 |
/* done with pg_inherits */ |
| 4540 |
systable_endscan(scan); |
| 4541 |
relation_close(pg_inherits, RowExclusiveLock); |
| 4542 |
|
| 4543 |
/* set relhassubclass if an index partition has been added to the parent */ |
| 4544 |
if (OidIsValid(parentOid)) |
| 4545 |
{ |
| 4546 |
LockRelationOid(parentOid, ShareUpdateExclusiveLock); |
| 4547 |
SetRelationHasSubclass(parentOid, true); |
| 4548 |
} |
| 4549 |
|
| 4550 |
/* set relispartition correctly on the partition */ |
| 4551 |
update_relispartition(partRelid, OidIsValid(parentOid)); |
| 4552 |
|
| 4553 |
if (fix_dependencies) |
| 4554 |
{ |
| 4555 |
/* |
| 4556 |
* Insert/delete pg_depend rows. If setting a parent, add PARTITION |
| 4557 |
* dependencies on the parent index and the table; if removing a |
| 4558 |
* parent, delete PARTITION dependencies. |
| 4559 |
*/ |
| 4560 |
if (OidIsValid(parentOid)) |
| 4561 |
{ |
| 4562 |
ObjectAddress partIdx; |
| 4563 |
ObjectAddress parentIdx; |
| 4564 |
ObjectAddress partitionTbl; |
| 4565 |
|
| 4566 |
ObjectAddressSet(partIdx, RelationRelationId, partRelid); |
| 4567 |
ObjectAddressSet(parentIdx, RelationRelationId, parentOid); |
| 4568 |
ObjectAddressSet(partitionTbl, RelationRelationId, |
| 4569 |
partitionIdx->rd_index->indrelid); |
| 4570 |
recordDependencyOn(&partIdx, &parentIdx, |
| 4571 |
DEPENDENCY_PARTITION_PRI); |
| 4572 |
recordDependencyOn(&partIdx, &partitionTbl, |
| 4573 |
DEPENDENCY_PARTITION_SEC); |
| 4574 |
} |
| 4575 |
else |
| 4576 |
{ |
| 4577 |
deleteDependencyRecordsForClass(RelationRelationId, partRelid, |
| 4578 |
RelationRelationId, |
| 4579 |
DEPENDENCY_PARTITION_PRI); |
| 4580 |
deleteDependencyRecordsForClass(RelationRelationId, partRelid, |
| 4581 |
RelationRelationId, |
| 4582 |
DEPENDENCY_PARTITION_SEC); |
| 4583 |
} |
| 4584 |
|
| 4585 |
/* make our updates visible */ |
| 4586 |
CommandCounterIncrement(); |
| 4587 |
} |
| 4588 |
} |
| 4589 |
|
| 4590 |
/* |
| 4591 |
* Subroutine of IndexSetParentIndex to update the relispartition flag of the |
| 4592 |
* given index to the given value. |
| 4593 |
*/ |
| 4594 |
static void |
| 4595 |
update_relispartition(Oid relationId, bool newval) |
| 4596 |
{ |
| 4597 |
HeapTuple tup; |
| 4598 |
Relation classRel; |
| 4599 |
ItemPointerData otid; |
| 4600 |
|
| 4601 |
classRel = table_open(RelationRelationId, RowExclusiveLock); |
| 4602 |
tup = SearchSysCacheLockedCopy1(RELOID, ObjectIdGetDatum(relationId)); |
| 4603 |
if (!HeapTupleIsValid(tup)) |
| 4604 |
elog(ERROR, "cache lookup failed for relation %u", relationId); |
| 4605 |
otid = tup->t_self; |
| 4606 |
Assert(((Form_pg_class) GETSTRUCT(tup))->relispartition != newval); |
| 4607 |
((Form_pg_class) GETSTRUCT(tup))->relispartition = newval; |
| 4608 |
CatalogTupleUpdate(classRel, &otid, tup); |
| 4609 |
UnlockTuple(classRel, &otid, InplaceUpdateTupleLock); |
| 4610 |
heap_freetuple(tup); |
| 4611 |
table_close(classRel, RowExclusiveLock); |
| 4612 |
} |
| 4613 |
|
| 4614 |
/* |
| 4615 |
* Set the PROC_IN_SAFE_IC flag in MyProc->statusFlags. |
| 4616 |
* |
| 4617 |
* When doing concurrent index builds, we can set this flag |
| 4618 |
* to tell other processes concurrently running CREATE |
| 4619 |
* INDEX CONCURRENTLY or REINDEX CONCURRENTLY to ignore us when |
| 4620 |
* doing their waits for concurrent snapshots. On one hand it |
| 4621 |
* avoids pointlessly waiting for a process that's not interesting |
| 4622 |
* anyway; but more importantly it avoids deadlocks in some cases. |
| 4623 |
* |
| 4624 |
* This can be done safely only for indexes that don't execute any |
| 4625 |
* expressions that could access other tables, so index must not be |
| 4626 |
* expressional nor partial. Caller is responsible for only calling |
| 4627 |
* this routine when that assumption holds true. |
| 4628 |
* |
| 4629 |
* (The flag is reset automatically at transaction end, so it must be |
| 4630 |
* set for each transaction.) |
| 4631 |
*/ |
| 4632 |
static inline void |
| 4633 |
set_indexsafe_procflags(void) |
| 4634 |
{ |
| 4635 |
/* |
| 4636 |
* This should only be called before installing xid or xmin in MyProc; |
| 4637 |
* otherwise, concurrent processes could see an Xmin that moves backwards. |
| 4638 |
*/ |
| 4639 |
Assert(MyProc->xid == InvalidTransactionId && |
| 4640 |
MyProc->xmin == InvalidTransactionId); |
| 4641 |
|
| 4642 |
LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); |
| 4643 |
MyProc->statusFlags |= PROC_IN_SAFE_IC; |
| 4644 |
ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; |
| 4645 |
LWLockRelease(ProcArrayLock); |
| 4646 |
} |