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