Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * catalog.c
4 : : * routines concerned with catalog naming conventions and other
5 : : * bits of hard-wired knowledge
6 : : *
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/catalog/catalog.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : :
18 : : #include "postgres.h"
19 : :
20 : : #include <fcntl.h>
21 : : #include <unistd.h>
22 : :
23 : : #include "access/genam.h"
24 : : #include "access/htup_details.h"
25 : : #include "access/table.h"
26 : : #include "access/transam.h"
27 : : #include "catalog/catalog.h"
28 : : #include "catalog/namespace.h"
29 : : #include "catalog/pg_auth_members.h"
30 : : #include "catalog/pg_authid.h"
31 : : #include "catalog/pg_database.h"
32 : : #include "catalog/pg_db_role_setting.h"
33 : : #include "catalog/pg_largeobject.h"
34 : : #include "catalog/pg_namespace.h"
35 : : #include "catalog/pg_parameter_acl.h"
36 : : #include "catalog/pg_replication_origin.h"
37 : : #include "catalog/pg_seclabel.h"
38 : : #include "catalog/pg_shdepend.h"
39 : : #include "catalog/pg_shdescription.h"
40 : : #include "catalog/pg_shseclabel.h"
41 : : #include "catalog/pg_subscription.h"
42 : : #include "catalog/pg_tablespace.h"
43 : : #include "catalog/pg_type.h"
44 : : #include "miscadmin.h"
45 : : #include "utils/fmgroids.h"
46 : : #include "utils/fmgrprotos.h"
47 : : #include "utils/rel.h"
48 : : #include "utils/snapmgr.h"
49 : : #include "utils/syscache.h"
50 : :
51 : : /*
52 : : * Parameters to determine when to emit a log message in
53 : : * GetNewOidWithIndex()
54 : : */
55 : : #define GETNEWOID_LOG_THRESHOLD 1000000
56 : : #define GETNEWOID_LOG_MAX_INTERVAL 128000000
57 : :
58 : : /*
59 : : * IsSystemRelation
60 : : * True iff the relation is either a system catalog or a toast table.
61 : : * See IsCatalogRelation for the exact definition of a system catalog.
62 : : *
63 : : * We treat toast tables of user relations as "system relations" for
64 : : * protection purposes, e.g. you can't change their schemas without
65 : : * special permissions. Therefore, most uses of this function are
66 : : * checking whether allow_system_table_mods restrictions apply.
67 : : * For other purposes, consider whether you shouldn't be using
68 : : * IsCatalogRelation instead.
69 : : *
70 : : * This function does not perform any catalog accesses.
71 : : * Some callers rely on that!
72 : : */
73 : : bool
74 : 115248 : IsSystemRelation(Relation relation)
75 : : {
76 : 115248 : return IsSystemClass(RelationGetRelid(relation), relation->rd_rel);
77 : : }
78 : :
79 : : /*
80 : : * IsSystemClass
81 : : * Like the above, but takes a Form_pg_class as argument.
82 : : * Used when we do not want to open the relation and have to
83 : : * search pg_class directly.
84 : : */
85 : : bool
86 : 183391 : IsSystemClass(Oid relid, Form_pg_class reltuple)
87 : : {
88 : : /* IsCatalogRelationOid is a bit faster, so test that first */
89 [ + + ]: 347390 : return (IsCatalogRelationOid(relid) ||
90 [ + + + + ]: 347390 : IsToastClass(reltuple) ||
91 : 152594 : IsConflictLogTableClass(reltuple));
92 : : }
93 : :
94 : : /*
95 : : * IsCatalogRelation
96 : : * True iff the relation is a system catalog.
97 : : *
98 : : * By a system catalog, we mean one that is created during the bootstrap
99 : : * phase of initdb. That includes not just the catalogs per se, but
100 : : * also their indexes, and TOAST tables and indexes if any.
101 : : *
102 : : * This function does not perform any catalog accesses.
103 : : * Some callers rely on that!
104 : : */
105 : : bool
106 : 34561170 : IsCatalogRelation(Relation relation)
107 : : {
108 : 34561170 : return IsCatalogRelationOid(RelationGetRelid(relation));
109 : : }
110 : :
111 : : /*
112 : : * IsCatalogRelationOid
113 : : * True iff the relation identified by this OID is a system catalog.
114 : : *
115 : : * By a system catalog, we mean one that is created during the bootstrap
116 : : * phase of initdb. That includes not just the catalogs per se, but
117 : : * also their indexes, and TOAST tables and indexes if any.
118 : : *
119 : : * This function does not perform any catalog accesses.
120 : : * Some callers rely on that!
121 : : */
122 : : bool
123 : 61136719 : IsCatalogRelationOid(Oid relid)
124 : : {
125 : : /*
126 : : * We consider a relation to be a system catalog if it has a pinned OID.
127 : : * This includes all the defined catalogs, their indexes, and their TOAST
128 : : * tables and indexes.
129 : : *
130 : : * This rule excludes the relations in information_schema, which are not
131 : : * integral to the system and can be treated the same as user relations.
132 : : * (Since it's valid to drop and recreate information_schema, any rule
133 : : * that did not act this way would be wrong.)
134 : : *
135 : : * This test is reliable since an OID wraparound will skip this range of
136 : : * OIDs; see GetNewObjectId().
137 : : */
138 : 61136719 : return (relid < (Oid) FirstUnpinnedObjectId);
139 : : }
140 : :
141 : : /*
142 : : * IsCatalogTextUniqueIndexOid
143 : : * True iff the relation identified by this OID is a catalog UNIQUE index
144 : : * having a column of type "text".
145 : : *
146 : : * The relcache must not use these indexes. Inserting into any UNIQUE
147 : : * index compares index keys while holding BUFFER_LOCK_EXCLUSIVE.
148 : : * bttextcmp() can search the COLLOID catcache. Depending on concurrent
149 : : * invalidation traffic, catcache can reach relcache builds. A backend
150 : : * would self-deadlock on LWLocks if the relcache build read the
151 : : * exclusive-locked buffer.
152 : : *
153 : : * To avoid being itself the cause of self-deadlock, this doesn't read
154 : : * catalogs. Instead, it uses a hard-coded list with a supporting
155 : : * regression test.
156 : : */
157 : : bool
158 : 844 : IsCatalogTextUniqueIndexOid(Oid relid)
159 : : {
160 [ + + ]: 844 : switch (relid)
161 : : {
162 : 16 : case ParameterAclParnameIndexId:
163 : : case ReplicationOriginNameIndex:
164 : : case SecLabelObjectIndexId:
165 : : case SharedSecLabelObjectIndexId:
166 : 16 : return true;
167 : : }
168 : 828 : return false;
169 : : }
170 : :
171 : : /*
172 : : * IsInplaceUpdateRelation
173 : : * True iff core code performs inplace updates on the relation.
174 : : *
175 : : * This is used for assertions and for making the executor follow the
176 : : * locking protocol described at README.tuplock section "Locking to write
177 : : * inplace-updated tables". Extensions may inplace-update other heap
178 : : * tables, but concurrent SQL UPDATE on the same table may overwrite
179 : : * those modifications.
180 : : *
181 : : * The executor can assume these are not partitions or partitioned and
182 : : * have no triggers.
183 : : */
184 : : bool
185 : 280728 : IsInplaceUpdateRelation(Relation relation)
186 : : {
187 : 280728 : return IsInplaceUpdateOid(RelationGetRelid(relation));
188 : : }
189 : :
190 : : /*
191 : : * IsInplaceUpdateOid
192 : : * Like the above, but takes an OID as argument.
193 : : */
194 : : bool
195 : 280728 : IsInplaceUpdateOid(Oid relid)
196 : : {
197 [ + + + + ]: 280728 : return (relid == RelationRelationId ||
198 : : relid == DatabaseRelationId);
199 : : }
200 : :
201 : : /*
202 : : * HasVersionedAttributes
203 : : * Return whether the relation has versioned attributes.
204 : : */
205 : : bool
206 : 1151159 : HasVersionedAttributes(Relation relation)
207 : : {
208 : : Assert(RelationGetRelid(relation) != InvalidOid);
209 : :
210 : : /*
211 : : * If the relation does not have a rowtype, its attributes obviously are
212 : : * not versioned, since attribute versioning exists to protect against
213 : : * deforming composite datums incompatible with the current type
214 : : * definition.
215 : : */
216 [ + + + + : 1151159 : if (!RELKIND_HAS_ROWTYPE(relation->rd_rel->relkind))
+ + + + +
+ + + ]
217 : : {
218 : : Assert(relation->rd_rel->reltype == InvalidOid);
219 : 585063 : return false;
220 : : }
221 : :
222 : : Assert(relation->rd_rel->reltype != InvalidOid);
223 : :
224 : : /*
225 : : * Bootstrapped relations are not versioned, for two reasons:
226 : : *
227 : : * First, they can't ever change, i.e. we never need to detect mismatches.
228 : : *
229 : : * Second, to determine an attribute's version, we might need to do
230 : : * syscache lookups, which could lead to recursion dangers (this is not
231 : : * the case right now, but might again be at a later point). As there's no
232 : : * reason to version, it's not worth analyzing further.
233 : : */
234 [ + + ]: 566096 : if (RelationGetRelid(relation) < FirstUnpinnedObjectId)
235 : 214293 : return false;
236 : :
237 : : Assert(!IsBootstrapProcessingMode());
238 : :
239 : 351803 : return true;
240 : : }
241 : :
242 : : /*
243 : : * IsToastRelation
244 : : * True iff relation is a TOAST support relation (or index).
245 : : *
246 : : * Does not perform any catalog accesses.
247 : : */
248 : : bool
249 : 3532718 : IsToastRelation(Relation relation)
250 : : {
251 : : /*
252 : : * What we actually check is whether the relation belongs to a pg_toast
253 : : * namespace. This should be equivalent because of restrictions that are
254 : : * enforced elsewhere against creating user relations in, or moving
255 : : * relations into/out of, a pg_toast namespace. Notice also that this
256 : : * will not say "true" for toast tables belonging to other sessions' temp
257 : : * tables; we expect that other mechanisms will prevent access to those.
258 : : */
259 : 3532718 : return IsToastNamespace(RelationGetNamespace(relation));
260 : : }
261 : :
262 : : /*
263 : : * IsToastClass
264 : : * Like the above, but takes a Form_pg_class as argument.
265 : : * Used when we do not want to open the relation and have to
266 : : * search pg_class directly.
267 : : */
268 : : bool
269 : 163999 : IsToastClass(Form_pg_class reltuple)
270 : : {
271 : 163999 : Oid relnamespace = reltuple->relnamespace;
272 : :
273 : 163999 : return IsToastNamespace(relnamespace);
274 : : }
275 : :
276 : : /*
277 : : * IsConflictLogTableClass
278 : : * True iff pg_class tuple represents a Conflict Log Table.
279 : : *
280 : : * Does not perform any catalog accesses. See
281 : : * IsConflictLogTableNamespace() for why operations on these tables are
282 : : * restricted.
283 : : */
284 : : bool
285 : 572109 : IsConflictLogTableClass(Form_pg_class reltuple)
286 : : {
287 : 572109 : Oid relnamespace = reltuple->relnamespace;
288 : :
289 : 572109 : return IsConflictLogTableNamespace(relnamespace);
290 : : }
291 : :
292 : : /*
293 : : * IsCatalogNamespace
294 : : * True iff namespace is pg_catalog.
295 : : *
296 : : * Does not perform any catalog accesses.
297 : : *
298 : : * NOTE: the reason this isn't a macro is to avoid having to include
299 : : * catalog/pg_namespace.h in a lot of places.
300 : : */
301 : : bool
302 : 145164 : IsCatalogNamespace(Oid namespaceId)
303 : : {
304 : 145164 : return namespaceId == PG_CATALOG_NAMESPACE;
305 : : }
306 : :
307 : : /*
308 : : * IsToastNamespace
309 : : * True iff namespace is pg_toast or my temporary-toast-table namespace.
310 : : *
311 : : * Does not perform any catalog accesses.
312 : : *
313 : : * Note: this will return false for temporary-toast-table namespaces belonging
314 : : * to other backends. Those are treated the same as other backends' regular
315 : : * temp table namespaces, and access is prevented where appropriate.
316 : : * If you need to check for those, you may be able to use isAnyTempNamespace,
317 : : * but beware that that does involve a catalog access.
318 : : */
319 : : bool
320 : 3759464 : IsToastNamespace(Oid namespaceId)
321 : : {
322 [ + + + + ]: 7478151 : return (namespaceId == PG_TOAST_NAMESPACE) ||
323 : 3718687 : isTempToastNamespace(namespaceId);
324 : : }
325 : :
326 : : /*
327 : : * IsConflictLogTableNamespace
328 : : * True iff namespace is pg_conflict.
329 : : *
330 : : * Does not perform any catalog accesses.
331 : : *
332 : : * Tables in the pg_conflict namespace are conflict log tables, created and
333 : : * maintained by the system to record logical replication conflicts. The
334 : : * apply worker's inserts depend on their fixed structure, so they are treated
335 : : * as system-managed: call sites across the backend use this (and
336 : : * IsConflictLogTableClass()) to reject operations that could disrupt logging,
337 : : * such as DDL, manual INSERT/UPDATE/MERGE, and row locking. SELECT, DELETE
338 : : * and TRUNCATE are the only data operations allowed, so that users can still
339 : : * query and prune conflict rows.
340 : : */
341 : : bool
342 : 1623443 : IsConflictLogTableNamespace(Oid namespaceId)
343 : : {
344 : 1623443 : return namespaceId == PG_CONFLICT_NAMESPACE;
345 : : }
346 : :
347 : : /*
348 : : * IsReservedName
349 : : * True iff name starts with the pg_ prefix.
350 : : *
351 : : * For some classes of objects, the prefix pg_ is reserved for
352 : : * system objects only. As of 8.0, this was only true for
353 : : * schema and tablespace names. With 9.6, this is also true
354 : : * for roles.
355 : : */
356 : : bool
357 : 2475 : IsReservedName(const char *name)
358 : : {
359 : : /* ugly coding for speed */
360 : 2539 : return (name[0] == 'p' &&
361 [ + + + + ]: 2489 : name[1] == 'g' &&
362 [ + + ]: 14 : name[2] == '_');
363 : : }
364 : :
365 : :
366 : : /*
367 : : * IsSharedRelation
368 : : * Given the OID of a relation, determine whether it's supposed to be
369 : : * shared across an entire database cluster.
370 : : *
371 : : * In older releases, this had to be hard-wired so that we could compute the
372 : : * locktag for a relation and lock it before examining its catalog entry.
373 : : * Since we now have MVCC catalog access, the race conditions that made that
374 : : * a hard requirement are gone, so we could look at relaxing this restriction.
375 : : * However, if we scanned the pg_class entry to find relisshared, and only
376 : : * then locked the relation, pg_class could get updated in the meantime,
377 : : * forcing us to scan the relation again, which would definitely be complex
378 : : * and might have undesirable performance consequences. Fortunately, the set
379 : : * of shared relations is fairly static, so a hand-maintained list of their
380 : : * OIDs isn't completely impractical.
381 : : */
382 : : bool
383 : 29374162 : IsSharedRelation(Oid relationId)
384 : : {
385 : : /* These are the shared catalogs (look for BKI_SHARED_RELATION) */
386 [ + + + + ]: 29374162 : if (relationId == AuthIdRelationId ||
387 [ + + ]: 29232852 : relationId == AuthMemRelationId ||
388 [ + + ]: 29127394 : relationId == DatabaseRelationId ||
389 [ + + ]: 29099505 : relationId == DbRoleSettingRelationId ||
390 [ + + ]: 29076873 : relationId == ParameterAclRelationId ||
391 [ + + ]: 29056278 : relationId == ReplicationOriginRelationId ||
392 [ + + ]: 28743794 : relationId == SharedDependRelationId ||
393 [ + + ]: 28739888 : relationId == SharedDescriptionRelationId ||
394 [ + + ]: 28732210 : relationId == SharedSecLabelRelationId ||
395 [ + + ]: 28706106 : relationId == SubscriptionRelationId ||
396 : : relationId == TableSpaceRelationId)
397 : 699693 : return true;
398 : : /* These are their indexes */
399 [ + + + + ]: 28674469 : if (relationId == AuthIdOidIndexId ||
400 [ + + ]: 28594317 : relationId == AuthIdRolnameIndexId ||
401 [ + + ]: 28582980 : relationId == AuthMemMemRoleIndexId ||
402 [ + + ]: 28576903 : relationId == AuthMemRoleMemIndexId ||
403 [ + + ]: 28574347 : relationId == AuthMemOidIndexId ||
404 [ + + ]: 28572406 : relationId == AuthMemGrantorIndexId ||
405 [ + + ]: 28546930 : relationId == DatabaseNameIndexId ||
406 [ + + ]: 28492617 : relationId == DatabaseOidIndexId ||
407 [ + + ]: 28405640 : relationId == DbRoleSettingDatidRolidIndexId ||
408 [ + + ]: 28398420 : relationId == ParameterAclOidIndexId ||
409 [ + + ]: 28391232 : relationId == ParameterAclParnameIndexId ||
410 [ + + ]: 28385600 : relationId == ReplicationOriginIdentIndex ||
411 [ + + ]: 28380058 : relationId == ReplicationOriginNameIndex ||
412 [ + + ]: 28209400 : relationId == SharedDependDependerIndexId ||
413 [ + + ]: 28200528 : relationId == SharedDependReferenceIndexId ||
414 [ + + ]: 28197398 : relationId == SharedDescriptionObjIndexId ||
415 [ + + ]: 28190491 : relationId == SharedSecLabelObjectIndexId ||
416 [ + + ]: 28184190 : relationId == SubscriptionNameIndexId ||
417 [ + + ]: 28177197 : relationId == SubscriptionObjectIndexId ||
418 [ + + ]: 28174252 : relationId == TablespaceNameIndexId ||
419 : : relationId == TablespaceOidIndexId)
420 : 516196 : return true;
421 : : /* These are their toast tables and toast indexes */
422 [ + + + + ]: 28158273 : if (relationId == PgDatabaseToastTable ||
423 [ + + ]: 28155342 : relationId == PgDatabaseToastIndex ||
424 [ + + ]: 28153922 : relationId == PgDbRoleSettingToastTable ||
425 [ + + ]: 28152691 : relationId == PgDbRoleSettingToastIndex ||
426 [ + + ]: 28151277 : relationId == PgParameterAclToastTable ||
427 [ + + ]: 28150052 : relationId == PgParameterAclToastIndex ||
428 [ + + ]: 28148602 : relationId == PgShdescriptionToastTable ||
429 [ + + ]: 28147343 : relationId == PgShdescriptionToastIndex ||
430 [ + + ]: 28145928 : relationId == PgShseclabelToastTable ||
431 [ + + ]: 28144702 : relationId == PgShseclabelToastIndex ||
432 [ + + ]: 28143287 : relationId == PgSubscriptionToastTable ||
433 [ + + ]: 28142061 : relationId == PgSubscriptionToastIndex ||
434 [ + + ]: 28140617 : relationId == PgTablespaceToastTable ||
435 : : relationId == PgTablespaceToastIndex)
436 : 18912 : return true;
437 : 28139361 : return false;
438 : : }
439 : :
440 : : /*
441 : : * IsPinnedObject
442 : : * Given the class + OID identity of a database object, report whether
443 : : * it is "pinned", that is not droppable because the system requires it.
444 : : *
445 : : * We used to represent this explicitly in pg_depend, but that proved to be
446 : : * an undesirable amount of overhead, so now we rely on an OID range test.
447 : : */
448 : : bool
449 : 1798704 : IsPinnedObject(Oid classId, Oid objectId)
450 : : {
451 : : /*
452 : : * Objects with OIDs above FirstUnpinnedObjectId are never pinned. Since
453 : : * the OID generator skips this range when wrapping around, this check
454 : : * guarantees that user-defined objects are never considered pinned.
455 : : */
456 [ + + ]: 1798704 : if (objectId >= FirstUnpinnedObjectId)
457 : 531246 : return false;
458 : :
459 : : /*
460 : : * Large objects are never pinned. We need this special case because
461 : : * their OIDs can be user-assigned.
462 : : */
463 [ + + ]: 1267458 : if (classId == LargeObjectRelationId)
464 : 36 : return false;
465 : :
466 : : /*
467 : : * There are a few objects defined in the catalog .dat files that, as a
468 : : * matter of policy, we prefer not to treat as pinned. We used to handle
469 : : * that by excluding them from pg_depend, but it's just as easy to
470 : : * hard-wire their OIDs here. (If the user does indeed drop and recreate
471 : : * them, they'll have new but certainly-unpinned OIDs, so no problem.)
472 : : *
473 : : * Checking both classId and objectId is overkill, since OIDs below
474 : : * FirstGenbkiObjectId should be globally unique, but do it anyway for
475 : : * robustness.
476 : : */
477 : :
478 : : /* the public namespace is not pinned */
479 [ + + + + ]: 1267422 : if (classId == NamespaceRelationId &&
480 : : objectId == PG_PUBLIC_NAMESPACE)
481 : 40626 : return false;
482 : :
483 : : /*
484 : : * Databases are never pinned. It might seem that it'd be prudent to pin
485 : : * at least template0; but we do this intentionally so that template0 and
486 : : * template1 can be rebuilt from each other, thus letting them serve as
487 : : * mutual backups (as long as you've not modified template1, anyway).
488 : : */
489 [ - + ]: 1226796 : if (classId == DatabaseRelationId)
490 : 0 : return false;
491 : :
492 : : /*
493 : : * All other initdb-created objects are pinned. This is overkill (the
494 : : * system doesn't really depend on having every last weird datatype, for
495 : : * instance) but generating only the minimum required set of dependencies
496 : : * seems hard, and enforcing an accurate list would be much more expensive
497 : : * than the simple range test used here.
498 : : */
499 : 1226796 : return true;
500 : : }
501 : :
502 : :
503 : : /*
504 : : * GetNewOidWithIndex
505 : : * Generate a new OID that is unique within the system relation.
506 : : *
507 : : * Since the OID is not immediately inserted into the table, there is a
508 : : * race condition here; but a problem could occur only if someone else
509 : : * managed to cycle through 2^32 OIDs and generate the same OID before we
510 : : * finish inserting our row. This seems unlikely to be a problem. Note
511 : : * that if we had to *commit* the row to end the race condition, the risk
512 : : * would be rather higher; therefore we use SnapshotAny in the test, so that
513 : : * we will see uncommitted rows. (We used to use SnapshotDirty, but that has
514 : : * the disadvantage that it ignores recently-deleted rows, creating a risk
515 : : * of transient conflicts for as long as our own MVCC snapshots think a
516 : : * recently-deleted row is live. The risk is far higher when selecting TOAST
517 : : * OIDs, because SnapshotToast considers dead rows as active indefinitely.)
518 : : *
519 : : * Note that we are effectively assuming that the table has a relatively small
520 : : * number of entries (much less than 2^32) and there aren't very long runs of
521 : : * consecutive existing OIDs. This is a mostly reasonable assumption for
522 : : * system catalogs.
523 : : *
524 : : * Caller must have a suitable lock on the relation.
525 : : */
526 : : Oid
527 : 574040 : GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
528 : : {
529 : : Oid newOid;
530 : : SysScanDesc scan;
531 : : ScanKeyData key;
532 : : bool collides;
533 : 574040 : uint64 retries = 0;
534 : 574040 : uint64 retries_before_log = GETNEWOID_LOG_THRESHOLD;
535 : :
536 : : /* Only system relations are supported */
537 : : Assert(IsSystemRelation(relation));
538 : :
539 : : /* In bootstrap mode, we don't have any indexes to use */
540 [ + + ]: 574040 : if (IsBootstrapProcessingMode())
541 : 6954 : return GetNewObjectId();
542 : :
543 : : /*
544 : : * We should never be asked to generate a new pg_type OID during
545 : : * pg_upgrade; doing so would risk collisions with the OIDs it wants to
546 : : * assign. Hitting this assert means there's some path where we failed to
547 : : * ensure that a type OID is determined by commands in the dump script.
548 : : */
549 : : Assert(!IsBinaryUpgrade || RelationGetRelid(relation) != TypeRelationId);
550 : :
551 : : /* Generate new OIDs until we find one not in the table */
552 : : do
553 : : {
554 [ - + ]: 567086 : CHECK_FOR_INTERRUPTS();
555 : :
556 : 567086 : newOid = GetNewObjectId();
557 : :
558 : 567086 : ScanKeyInit(&key,
559 : : oidcolumn,
560 : : BTEqualStrategyNumber, F_OIDEQ,
561 : : ObjectIdGetDatum(newOid));
562 : :
563 : : /* see notes above about using SnapshotAny */
564 : 567086 : scan = systable_beginscan(relation, indexId, true,
565 : : SnapshotAny, 1, &key);
566 : :
567 : 567086 : collides = HeapTupleIsValid(systable_getnext(scan));
568 : :
569 : 567086 : systable_endscan(scan);
570 : :
571 : : /*
572 : : * Log that we iterate more than GETNEWOID_LOG_THRESHOLD but have not
573 : : * yet found OID unused in the relation. Then repeat logging with
574 : : * exponentially increasing intervals until we iterate more than
575 : : * GETNEWOID_LOG_MAX_INTERVAL. Finally repeat logging every
576 : : * GETNEWOID_LOG_MAX_INTERVAL unless an unused OID is found. This
577 : : * logic is necessary not to fill up the server log with the similar
578 : : * messages.
579 : : */
580 [ - + ]: 567086 : if (retries >= retries_before_log)
581 : : {
582 [ # # ]: 0 : ereport(LOG,
583 : : (errmsg("still searching for an unused OID in relation \"%s\"",
584 : : RelationGetRelationName(relation)),
585 : : errdetail_plural("OID candidates have been checked %" PRIu64 " time, but no unused OID has been found yet.",
586 : : "OID candidates have been checked %" PRIu64 " times, but no unused OID has been found yet.",
587 : : retries,
588 : : retries)));
589 : :
590 : : /*
591 : : * Double the number of retries to do before logging next until it
592 : : * reaches GETNEWOID_LOG_MAX_INTERVAL.
593 : : */
594 [ # # ]: 0 : if (retries_before_log * 2 <= GETNEWOID_LOG_MAX_INTERVAL)
595 : 0 : retries_before_log *= 2;
596 : : else
597 : 0 : retries_before_log += GETNEWOID_LOG_MAX_INTERVAL;
598 : : }
599 : :
600 : 567086 : retries++;
601 [ - + ]: 567086 : } while (collides);
602 : :
603 : : /*
604 : : * If at least one log message is emitted, also log the completion of OID
605 : : * assignment.
606 : : */
607 [ - + ]: 567086 : if (retries > GETNEWOID_LOG_THRESHOLD)
608 : : {
609 [ # # ]: 0 : ereport(LOG,
610 : : (errmsg_plural("new OID has been assigned in relation \"%s\" after %" PRIu64 " retry",
611 : : "new OID has been assigned in relation \"%s\" after %" PRIu64 " retries",
612 : : retries,
613 : : RelationGetRelationName(relation), retries)));
614 : : }
615 : :
616 : 567086 : return newOid;
617 : : }
618 : :
619 : : /*
620 : : * GetNewRelFileNumber
621 : : * Generate a new relfilenumber that is unique within the
622 : : * database of the given tablespace.
623 : : *
624 : : * If the relfilenumber will also be used as the relation's OID, pass the
625 : : * opened pg_class catalog, and this routine will guarantee that the result
626 : : * is also an unused OID within pg_class. If the result is to be used only
627 : : * as a relfilenumber for an existing relation, pass NULL for pg_class.
628 : : *
629 : : * As with GetNewOidWithIndex(), there is some theoretical risk of a race
630 : : * condition, but it doesn't seem worth worrying about.
631 : : *
632 : : * Note: we don't support using this in bootstrap mode. All relations
633 : : * created by bootstrap have preassigned OIDs, so there's no need.
634 : : */
635 : : RelFileNumber
636 : 82672 : GetNewRelFileNumber(Oid reltablespace, Relation pg_class, char relpersistence)
637 : : {
638 : : RelFileLocatorBackend rlocator;
639 : : RelPathStr rpath;
640 : : bool collides;
641 : : ProcNumber procNumber;
642 : :
643 : : /*
644 : : * If we ever get here during pg_upgrade, there's something wrong; all
645 : : * relfilenumber assignments during a binary-upgrade run should be
646 : : * determined by commands in the dump script.
647 : : */
648 : : Assert(!IsBinaryUpgrade);
649 : :
650 [ + + - ]: 82672 : switch (relpersistence)
651 : : {
652 : 5012 : case RELPERSISTENCE_TEMP:
653 [ + - ]: 5012 : procNumber = ProcNumberForTempRelations();
654 : 5012 : break;
655 : 77660 : case RELPERSISTENCE_UNLOGGED:
656 : : case RELPERSISTENCE_PERMANENT:
657 : 77660 : procNumber = INVALID_PROC_NUMBER;
658 : 77660 : break;
659 : 0 : default:
660 [ # # ]: 0 : elog(ERROR, "invalid relpersistence: %c", relpersistence);
661 : : return InvalidRelFileNumber; /* placate compiler */
662 : : }
663 : :
664 : : /* This logic should match RelationInitPhysicalAddr */
665 [ + + ]: 82672 : rlocator.locator.spcOid = reltablespace ? reltablespace : MyDatabaseTableSpace;
666 : 82672 : rlocator.locator.dbOid =
667 : 82672 : (rlocator.locator.spcOid == GLOBALTABLESPACE_OID) ?
668 [ + + ]: 82672 : InvalidOid : MyDatabaseId;
669 : :
670 : : /*
671 : : * The relpath will vary based on the backend number, so we must
672 : : * initialize that properly here to make sure that any collisions based on
673 : : * filename are properly detected.
674 : : */
675 : 82672 : rlocator.backend = procNumber;
676 : :
677 : : do
678 : : {
679 [ + + ]: 82672 : CHECK_FOR_INTERRUPTS();
680 : :
681 : : /* Generate the OID */
682 [ + + ]: 82672 : if (pg_class)
683 : 74411 : rlocator.locator.relNumber = GetNewOidWithIndex(pg_class, ClassOidIndexId,
684 : : Anum_pg_class_oid);
685 : : else
686 : 8261 : rlocator.locator.relNumber = GetNewObjectId();
687 : :
688 : : /* Check for existing file of same name */
689 : 82672 : rpath = relpath(rlocator, MAIN_FORKNUM);
690 : :
691 [ - + ]: 82672 : if (access(rpath.str, F_OK) == 0)
692 : : {
693 : : /* definite collision */
694 : 0 : collides = true;
695 : : }
696 : : else
697 : : {
698 : : /*
699 : : * Here we have a little bit of a dilemma: if errno is something
700 : : * other than ENOENT, should we declare a collision and loop? In
701 : : * practice it seems best to go ahead regardless of the errno. If
702 : : * there is a colliding file we will get an smgr failure when we
703 : : * attempt to create the new relation file.
704 : : */
705 : 82672 : collides = false;
706 : : }
707 [ - + ]: 82672 : } while (collides);
708 : :
709 : 82672 : return rlocator.locator.relNumber;
710 : : }
711 : :
712 : : /*
713 : : * SQL callable interface for GetNewOidWithIndex(). Outside of initdb's
714 : : * direct insertions into catalog tables, and recovering from corruption, this
715 : : * should rarely be needed.
716 : : *
717 : : * Function is intentionally not documented in the user facing docs.
718 : : */
719 : : Datum
720 : 0 : pg_nextoid(PG_FUNCTION_ARGS)
721 : : {
722 : 0 : Oid reloid = PG_GETARG_OID(0);
723 : 0 : Name attname = PG_GETARG_NAME(1);
724 : 0 : Oid idxoid = PG_GETARG_OID(2);
725 : : Relation rel;
726 : : Relation idx;
727 : : HeapTuple atttuple;
728 : : Form_pg_attribute attform;
729 : : AttrNumber attno;
730 : : Oid newoid;
731 : :
732 : : /*
733 : : * As this function is not intended to be used during normal running, and
734 : : * only supports system catalogs (which require superuser permissions to
735 : : * modify), just checking for superuser ought to not obstruct valid
736 : : * usecases.
737 : : */
738 [ # # ]: 0 : if (!superuser())
739 [ # # ]: 0 : ereport(ERROR,
740 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
741 : : errmsg("must be superuser to call %s()",
742 : : "pg_nextoid")));
743 : :
744 : 0 : rel = table_open(reloid, RowExclusiveLock);
745 : 0 : idx = index_open(idxoid, RowExclusiveLock);
746 : :
747 [ # # ]: 0 : if (!IsSystemRelation(rel))
748 [ # # ]: 0 : ereport(ERROR,
749 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
750 : : errmsg("pg_nextoid() can only be used on system catalogs")));
751 : :
752 [ # # ]: 0 : if (idx->rd_index->indrelid != RelationGetRelid(rel))
753 [ # # ]: 0 : ereport(ERROR,
754 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
755 : : errmsg("index \"%s\" does not belong to table \"%s\"",
756 : : RelationGetRelationName(idx),
757 : : RelationGetRelationName(rel))));
758 : :
759 : 0 : atttuple = SearchSysCacheAttName(reloid, NameStr(*attname));
760 [ # # ]: 0 : if (!HeapTupleIsValid(atttuple))
761 [ # # ]: 0 : ereport(ERROR,
762 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
763 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
764 : : NameStr(*attname), RelationGetRelationName(rel))));
765 : :
766 : 0 : attform = ((Form_pg_attribute) GETSTRUCT(atttuple));
767 : 0 : attno = attform->attnum;
768 : :
769 [ # # ]: 0 : if (attform->atttypid != OIDOID)
770 [ # # ]: 0 : ereport(ERROR,
771 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
772 : : errmsg("column \"%s\" is not of type %s",
773 : : NameStr(*attname), "oid")));
774 : :
775 [ # # ]: 0 : if (IndexRelationGetNumberOfKeyAttributes(idx) != 1 ||
776 [ # # ]: 0 : idx->rd_index->indkey.values[0] != attno)
777 [ # # ]: 0 : ereport(ERROR,
778 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
779 : : errmsg("index \"%s\" is not the index for column \"%s\"",
780 : : RelationGetRelationName(idx),
781 : : NameStr(*attname))));
782 : :
783 : 0 : newoid = GetNewOidWithIndex(rel, idxoid, attno);
784 : :
785 : 0 : ReleaseSysCache(atttuple);
786 : 0 : table_close(rel, RowExclusiveLock);
787 : 0 : index_close(idx, RowExclusiveLock);
788 : :
789 : 0 : PG_RETURN_OID(newoid);
790 : : }
791 : :
792 : : /*
793 : : * SQL callable interface for StopGeneratingPinnedObjectIds().
794 : : *
795 : : * This is only to be used by initdb, so it's intentionally not documented in
796 : : * the user facing docs.
797 : : */
798 : : Datum
799 : 59 : pg_stop_making_pinned_objects(PG_FUNCTION_ARGS)
800 : : {
801 : : /*
802 : : * Belt-and-suspenders check, since StopGeneratingPinnedObjectIds will
803 : : * fail anyway in non-single-user mode.
804 : : */
805 [ - + ]: 59 : if (!superuser())
806 [ # # ]: 0 : ereport(ERROR,
807 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
808 : : errmsg("must be superuser to call %s()",
809 : : "pg_stop_making_pinned_objects")));
810 : :
811 : 59 : StopGeneratingPinnedObjectIds();
812 : :
813 : 59 : PG_RETURN_VOID();
814 : : }
|