Debian Codegraph @

src/backend/catalog/namespace.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * namespace.c
4 * code to support accessing and searching namespaces
5 *
6 * This is separate from pg_namespace.c, which contains the routines that
7 * directly manipulate the pg_namespace system catalog. This module
8 * provides routines associated with defining a "namespace search path"
9 * and implementing search-path-controlled searches.
10 *
11 *
12 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
14 *
15 * IDENTIFICATION
16 * src/backend/catalog/namespace.c
17 *
18 *-------------------------------------------------------------------------
19 */
20 #include "postgres.h"
21
22 #include "access/htup_details.h"
23 #include "access/parallel.h"
24 #include "access/xact.h"
25 #include "access/xlog.h"
26 #include "catalog/dependency.h"
27 #include "catalog/namespace.h"
28 #include "catalog/objectaccess.h"
29 #include "catalog/pg_authid.h"
30 #include "catalog/pg_collation.h"
31 #include "catalog/pg_conversion.h"
32 #include "catalog/pg_database.h"
33 #include "catalog/pg_namespace.h"
34 #include "catalog/pg_opclass.h"
35 #include "catalog/pg_operator.h"
36 #include "catalog/pg_opfamily.h"
37 #include "catalog/pg_proc.h"
38 #include "catalog/pg_statistic_ext.h"
39 #include "catalog/pg_ts_config.h"
40 #include "catalog/pg_ts_dict.h"
41 #include "catalog/pg_ts_parser.h"
42 #include "catalog/pg_ts_template.h"
43 #include "catalog/pg_type.h"
44 #include "commands/dbcommands.h"
45 #include "common/hashfn_unstable.h"
46 #include "funcapi.h"
47 #include "mb/pg_wchar.h"
48 #include "miscadmin.h"
49 #include "nodes/makefuncs.h"
50 #include "storage/ipc.h"
51 #include "storage/lmgr.h"
52 #include "storage/procarray.h"
53 #include "utils/acl.h"
54 #include "utils/builtins.h"
55 #include "utils/catcache.h"
56 #include "utils/guc_hooks.h"
57 #include "utils/inval.h"
58 #include "utils/lsyscache.h"
59 #include "utils/memutils.h"
60 #include "utils/snapmgr.h"
61 #include "utils/syscache.h"
62 #include "utils/varlena.h"
63
64
65 /*
66 * The namespace search path is a possibly-empty list of namespace OIDs.
67 * In addition to the explicit list, implicitly-searched namespaces
68 * may be included:
69 *
70 * 1. If a TEMP table namespace has been initialized in this session, it
71 * is implicitly searched first.
72 *
73 * 2. The system catalog namespace is always searched. If the system
74 * namespace is present in the explicit path then it will be searched in
75 * the specified order; otherwise it will be searched after TEMP tables and
76 * *before* the explicit list. (It might seem that the system namespace
77 * should be implicitly last, but this behavior appears to be required by
78 * SQL99. Also, this provides a way to search the system namespace first
79 * without thereby making it the default creation target namespace.)
80 *
81 * For security reasons, searches using the search path will ignore the temp
82 * namespace when searching for any object type other than relations and
83 * types. (We must allow types since temp tables have rowtypes.)
84 *
85 * The default creation target namespace is always the first element of the
86 * explicit list. If the explicit list is empty, there is no default target.
87 *
88 * The textual specification of search_path can include "$user" to refer to
89 * the namespace named the same as the current user, if any. (This is just
90 * ignored if there is no such namespace.) Also, it can include "pg_temp"
91 * to refer to the current backend's temp namespace. This is usually also
92 * ignorable if the temp namespace hasn't been set up, but there's a special
93 * case: if "pg_temp" appears first then it should be the default creation
94 * target. We kluge this case a little bit so that the temp namespace isn't
95 * set up until the first attempt to create something in it. (The reason for
96 * klugery is that we can't create the temp namespace outside a transaction,
97 * but initial GUC processing of search_path happens outside a transaction.)
98 * activeTempCreationPending is true if "pg_temp" appears first in the string
99 * but is not reflected in activeCreationNamespace because the namespace isn't
100 * set up yet.
101 *
102 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
103 * the system namespace is the only one searched or inserted into.
104 * initdb is also careful to set search_path to "pg_catalog" for its
105 * post-bootstrap standalone backend runs. Otherwise the default search
106 * path is determined by GUC. The factory default path contains the PUBLIC
107 * namespace (if it exists), preceded by the user's personal namespace
108 * (if one exists).
109 *
110 * activeSearchPath is always the actually active path; it points to
111 * baseSearchPath which is the list derived from namespace_search_path.
112 *
113 * If baseSearchPathValid is false, then baseSearchPath (and other derived
114 * variables) need to be recomputed from namespace_search_path, or retrieved
115 * from the search path cache if there haven't been any syscache
116 * invalidations. We mark it invalid upon an assignment to
117 * namespace_search_path or receipt of a syscache invalidation event for
118 * pg_namespace or pg_authid. The recomputation is done during the next
119 * lookup attempt.
120 *
121 * Any namespaces mentioned in namespace_search_path that are not readable
122 * by the current user ID are simply left out of baseSearchPath; so
123 * we have to be willing to recompute the path when current userid changes.
124 * namespaceUser is the userid the path has been computed for.
125 *
126 * Note: all data pointed to by these List variables is in TopMemoryContext.
127 *
128 * activePathGeneration is incremented whenever the effective values of
129 * activeSearchPath/activeCreationNamespace/activeTempCreationPending change.
130 * This can be used to quickly detect whether any change has happened since
131 * a previous examination of the search path state.
132 */
133
134 /* These variables define the actually active state: */
135
136 static List *activeSearchPath = NIL;
137
138 /* default place to create stuff; if InvalidOid, no default */
139 static Oid activeCreationNamespace = InvalidOid;
140
141 /* if true, activeCreationNamespace is wrong, it should be temp namespace */
142 static bool activeTempCreationPending = false;
143
144 /* current generation counter; make sure this is never zero */
145 static uint64 activePathGeneration = 1;
146
147 /* These variables are the values last derived from namespace_search_path: */
148
149 static List *baseSearchPath = NIL;
150
151 static Oid baseCreationNamespace = InvalidOid;
152
153 static bool baseTempCreationPending = false;
154
155 static Oid namespaceUser = InvalidOid;
156
157 /* The above four values are valid only if baseSearchPathValid */
158 static bool baseSearchPathValid = true;
159
160 /*
161 * Storage for search path cache. Clear searchPathCacheValid as a simple
162 * way to invalidate *all* the cache entries, not just the active one.
163 */
164 static bool searchPathCacheValid = false;
165 static MemoryContext SearchPathCacheContext = NULL;
166
167 typedef struct SearchPathCacheKey
168 {
169 const char *searchPath;
170 Oid roleid;
171 } SearchPathCacheKey;
172
173 typedef struct SearchPathCacheEntry
174 {
175 SearchPathCacheKey key;
176 List *oidlist; /* namespace OIDs that pass ACL checks */
177 List *finalPath; /* cached final computed search path */
178 Oid firstNS; /* first explicitly-listed namespace */
179 bool temp_missing;
180 bool forceRecompute; /* force recompute of finalPath */
181
182 /* needed for simplehash */
183 char status;
184 } SearchPathCacheEntry;
185
186 /*
187 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
188 * in a particular backend session (this happens when a CREATE TEMP TABLE
189 * command is first executed). Thereafter it's the OID of the temp namespace.
190 *
191 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
192 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
193 *
194 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
195 * current subtransaction. The flag propagates up the subtransaction tree,
196 * so the main transaction will correctly recognize the flag if all
197 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
198 * we either haven't made the TEMP namespace yet, or have successfully
199 * committed its creation, depending on whether myTempNamespace is valid.
200 */
201 static Oid myTempNamespace = InvalidOid;
202
203 static Oid myTempToastNamespace = InvalidOid;
204
205 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
206
207 /*
208 * This is the user's textual search path specification --- it's the value
209 * of the GUC variable 'search_path'.
210 */
211 char *namespace_search_path = NULL;
212
213
214 /* Local functions */
215 static bool RelationIsVisibleExt(Oid relid, bool *is_missing);
216 static bool TypeIsVisibleExt(Oid typid, bool *is_missing);
217 static bool FunctionIsVisibleExt(Oid funcid, bool *is_missing);
218 static bool OperatorIsVisibleExt(Oid oprid, bool *is_missing);
219 static bool OpclassIsVisibleExt(Oid opcid, bool *is_missing);
220 static bool OpfamilyIsVisibleExt(Oid opfid, bool *is_missing);
221 static bool CollationIsVisibleExt(Oid collid, bool *is_missing);
222 static bool ConversionIsVisibleExt(Oid conid, bool *is_missing);
223 static bool StatisticsObjIsVisibleExt(Oid stxid, bool *is_missing);
224 static bool TSParserIsVisibleExt(Oid prsId, bool *is_missing);
225 static bool TSDictionaryIsVisibleExt(Oid dictId, bool *is_missing);
226 static bool TSTemplateIsVisibleExt(Oid tmplId, bool *is_missing);
227 static bool TSConfigIsVisibleExt(Oid cfgid, bool *is_missing);
228 static void recomputeNamespacePath(void);
229 static void AccessTempTableNamespace(bool force);
230 static void InitTempTableNamespace(void);
231 static void RemoveTempRelations(Oid tempNamespaceId);
232 static void RemoveTempRelationsCallback(int code, Datum arg);
233 static void InvalidationCallback(Datum arg, int cacheid, uint32 hashvalue);
234 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
235 bool include_out_arguments, int pronargs,
236 int **argnumbers);
237
238 /*
239 * Recomputing the namespace path can be costly when done frequently, such as
240 * when a function has search_path set in proconfig. Add a search path cache
241 * that can be used by recomputeNamespacePath().
242 *
243 * The cache is also used to remember already-validated strings in
244 * check_search_path() to avoid the need to call SplitIdentifierString()
245 * repeatedly.
246 *
247 * The search path cache is based on a wrapper around a simplehash hash table
248 * (nsphash, defined below). The spcache wrapper deals with OOM while trying
249 * to initialize a key, optimizes repeated lookups of the same key, and also
250 * offers a more convenient API.
251 */
252
253 static inline uint32
254 spcachekey_hash(SearchPathCacheKey key)
255 {
256 fasthash_state hs;
257 int sp_len;
258
259 fasthash_init(&hs, 0);
260
261 hs.accum = key.roleid;
262 fasthash_combine(&hs);
263
264 /*
265 * Combine search path into the hash and save the length for tweaking the
266 * final mix.
267 */
268 sp_len = fasthash_accum_cstring(&hs, key.searchPath);
269
270 return fasthash_final32(&hs, sp_len);
271 }
272
273 static inline bool
274 spcachekey_equal(SearchPathCacheKey a, SearchPathCacheKey b)
275 {
276 return a.roleid == b.roleid &&
277 strcmp(a.searchPath, b.searchPath) == 0;
278 }
279
280 #define SH_PREFIX nsphash
281 #define SH_ELEMENT_TYPE SearchPathCacheEntry
282 #define SH_KEY_TYPE SearchPathCacheKey
283 #define SH_KEY key
284 #define SH_HASH_KEY(tb, key) spcachekey_hash(key)
285 #define SH_EQUAL(tb, a, b) spcachekey_equal(a, b)
286 #define SH_SCOPE static inline
287 #define SH_DECLARE
288 #define SH_DEFINE
289 #include "lib/simplehash.h"
290
291 /*
292 * We only expect a small number of unique search_path strings to be used. If
293 * this cache grows to an unreasonable size, reset it to avoid steady-state
294 * memory growth. Most likely, only a few of those entries will benefit from
295 * the cache, and the cache will be quickly repopulated with such entries.
296 */
297 #define SPCACHE_RESET_THRESHOLD 256
298
299 static nsphash_hash *SearchPathCache = NULL;
300 static SearchPathCacheEntry *LastSearchPathCacheEntry = NULL;
301
302 /*
303 * Create or reset search_path cache as necessary.
304 */
305 static void
306 spcache_init(void)
307 {
308 if (SearchPathCache && searchPathCacheValid &&
309 SearchPathCache->members < SPCACHE_RESET_THRESHOLD)
310 return;
311
312 searchPathCacheValid = false;
313 baseSearchPathValid = false;
314
315 /*
316 * Make sure we don't leave dangling pointers if a failure happens during
317 * initialization.
318 */
319 SearchPathCache = NULL;
320 LastSearchPathCacheEntry = NULL;
321
322 if (SearchPathCacheContext == NULL)
323 {
324 /* Make the context we'll keep search path cache hashtable in */
325 SearchPathCacheContext = AllocSetContextCreate(TopMemoryContext,
326 "search_path processing cache",
327 ALLOCSET_DEFAULT_SIZES);
328 }
329 else
330 {
331 MemoryContextReset(SearchPathCacheContext);
332 }
333
334 /* arbitrary initial starting size of 16 elements */
335 SearchPathCache = nsphash_create(SearchPathCacheContext, 16, NULL);
336 searchPathCacheValid = true;
337 }
338
339 /*
340 * Look up entry in search path cache without inserting. Returns NULL if not
341 * present.
342 */
343 static SearchPathCacheEntry *
344 spcache_lookup(const char *searchPath, Oid roleid)
345 {
346 if (LastSearchPathCacheEntry &&
347 LastSearchPathCacheEntry->key.roleid == roleid &&
348 strcmp(LastSearchPathCacheEntry->key.searchPath, searchPath) == 0)
349 {
350 return LastSearchPathCacheEntry;
351 }
352 else
353 {
354 SearchPathCacheEntry *entry;
355 SearchPathCacheKey cachekey = {
356 .searchPath = searchPath,
357 .roleid = roleid
358 };
359
360 entry = nsphash_lookup(SearchPathCache, cachekey);
361 if (entry)
362 LastSearchPathCacheEntry = entry;
363 return entry;
364 }
365 }
366
367 /*
368 * Look up or insert entry in search path cache.
369 *
370 * Initialize key safely, so that OOM does not leave an entry without a valid
371 * key. Caller must ensure that non-key contents are properly initialized.
372 */
373 static SearchPathCacheEntry *
374 spcache_insert(const char *searchPath, Oid roleid)
375 {
376 if (LastSearchPathCacheEntry &&
377 LastSearchPathCacheEntry->key.roleid == roleid &&
378 strcmp(LastSearchPathCacheEntry->key.searchPath, searchPath) == 0)
379 {
380 return LastSearchPathCacheEntry;
381 }
382 else
383 {
384 SearchPathCacheEntry *entry;
385 SearchPathCacheKey cachekey = {
386 .searchPath = searchPath,
387 .roleid = roleid
388 };
389
390 /*
391 * searchPath is not saved in SearchPathCacheContext. First perform a
392 * lookup, and copy searchPath only if we need to create a new entry.
393 */
394 entry = nsphash_lookup(SearchPathCache, cachekey);
395
396 if (!entry)
397 {
398 bool found;
399
400 cachekey.searchPath = MemoryContextStrdup(SearchPathCacheContext, searchPath);
401 entry = nsphash_insert(SearchPathCache, cachekey, &found);
402 Assert(!found);
403
404 entry->oidlist = NIL;
405 entry->finalPath = NIL;
406 entry->firstNS = InvalidOid;
407 entry->temp_missing = false;
408 entry->forceRecompute = false;
409 /* do not touch entry->status, used by simplehash */
410 }
411
412 LastSearchPathCacheEntry = entry;
413 return entry;
414 }
415 }
416
417 /*
418 * RangeVarGetRelidExtended
419 * Given a RangeVar describing an existing relation,
420 * select the proper namespace and look up the relation OID.
421 *
422 * If the schema or relation is not found, return InvalidOid if flags contains
423 * RVR_MISSING_OK, otherwise raise an error.
424 *
425 * If flags contains RVR_NOWAIT, throw an error if we'd have to wait for a
426 * lock.
427 *
428 * If flags contains RVR_SKIP_LOCKED, return InvalidOid if we'd have to wait
429 * for a lock.
430 *
431 * flags cannot contain both RVR_NOWAIT and RVR_SKIP_LOCKED.
432 *
433 * Note that if RVR_MISSING_OK and RVR_SKIP_LOCKED are both specified, a
434 * return value of InvalidOid could either mean the relation is missing or it
435 * could not be locked.
436 *
437 * Callback allows caller to check permissions or acquire additional locks
438 * prior to grabbing the relation lock.
439 */
440 Oid
441 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
442 uint32 flags,
443 RangeVarGetRelidCallback callback, void *callback_arg)
444 {
445 uint64 inval_count;
446 Oid relId;
447 Oid oldRelId = InvalidOid;
448 bool retry = false;
449 bool missing_ok = (flags & RVR_MISSING_OK) != 0;
450
451 /* verify that flags do no conflict */
452 Assert(!((flags & RVR_NOWAIT) && (flags & RVR_SKIP_LOCKED)));
453
454 /*
455 * We check the catalog name and then ignore it.
456 */
457 if (relation->catalogname)
458 {
459 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
460 ereport(ERROR,
461 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
462 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
463 relation->catalogname, relation->schemaname,
464 relation->relname)));
465 }
466
467 /*
468 * DDL operations can change the results of a name lookup. Since all such
469 * operations will generate invalidation messages, we keep track of
470 * whether any such messages show up while we're performing the operation,
471 * and retry until either (1) no more invalidation messages show up or (2)
472 * the answer doesn't change.
473 *
474 * But if lockmode = NoLock, then we assume that either the caller is OK
475 * with the answer changing under them, or that they already hold some
476 * appropriate lock, and therefore return the first answer we get without
477 * checking for invalidation messages. Also, if the requested lock is
478 * already held, LockRelationOid will not AcceptInvalidationMessages, so
479 * we may fail to notice a change. We could protect against that case by
480 * calling AcceptInvalidationMessages() before beginning this loop, but
481 * that would add a significant amount overhead, so for now we don't.
482 */
483 for (;;)
484 {
485 /*
486 * Remember this value, so that, after looking up the relation name
487 * and locking its OID, we can check whether any invalidation messages
488 * have been processed that might require a do-over.
489 */
490 inval_count = SharedInvalidMessageCounter;
491
492 /*
493 * Some non-default relpersistence value may have been specified. The
494 * parser never generates such a RangeVar in simple DML, but it can
495 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
496 * KEY)". Such a command will generate an added CREATE INDEX
497 * operation, which must be careful to find the temp table, even when
498 * pg_temp is not first in the search path.
499 */
500 if (relation->relpersistence == RELPERSISTENCE_TEMP)
501 {
502 if (!OidIsValid(myTempNamespace))
503 relId = InvalidOid; /* this probably can't happen? */
504 else
505 {
506 if (relation->schemaname)
507 {
508 Oid namespaceId;
509
510 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
511
512 /*
513 * For missing_ok, allow a non-existent schema name to
514 * return InvalidOid.
515 */
516 if (namespaceId != myTempNamespace)
517 ereport(ERROR,
518 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
519 errmsg("temporary tables cannot specify a schema name")));
520 }
521
522 relId = get_relname_relid(relation->relname, myTempNamespace);
523 }
524 }
525 else if (relation->schemaname)
526 {
527 Oid namespaceId;
528
529 /* use exact schema given */
530 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
531 if (missing_ok && !OidIsValid(namespaceId))
532 relId = InvalidOid;
533 else
534 relId = get_relname_relid(relation->relname, namespaceId);
535 }
536 else
537 {
538 /* search the namespace path */
539 relId = RelnameGetRelid(relation->relname);
540 }
541
542 /*
543 * Invoke caller-supplied callback, if any.
544 *
545 * This callback is a good place to check permissions: we haven't
546 * taken the table lock yet (and it's really best to check permissions
547 * before locking anything!), but we've gotten far enough to know what
548 * OID we think we should lock. Of course, concurrent DDL might
549 * change things while we're waiting for the lock, but in that case
550 * the callback will be invoked again for the new OID.
551 */
552 if (callback)
553 callback(relation, relId, oldRelId, callback_arg);
554
555 /*
556 * If no lock requested, we assume the caller knows what they're
557 * doing. They should have already acquired a heavyweight lock on
558 * this relation earlier in the processing of this same statement, so
559 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
560 * that might pull the rug out from under them.
561 */
562 if (lockmode == NoLock)
563 break;
564
565 /*
566 * If, upon retry, we get back the same OID we did last time, then the
567 * invalidation messages we processed did not change the final answer.
568 * So we're done.
569 *
570 * If we got a different OID, we've locked the relation that used to
571 * have this name rather than the one that does now. So release the
572 * lock.
573 */
574 if (retry)
575 {
576 if (relId == oldRelId)
577 break;
578 if (OidIsValid(oldRelId))
579 UnlockRelationOid(oldRelId, lockmode);
580 }
581
582 /*
583 * Lock relation. This will also accept any pending invalidation
584 * messages. If we got back InvalidOid, indicating not found, then
585 * there's nothing to lock, but we accept invalidation messages
586 * anyway, to flush any negative catcache entries that may be
587 * lingering.
588 */
589 if (!OidIsValid(relId))
590 AcceptInvalidationMessages();
591 else if (!(flags & (RVR_NOWAIT | RVR_SKIP_LOCKED)))
592 LockRelationOid(relId, lockmode);
593 else if (!ConditionalLockRelationOid(relId, lockmode))
594 {
595 int elevel = (flags & RVR_SKIP_LOCKED) ? DEBUG1 : ERROR;
596
597 if (relation->schemaname)
598 ereport(elevel,
599 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
600 errmsg("could not obtain lock on relation \"%s.%s\"",
601 relation->schemaname, relation->relname)));
602 else
603 ereport(elevel,
604 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
605 errmsg("could not obtain lock on relation \"%s\"",
606 relation->relname)));
607
608 return InvalidOid;
609 }
610
611 /*
612 * If no invalidation message were processed, we're done!
613 */
614 if (inval_count == SharedInvalidMessageCounter)
615 break;
616
617 /*
618 * Something may have changed. Let's repeat the name lookup, to make
619 * sure this name still references the same relation it did
620 * previously.
621 */
622 retry = true;
623 oldRelId = relId;
624 }
625
626 if (!OidIsValid(relId))
627 {
628 int elevel = missing_ok ? DEBUG1 : ERROR;
629
630 if (relation->schemaname)
631 ereport(elevel,
632 (errcode(ERRCODE_UNDEFINED_TABLE),
633 errmsg("relation \"%s.%s\" does not exist",
634 relation->schemaname, relation->relname)));
635 else
636 ereport(elevel,
637 (errcode(ERRCODE_UNDEFINED_TABLE),
638 errmsg("relation \"%s\" does not exist",
639 relation->relname)));
640 }
641 return relId;
642 }
643
644 /*
645 * RangeVarGetCreationNamespace
646 * Given a RangeVar describing a to-be-created relation,
647 * choose which namespace to create it in.
648 *
649 * Note: calling this may result in a CommandCounterIncrement operation.
650 * That will happen on the first request for a temp table in any particular
651 * backend run; we will need to either create or clean out the temp schema.
652 */
653 Oid
654 RangeVarGetCreationNamespace(const RangeVar *newRelation)
655 {
656 Oid namespaceId;
657
658 /*
659 * We check the catalog name and then ignore it.
660 */
661 if (newRelation->catalogname)
662 {
663 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
664 ereport(ERROR,
665 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
666 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
667 newRelation->catalogname, newRelation->schemaname,
668 newRelation->relname)));
669 }
670
671 if (newRelation->schemaname)
672 {
673 /* check for pg_temp alias */
674 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
675 {
676 /* Initialize temp namespace */
677 AccessTempTableNamespace(false);
678 return myTempNamespace;
679 }
680 /* use exact schema given */
681 namespaceId = get_namespace_oid(newRelation->schemaname, false);
682 /* we do not check for USAGE rights here! */
683 }
684 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
685 {
686 /* Initialize temp namespace */
687 AccessTempTableNamespace(false);
688 return myTempNamespace;
689 }
690 else
691 {
692 /* use the default creation namespace */
693 recomputeNamespacePath();
694 if (activeTempCreationPending)
695 {
696 /* Need to initialize temp namespace */
697 AccessTempTableNamespace(true);
698 return myTempNamespace;
699 }
700 namespaceId = activeCreationNamespace;
701 if (!OidIsValid(namespaceId))
702 ereport(ERROR,
703 (errcode(ERRCODE_UNDEFINED_SCHEMA),
704 errmsg("no schema has been selected to create in")));
705 }
706
707 /* Note: callers will check for CREATE rights when appropriate */
708
709 return namespaceId;
710 }
711
712 /*
713 * RangeVarGetAndCheckCreationNamespace
714 *
715 * This function returns the OID of the namespace in which a new relation
716 * with a given name should be created. If the user does not have CREATE
717 * permission on the target namespace, this function will instead signal
718 * an ERROR.
719 *
720 * If non-NULL, *existing_relation_id is set to the OID of any existing relation
721 * with the same name which already exists in that namespace, or to InvalidOid
722 * if no such relation exists.
723 *
724 * If lockmode != NoLock, the specified lock mode is acquired on the existing
725 * relation, if any, provided that the current user owns the target relation.
726 * However, if lockmode != NoLock and the user does not own the target
727 * relation, we throw an ERROR, as we must not try to lock relations the
728 * user does not have permissions on.
729 *
730 * As a side effect, this function acquires AccessShareLock on the target
731 * namespace. Without this, the namespace could be dropped before our
732 * transaction commits, leaving behind relations with relnamespace pointing
733 * to a no-longer-existent namespace.
734 *
735 * As a further side-effect, if the selected namespace is a temporary namespace,
736 * we mark the RangeVar as RELPERSISTENCE_TEMP.
737 */
738 Oid
739 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
740 LOCKMODE lockmode,
741 Oid *existing_relation_id)
742 {
743 uint64 inval_count;
744 Oid relid;
745 Oid oldrelid = InvalidOid;
746 Oid nspid;
747 Oid oldnspid = InvalidOid;
748 bool retry = false;
749
750 /*
751 * We check the catalog name and then ignore it.
752 */
753 if (relation->catalogname)
754 {
755 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
756 ereport(ERROR,
757 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
758 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
759 relation->catalogname, relation->schemaname,
760 relation->relname)));
761 }
762
763 /*
764 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
765 * operations by tracking whether any invalidation messages are processed
766 * while we're doing the name lookups and acquiring locks. See comments
767 * in that function for a more detailed explanation of this logic.
768 */
769 for (;;)
770 {
771 AclResult aclresult;
772
773 inval_count = SharedInvalidMessageCounter;
774
775 /* Look up creation namespace and check for existing relation. */
776 nspid = RangeVarGetCreationNamespace(relation);
777 Assert(OidIsValid(nspid));
778 if (existing_relation_id != NULL)
779 relid = get_relname_relid(relation->relname, nspid);
780 else
781 relid = InvalidOid;
782
783 /*
784 * In bootstrap processing mode, we don't bother with permissions or
785 * locking. Permissions might not be working yet, and locking is
786 * unnecessary.
787 */
788 if (IsBootstrapProcessingMode())
789 break;
790
791 /* Check namespace permissions. */
792 aclresult = object_aclcheck(NamespaceRelationId, nspid, GetUserId(), ACL_CREATE);
793 if (aclresult != ACLCHECK_OK)
794 aclcheck_error(aclresult, OBJECT_SCHEMA,
795 get_namespace_name(nspid));
796
797 if (retry)
798 {
799 /* If nothing changed, we're done. */
800 if (relid == oldrelid && nspid == oldnspid)
801 break;
802 /* If creation namespace has changed, give up old lock. */
803 if (nspid != oldnspid)
804 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
805 AccessShareLock);
806 /* If name points to something different, give up old lock. */
807 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
808 UnlockRelationOid(oldrelid, lockmode);
809 }
810
811 /* Lock namespace. */
812 if (nspid != oldnspid)
813 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
814
815 /* Lock relation, if required if and we have permission. */
816 if (lockmode != NoLock && OidIsValid(relid))
817 {
818 if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
819 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)),
820 relation->relname);
821 if (relid != oldrelid)
822 LockRelationOid(relid, lockmode);
823 }
824
825 /* If no invalidation message were processed, we're done! */
826 if (inval_count == SharedInvalidMessageCounter)
827 break;
828
829 /* Something may have changed, so recheck our work. */
830 retry = true;
831 oldrelid = relid;
832 oldnspid = nspid;
833 }
834
835 RangeVarAdjustRelationPersistence(relation, nspid);
836 if (existing_relation_id != NULL)
837 *existing_relation_id = relid;
838 return nspid;
839 }
840
841 /*
842 * Adjust the relpersistence for an about-to-be-created relation based on the
843 * creation namespace, and throw an error for invalid combinations.
844 */
845 void
846 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
847 {
848 switch (newRelation->relpersistence)
849 {
850 case RELPERSISTENCE_TEMP:
851 if (!isTempOrTempToastNamespace(nspid))
852 {
853 if (isAnyTempNamespace(nspid))
854 ereport(ERROR,
855 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
856 errmsg("cannot create relations in temporary schemas of other sessions")));
857 else
858 ereport(ERROR,
859 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
860 errmsg("cannot create temporary relation in non-temporary schema")));
861 }
862 break;
863 case RELPERSISTENCE_PERMANENT:
864 if (isTempOrTempToastNamespace(nspid))
865 newRelation->relpersistence = RELPERSISTENCE_TEMP;
866 else if (isAnyTempNamespace(nspid))
867 ereport(ERROR,
868 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
869 errmsg("cannot create relations in temporary schemas of other sessions")));
870 break;
871 default:
872 if (isAnyTempNamespace(nspid))
873 ereport(ERROR,
874 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
875 errmsg("only temporary relations may be created in temporary schemas")));
876 }
877 }
878
879 /*
880 * RelnameGetRelid
881 * Try to resolve an unqualified relation name.
882 * Returns OID if relation found in search path, else InvalidOid.
883 */
884 Oid
885 RelnameGetRelid(const char *relname)
886 {
887 Oid relid;
888 ListCell *l;
889
890 recomputeNamespacePath();
891
892 foreach(l, activeSearchPath)
893 {
894 Oid namespaceId = lfirst_oid(l);
895
896 relid = get_relname_relid(relname, namespaceId);
897 if (OidIsValid(relid))
898 return relid;
899 }
900
901 /* Not found in path */
902 return InvalidOid;
903 }
904
905
906 /*
907 * RelationIsVisible
908 * Determine whether a relation (identified by OID) is visible in the
909 * current search path. Visible means "would be found by searching
910 * for the unqualified relation name".
911 */
912 bool
913 RelationIsVisible(Oid relid)
914 {
915 return RelationIsVisibleExt(relid, NULL);
916 }
917
918 /*
919 * RelationIsVisibleExt
920 * As above, but if the relation isn't found and is_missing is not NULL,
921 * then set *is_missing = true and return false instead of throwing
922 * an error. (Caller must initialize *is_missing = false.)
923 */
924 static bool
925 RelationIsVisibleExt(Oid relid, bool *is_missing)
926 {
927 HeapTuple reltup;
928 Form_pg_class relform;
929 Oid relnamespace;
930 bool visible;
931
932 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
933 if (!HeapTupleIsValid(reltup))
934 {
935 if (is_missing != NULL)
936 {
937 *is_missing = true;
938 return false;
939 }
940 elog(ERROR, "cache lookup failed for relation %u", relid);
941 }
942 relform = (Form_pg_class) GETSTRUCT(reltup);
943
944 recomputeNamespacePath();
945
946 /*
947 * Quick check: if it ain't in the path at all, it ain't visible. Items in
948 * the system namespace are surely in the path and so we needn't even do
949 * list_member_oid() for them.
950 */
951 relnamespace = relform->relnamespace;
952 if (relnamespace != PG_CATALOG_NAMESPACE &&
953 !list_member_oid(activeSearchPath, relnamespace))
954 visible = false;
955 else
956 {
957 /*
958 * If it is in the path, it might still not be visible; it could be
959 * hidden by another relation of the same name earlier in the path. So
960 * we must do a slow check for conflicting relations.
961 */
962 char *relname = NameStr(relform->relname);
963 ListCell *l;
964
965 visible = false;
966 foreach(l, activeSearchPath)
967 {
968 Oid namespaceId = lfirst_oid(l);
969
970 if (namespaceId == relnamespace)
971 {
972 /* Found it first in path */
973 visible = true;
974 break;
975 }
976 if (OidIsValid(get_relname_relid(relname, namespaceId)))
977 {
978 /* Found something else first in path */
979 break;
980 }
981 }
982 }
983
984 ReleaseSysCache(reltup);
985
986 return visible;
987 }
988
989
990 /*
991 * TypenameGetTypid
992 * Wrapper for binary compatibility.
993 */
994 Oid
995 TypenameGetTypid(const char *typname)
996 {
997 return TypenameGetTypidExtended(typname, true);
998 }
999
1000 /*
1001 * TypenameGetTypidExtended
1002 * Try to resolve an unqualified datatype name.
1003 * Returns OID if type found in search path, else InvalidOid.
1004 *
1005 * This is essentially the same as RelnameGetRelid.
1006 */
1007 Oid
1008 TypenameGetTypidExtended(const char *typname, bool temp_ok)
1009 {
1010 Oid typid;
1011 ListCell *l;
1012
1013 recomputeNamespacePath();
1014
1015 foreach(l, activeSearchPath)
1016 {
1017 Oid namespaceId = lfirst_oid(l);
1018
1019 if (!temp_ok && namespaceId == myTempNamespace)
1020 continue; /* do not look in temp namespace */
1021
1022 typid = GetSysCacheOid2(TYPENAMENSP, Anum_pg_type_oid,
1023 PointerGetDatum(typname),
1024 ObjectIdGetDatum(namespaceId));
1025 if (OidIsValid(typid))
1026 return typid;
1027 }
1028
1029 /* Not found in path */
1030 return InvalidOid;
1031 }
1032
1033 /*
1034 * TypeIsVisible
1035 * Determine whether a type (identified by OID) is visible in the
1036 * current search path. Visible means "would be found by searching
1037 * for the unqualified type name".
1038 */
1039 bool
1040 TypeIsVisible(Oid typid)
1041 {
1042 return TypeIsVisibleExt(typid, NULL);
1043 }
1044
1045 /*
1046 * TypeIsVisibleExt
1047 * As above, but if the type isn't found and is_missing is not NULL,
1048 * then set *is_missing = true and return false instead of throwing
1049 * an error. (Caller must initialize *is_missing = false.)
1050 */
1051 static bool
1052 TypeIsVisibleExt(Oid typid, bool *is_missing)
1053 {
1054 HeapTuple typtup;
1055 Form_pg_type typform;
1056 Oid typnamespace;
1057 bool visible;
1058
1059 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
1060 if (!HeapTupleIsValid(typtup))
1061 {
1062 if (is_missing != NULL)
1063 {
1064 *is_missing = true;
1065 return false;
1066 }
1067 elog(ERROR, "cache lookup failed for type %u", typid);
1068 }
1069 typform = (Form_pg_type) GETSTRUCT(typtup);
1070
1071 recomputeNamespacePath();
1072
1073 /*
1074 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1075 * the system namespace are surely in the path and so we needn't even do
1076 * list_member_oid() for them.
1077 */
1078 typnamespace = typform->typnamespace;
1079 if (typnamespace != PG_CATALOG_NAMESPACE &&
1080 !list_member_oid(activeSearchPath, typnamespace))
1081 visible = false;
1082 else
1083 {
1084 /*
1085 * If it is in the path, it might still not be visible; it could be
1086 * hidden by another type of the same name earlier in the path. So we
1087 * must do a slow check for conflicting types.
1088 */
1089 char *typname = NameStr(typform->typname);
1090 ListCell *l;
1091
1092 visible = false;
1093 foreach(l, activeSearchPath)
1094 {
1095 Oid namespaceId = lfirst_oid(l);
1096
1097 if (namespaceId == typnamespace)
1098 {
1099 /* Found it first in path */
1100 visible = true;
1101 break;
1102 }
1103 if (SearchSysCacheExists2(TYPENAMENSP,
1104 PointerGetDatum(typname),
1105 ObjectIdGetDatum(namespaceId)))
1106 {
1107 /* Found something else first in path */
1108 break;
1109 }
1110 }
1111 }
1112
1113 ReleaseSysCache(typtup);
1114
1115 return visible;
1116 }
1117
1118
1119 /*
1120 * FuncnameGetCandidates
1121 * Given a possibly-qualified function name and argument count,
1122 * retrieve a list of the possible matches.
1123 *
1124 * If nargs is -1, we return all functions matching the given name,
1125 * regardless of argument count. (argnames must be NIL, and expand_variadic
1126 * and expand_defaults must be false, in this case.)
1127 *
1128 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
1129 * and only functions having all the listed argument names will be returned.
1130 * (We assume that length(argnames) <= nargs and all the passed-in names are
1131 * distinct.) The returned structs will include an argnumbers array showing
1132 * the actual argument index for each logical argument position.
1133 *
1134 * If expand_variadic is true, then variadic functions having the same number
1135 * or fewer arguments will be retrieved, with the variadic argument and any
1136 * additional argument positions filled with the variadic element type.
1137 * nvargs in the returned struct is set to the number of such arguments.
1138 * If expand_variadic is false, variadic arguments are not treated specially,
1139 * and the returned nvargs will always be zero.
1140 *
1141 * If expand_defaults is true, functions that could match after insertion of
1142 * default argument values will also be retrieved. In this case the returned
1143 * structs could have nargs > passed-in nargs, and ndargs is set to the number
1144 * of additional args (which can be retrieved from the function's
1145 * proargdefaults entry).
1146 *
1147 * If include_out_arguments is true, then OUT-mode arguments are considered to
1148 * be included in the argument list. Their types are included in the returned
1149 * arrays, and argnumbers are indexes in proallargtypes not proargtypes.
1150 * We also set nominalnargs to be the length of proallargtypes not proargtypes.
1151 * Otherwise OUT-mode arguments are ignored.
1152 *
1153 * It is not possible for nvargs and ndargs to both be nonzero in the same
1154 * list entry, since default insertion allows matches to functions with more
1155 * than nargs arguments while the variadic transformation requires the same
1156 * number or less.
1157 *
1158 * When argnames isn't NIL, the returned args[] type arrays are not ordered
1159 * according to the functions' declarations, but rather according to the call:
1160 * first any positional arguments, then the named arguments, then defaulted
1161 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
1162 * array can be used to map this back to the catalog information.
1163 * argnumbers[k] is set to the proargtypes or proallargtypes index of the
1164 * k'th call argument.
1165 *
1166 * We search a single namespace if the function name is qualified, else
1167 * all namespaces in the search path. In the multiple-namespace case,
1168 * we arrange for entries in earlier namespaces to mask identical entries in
1169 * later namespaces.
1170 *
1171 * When expanding variadics, we arrange for non-variadic functions to mask
1172 * variadic ones if the expanded argument list is the same. It is still
1173 * possible for there to be conflicts between different variadic functions,
1174 * however.
1175 *
1176 * It is guaranteed that the return list will never contain multiple entries
1177 * with identical argument lists. When expand_defaults is true, the entries
1178 * could have more than nargs positions, but we still guarantee that they are
1179 * distinct in the first nargs positions. However, if argnames isn't NIL or
1180 * either expand_variadic or expand_defaults is true, there might be multiple
1181 * candidate functions that expand to identical argument lists. Rather than
1182 * throw error here, we report such situations by returning a single entry
1183 * with oid = 0 that represents a set of such conflicting candidates.
1184 * The caller might end up discarding such an entry anyway, but if it selects
1185 * such an entry it should react as though the call were ambiguous.
1186 *
1187 * If missing_ok is true, an empty list (NULL) is returned if the name was
1188 * schema-qualified with a schema that does not exist. Likewise if no
1189 * candidate is found for other reasons.
1190 */
1191 FuncCandidateList
1192 FuncnameGetCandidates(List *names, int nargs, List *argnames,
1193 bool expand_variadic, bool expand_defaults,
1194 bool include_out_arguments, bool missing_ok)
1195 {
1196 FuncCandidateList resultList = NULL;
1197 bool any_special = false;
1198 char *schemaname;
1199 char *funcname;
1200 Oid namespaceId;
1201 CatCList *catlist;
1202 int i;
1203
1204 /* check for caller error */
1205 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
1206
1207 /* deconstruct the name list */
1208 DeconstructQualifiedName(names, &schemaname, &funcname);
1209
1210 if (schemaname)
1211 {
1212 /* use exact schema given */
1213 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
1214 if (!OidIsValid(namespaceId))
1215 return NULL;
1216 }
1217 else
1218 {
1219 /* flag to indicate we need namespace search */
1220 namespaceId = InvalidOid;
1221 recomputeNamespacePath();
1222 }
1223
1224 /* Search syscache by name only */
1225 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
1226
1227 for (i = 0; i < catlist->n_members; i++)
1228 {
1229 HeapTuple proctup = &catlist->members[i]->tuple;
1230 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1231 Oid *proargtypes = procform->proargtypes.values;
1232 int pronargs = procform->pronargs;
1233 int effective_nargs;
1234 int pathpos = 0;
1235 bool variadic;
1236 bool use_defaults;
1237 Oid va_elem_type;
1238 int *argnumbers = NULL;
1239 FuncCandidateList newResult;
1240
1241 if (OidIsValid(namespaceId))
1242 {
1243 /* Consider only procs in specified namespace */
1244 if (procform->pronamespace != namespaceId)
1245 continue;
1246 }
1247 else
1248 {
1249 /*
1250 * Consider only procs that are in the search path and are not in
1251 * the temp namespace.
1252 */
1253 ListCell *nsp;
1254
1255 foreach(nsp, activeSearchPath)
1256 {
1257 if (procform->pronamespace == lfirst_oid(nsp) &&
1258 procform->pronamespace != myTempNamespace)
1259 break;
1260 pathpos++;
1261 }
1262 if (nsp == NULL)
1263 continue; /* proc is not in search path */
1264 }
1265
1266 /*
1267 * If we are asked to match to OUT arguments, then use the
1268 * proallargtypes array (which includes those); otherwise use
1269 * proargtypes (which doesn't). Of course, if proallargtypes is null,
1270 * we always use proargtypes.
1271 */
1272 if (include_out_arguments)
1273 {
1274 Datum proallargtypes;
1275 bool isNull;
1276
1277 proallargtypes = SysCacheGetAttr(PROCNAMEARGSNSP, proctup,
1278 Anum_pg_proc_proallargtypes,
1279 &isNull);
1280 if (!isNull)
1281 {
1282 ArrayType *arr = DatumGetArrayTypeP(proallargtypes);
1283
1284 pronargs = ARR_DIMS(arr)[0];
1285 if (ARR_NDIM(arr) != 1 ||
1286 pronargs < 0 ||
1287 ARR_HASNULL(arr) ||
1288 ARR_ELEMTYPE(arr) != OIDOID)
1289 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
1290 Assert(pronargs >= procform->pronargs);
1291 proargtypes = (Oid *) ARR_DATA_PTR(arr);
1292 }
1293 }
1294
1295 if (argnames != NIL)
1296 {
1297 /*
1298 * Call uses named or mixed notation
1299 *
1300 * Named or mixed notation can match a variadic function only if
1301 * expand_variadic is off; otherwise there is no way to match the
1302 * presumed-nameless parameters expanded from the variadic array.
1303 */
1304 if (OidIsValid(procform->provariadic) && expand_variadic)
1305 continue;
1306 va_elem_type = InvalidOid;
1307 variadic = false;
1308
1309 /*
1310 * Check argument count.
1311 */
1312 Assert(nargs >= 0); /* -1 not supported with argnames */
1313
1314 if (pronargs > nargs && expand_defaults)
1315 {
1316 /* Ignore if not enough default expressions */
1317 if (nargs + procform->pronargdefaults < pronargs)
1318 continue;
1319 use_defaults = true;
1320 }
1321 else
1322 use_defaults = false;
1323
1324 /* Ignore if it doesn't match requested argument count */
1325 if (pronargs != nargs && !use_defaults)
1326 continue;
1327
1328 /* Check for argument name match, generate positional mapping */
1329 if (!MatchNamedCall(proctup, nargs, argnames,
1330 include_out_arguments, pronargs,
1331 &argnumbers))
1332 continue;
1333
1334 /* Named argument matching is always "special" */
1335 any_special = true;
1336 }
1337 else
1338 {
1339 /*
1340 * Call uses positional notation
1341 *
1342 * Check if function is variadic, and get variadic element type if
1343 * so. If expand_variadic is false, we should just ignore
1344 * variadic-ness.
1345 */
1346 if (pronargs <= nargs && expand_variadic)
1347 {
1348 va_elem_type = procform->provariadic;
1349 variadic = OidIsValid(va_elem_type);
1350 any_special |= variadic;
1351 }
1352 else
1353 {
1354 va_elem_type = InvalidOid;
1355 variadic = false;
1356 }
1357
1358 /*
1359 * Check if function can match by using parameter defaults.
1360 */
1361 if (pronargs > nargs && expand_defaults)
1362 {
1363 /* Ignore if not enough default expressions */
1364 if (nargs + procform->pronargdefaults < pronargs)
1365 continue;
1366 use_defaults = true;
1367 any_special = true;
1368 }
1369 else
1370 use_defaults = false;
1371
1372 /* Ignore if it doesn't match requested argument count */
1373 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1374 continue;
1375 }
1376
1377 /*
1378 * We must compute the effective argument list so that we can easily
1379 * compare it to earlier results. We waste a palloc cycle if it gets
1380 * masked by an earlier result, but really that's a pretty infrequent
1381 * case so it's not worth worrying about.
1382 */
1383 effective_nargs = Max(pronargs, nargs);
1384 newResult = (FuncCandidateList)
1385 palloc(offsetof(struct _FuncCandidateList, args) +
1386 effective_nargs * sizeof(Oid));
1387 newResult->pathpos = pathpos;
1388 newResult->oid = procform->oid;
1389 newResult->nominalnargs = pronargs;
1390 newResult->nargs = effective_nargs;
1391 newResult->argnumbers = argnumbers;
1392 if (argnumbers)
1393 {
1394 /* Re-order the argument types into call's logical order */
1395 for (int j = 0; j < pronargs; j++)
1396 newResult->args[j] = proargtypes[argnumbers[j]];
1397 }
1398 else
1399 {
1400 /* Simple positional case, just copy proargtypes as-is */
1401 memcpy(newResult->args, proargtypes, pronargs * sizeof(Oid));
1402 }
1403 if (variadic)
1404 {
1405 newResult->nvargs = effective_nargs - pronargs + 1;
1406 /* Expand variadic argument into N copies of element type */
1407 for (int j = pronargs - 1; j < effective_nargs; j++)
1408 newResult->args[j] = va_elem_type;
1409 }
1410 else
1411 newResult->nvargs = 0;
1412 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1413
1414 /*
1415 * Does it have the same arguments as something we already accepted?
1416 * If so, decide what to do to avoid returning duplicate argument
1417 * lists. We can skip this check for the single-namespace case if no
1418 * special (named, variadic or defaults) match has been made, since
1419 * then the unique index on pg_proc guarantees all the matches have
1420 * different argument lists.
1421 */
1422 if (resultList != NULL &&
1423 (any_special || !OidIsValid(namespaceId)))
1424 {
1425 /*
1426 * If we have an ordered list from SearchSysCacheList (the normal
1427 * case), then any conflicting proc must immediately adjoin this
1428 * one in the list, so we only need to look at the newest result
1429 * item. If we have an unordered list, we have to scan the whole
1430 * result list. Also, if either the current candidate or any
1431 * previous candidate is a special match, we can't assume that
1432 * conflicts are adjacent.
1433 *
1434 * We ignore defaulted arguments in deciding what is a match.
1435 */
1436 FuncCandidateList prevResult;
1437
1438 if (catlist->ordered && !any_special)
1439 {
1440 /* ndargs must be 0 if !any_special */
1441 if (effective_nargs == resultList->nargs &&
1442 memcmp(newResult->args,
1443 resultList->args,
1444 effective_nargs * sizeof(Oid)) == 0)
1445 prevResult = resultList;
1446 else
1447 prevResult = NULL;
1448 }
1449 else
1450 {
1451 int cmp_nargs = newResult->nargs - newResult->ndargs;
1452
1453 for (prevResult = resultList;
1454 prevResult;
1455 prevResult = prevResult->next)
1456 {
1457 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1458 memcmp(newResult->args,
1459 prevResult->args,
1460 cmp_nargs * sizeof(Oid)) == 0)
1461 break;
1462 }
1463 }
1464
1465 if (prevResult)
1466 {
1467 /*
1468 * We have a match with a previous result. Decide which one
1469 * to keep, or mark it ambiguous if we can't decide. The
1470 * logic here is preference > 0 means prefer the old result,
1471 * preference < 0 means prefer the new, preference = 0 means
1472 * ambiguous.
1473 */
1474 int preference;
1475
1476 if (pathpos != prevResult->pathpos)
1477 {
1478 /*
1479 * Prefer the one that's earlier in the search path.
1480 */
1481 preference = pathpos - prevResult->pathpos;
1482 }
1483 else if (variadic && prevResult->nvargs == 0)
1484 {
1485 /*
1486 * With variadic functions we could have, for example,
1487 * both foo(numeric) and foo(variadic numeric[]) in the
1488 * same namespace; if so we prefer the non-variadic match
1489 * on efficiency grounds.
1490 */
1491 preference = 1;
1492 }
1493 else if (!variadic && prevResult->nvargs > 0)
1494 {
1495 preference = -1;
1496 }
1497 else
1498 {
1499 /*----------
1500 * We can't decide. This can happen with, for example,
1501 * both foo(numeric, variadic numeric[]) and
1502 * foo(variadic numeric[]) in the same namespace, or
1503 * both foo(int) and foo (int, int default something)
1504 * in the same namespace, or both foo(a int, b text)
1505 * and foo(b text, a int) in the same namespace.
1506 *----------
1507 */
1508 preference = 0;
1509 }
1510
1511 if (preference > 0)
1512 {
1513 /* keep previous result */
1514 pfree(newResult);
1515 continue;
1516 }
1517 else if (preference < 0)
1518 {
1519 /* remove previous result from the list */
1520 if (prevResult == resultList)
1521 resultList = prevResult->next;
1522 else
1523 {
1524 FuncCandidateList prevPrevResult;
1525
1526 for (prevPrevResult = resultList;
1527 prevPrevResult;
1528 prevPrevResult = prevPrevResult->next)
1529 {
1530 if (prevResult == prevPrevResult->next)
1531 {
1532 prevPrevResult->next = prevResult->next;
1533 break;
1534 }
1535 }
1536 Assert(prevPrevResult); /* assert we found it */
1537 }
1538 pfree(prevResult);
1539 /* fall through to add newResult to list */
1540 }
1541 else
1542 {
1543 /* mark old result as ambiguous, discard new */
1544 prevResult->oid = InvalidOid;
1545 pfree(newResult);
1546 continue;
1547 }
1548 }
1549 }
1550
1551 /*
1552 * Okay to add it to result list
1553 */
1554 newResult->next = resultList;
1555 resultList = newResult;
1556 }
1557
1558 ReleaseSysCacheList(catlist);
1559
1560 return resultList;
1561 }
1562
1563 /*
1564 * MatchNamedCall
1565 * Given a pg_proc heap tuple and a call's list of argument names,
1566 * check whether the function could match the call.
1567 *
1568 * The call could match if all supplied argument names are accepted by
1569 * the function, in positions after the last positional argument, and there
1570 * are defaults for all unsupplied arguments.
1571 *
1572 * If include_out_arguments is true, we are treating OUT arguments as
1573 * included in the argument list. pronargs is the number of arguments
1574 * we're considering (the length of either proargtypes or proallargtypes).
1575 *
1576 * The number of positional arguments is nargs - list_length(argnames).
1577 * Note caller has already done basic checks on argument count.
1578 *
1579 * On match, return true and fill *argnumbers with a palloc'd array showing
1580 * the mapping from call argument positions to actual function argument
1581 * numbers. Defaulted arguments are included in this map, at positions
1582 * after the last supplied argument.
1583 */
1584 static bool
1585 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1586 bool include_out_arguments, int pronargs,
1587 int **argnumbers)
1588 {
1589 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1590 int numposargs = nargs - list_length(argnames);
1591 int pronallargs;
1592 Oid *p_argtypes;
1593 char **p_argnames;
1594 char *p_argmodes;
1595 bool *arggiven;
1596 bool isnull;
1597 int ap; /* call args position */
1598 int pp; /* proargs position */
1599 ListCell *lc;
1600
1601 Assert(argnames != NIL);
1602 Assert(numposargs >= 0);
1603 Assert(nargs <= pronargs);
1604
1605 /* Ignore this function if its proargnames is null */
1606 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1607 &isnull);
1608 if (isnull)
1609 return false;
1610
1611 /* OK, let's extract the argument names and types */
1612 pronallargs = get_func_arg_info(proctup,
1613 &p_argtypes, &p_argnames, &p_argmodes);
1614 Assert(p_argnames != NULL);
1615
1616 Assert(include_out_arguments ? (pronargs == pronallargs) : (pronargs <= pronallargs));
1617
1618 /* initialize state for matching */
1619 *argnumbers = palloc_array(int, pronargs);
1620 arggiven = palloc0_array(bool, pronallargs);
1621
1622 /* there are numposargs positional args before the named args */
1623 for (ap = 0; ap < numposargs; ap++)
1624 {
1625 (*argnumbers)[ap] = ap;
1626 arggiven[ap] = true;
1627 }
1628
1629 /* now examine the named args */
1630 foreach(lc, argnames)
1631 {
1632 char *argname = (char *) lfirst(lc);
1633 bool found;
1634 int i;
1635
1636 pp = 0;
1637 found = false;
1638 for (i = 0; i < pronallargs; i++)
1639 {
1640 /* consider only input params, except with include_out_arguments */
1641 if (!include_out_arguments &&
1642 p_argmodes &&
1643 (p_argmodes[i] != FUNC_PARAM_IN &&
1644 p_argmodes[i] != FUNC_PARAM_INOUT &&
1645 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1646 continue;
1647 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1648 {
1649 /* fail if argname matches a positional argument */
1650 if (arggiven[pp])
1651 return false;
1652 arggiven[pp] = true;
1653 (*argnumbers)[ap] = pp;
1654 found = true;
1655 break;
1656 }
1657 /* increase pp only for considered parameters */
1658 pp++;
1659 }
1660 /* if name isn't in proargnames, fail */
1661 if (!found)
1662 return false;
1663 ap++;
1664 }
1665
1666 Assert(ap == nargs); /* processed all actual parameters */
1667
1668 /* Check for default arguments */
1669 if (nargs < pronargs)
1670 {
1671 int first_arg_with_default = pronargs - procform->pronargdefaults;
1672
1673 for (pp = numposargs; pp < pronargs; pp++)
1674 {
1675 if (arggiven[pp])
1676 continue;
1677 /* fail if arg not given and no default available */
1678 if (pp < first_arg_with_default)
1679 return false;
1680 (*argnumbers)[ap++] = pp;
1681 }
1682 }
1683
1684 Assert(ap == pronargs); /* processed all function parameters */
1685
1686 return true;
1687 }
1688
1689 /*
1690 * FunctionIsVisible
1691 * Determine whether a function (identified by OID) is visible in the
1692 * current search path. Visible means "would be found by searching
1693 * for the unqualified function name with exact argument matches".
1694 */
1695 bool
1696 FunctionIsVisible(Oid funcid)
1697 {
1698 return FunctionIsVisibleExt(funcid, NULL);
1699 }
1700
1701 /*
1702 * FunctionIsVisibleExt
1703 * As above, but if the function isn't found and is_missing is not NULL,
1704 * then set *is_missing = true and return false instead of throwing
1705 * an error. (Caller must initialize *is_missing = false.)
1706 */
1707 static bool
1708 FunctionIsVisibleExt(Oid funcid, bool *is_missing)
1709 {
1710 HeapTuple proctup;
1711 Form_pg_proc procform;
1712 Oid pronamespace;
1713 bool visible;
1714
1715 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1716 if (!HeapTupleIsValid(proctup))
1717 {
1718 if (is_missing != NULL)
1719 {
1720 *is_missing = true;
1721 return false;
1722 }
1723 elog(ERROR, "cache lookup failed for function %u", funcid);
1724 }
1725 procform = (Form_pg_proc) GETSTRUCT(proctup);
1726
1727 recomputeNamespacePath();
1728
1729 /*
1730 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1731 * the system namespace are surely in the path and so we needn't even do
1732 * list_member_oid() for them.
1733 */
1734 pronamespace = procform->pronamespace;
1735 if (pronamespace != PG_CATALOG_NAMESPACE &&
1736 !list_member_oid(activeSearchPath, pronamespace))
1737 visible = false;
1738 else
1739 {
1740 /*
1741 * If it is in the path, it might still not be visible; it could be
1742 * hidden by another proc of the same name and arguments earlier in
1743 * the path. So we must do a slow check to see if this is the same
1744 * proc that would be found by FuncnameGetCandidates.
1745 */
1746 char *proname = NameStr(procform->proname);
1747 int nargs = procform->pronargs;
1748 FuncCandidateList clist;
1749
1750 visible = false;
1751
1752 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1753 nargs, NIL, false, false, false, false);
1754
1755 for (; clist; clist = clist->next)
1756 {
1757 if (memcmp(clist->args, procform->proargtypes.values,
1758 nargs * sizeof(Oid)) == 0)
1759 {
1760 /* Found the expected entry; is it the right proc? */
1761 visible = (clist->oid == funcid);
1762 break;
1763 }
1764 }
1765 }
1766
1767 ReleaseSysCache(proctup);
1768
1769 return visible;
1770 }
1771
1772
1773 /*
1774 * OpernameGetOprid
1775 * Given a possibly-qualified operator name and exact input datatypes,
1776 * look up the operator. Returns InvalidOid if not found.
1777 *
1778 * Pass oprleft = InvalidOid for a prefix op.
1779 *
1780 * If the operator name is not schema-qualified, it is sought in the current
1781 * namespace search path. If the name is schema-qualified and the given
1782 * schema does not exist, InvalidOid is returned.
1783 */
1784 Oid
1785 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1786 {
1787 char *schemaname;
1788 char *opername;
1789 CatCList *catlist;
1790 ListCell *l;
1791
1792 /* deconstruct the name list */
1793 DeconstructQualifiedName(names, &schemaname, &opername);
1794
1795 if (schemaname)
1796 {
1797 /* search only in exact schema given */
1798 Oid namespaceId;
1799
1800 namespaceId = LookupExplicitNamespace(schemaname, true);
1801 if (OidIsValid(namespaceId))
1802 {
1803 HeapTuple opertup;
1804
1805 opertup = SearchSysCache4(OPERNAMENSP,
1806 CStringGetDatum(opername),
1807 ObjectIdGetDatum(oprleft),
1808 ObjectIdGetDatum(oprright),
1809 ObjectIdGetDatum(namespaceId));
1810 if (HeapTupleIsValid(opertup))
1811 {
1812 Form_pg_operator operclass = (Form_pg_operator) GETSTRUCT(opertup);
1813 Oid result = operclass->oid;
1814
1815 ReleaseSysCache(opertup);
1816 return result;
1817 }
1818 }
1819
1820 return InvalidOid;
1821 }
1822
1823 /* Search syscache by name and argument types */
1824 catlist = SearchSysCacheList3(OPERNAMENSP,
1825 CStringGetDatum(opername),
1826 ObjectIdGetDatum(oprleft),
1827 ObjectIdGetDatum(oprright));
1828
1829 if (catlist->n_members == 0)
1830 {
1831 /* no hope, fall out early */
1832 ReleaseSysCacheList(catlist);
1833 return InvalidOid;
1834 }
1835
1836 /*
1837 * We have to find the list member that is first in the search path, if
1838 * there's more than one. This doubly-nested loop looks ugly, but in
1839 * practice there should usually be few catlist members.
1840 */
1841 recomputeNamespacePath();
1842
1843 foreach(l, activeSearchPath)
1844 {
1845 Oid namespaceId = lfirst_oid(l);
1846 int i;
1847
1848 if (namespaceId == myTempNamespace)
1849 continue; /* do not look in temp namespace */
1850
1851 for (i = 0; i < catlist->n_members; i++)
1852 {
1853 HeapTuple opertup = &catlist->members[i]->tuple;
1854 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1855
1856 if (operform->oprnamespace == namespaceId)
1857 {
1858 Oid result = operform->oid;
1859
1860 ReleaseSysCacheList(catlist);
1861 return result;
1862 }
1863 }
1864 }
1865
1866 ReleaseSysCacheList(catlist);
1867 return InvalidOid;
1868 }
1869
1870 /*
1871 * OpernameGetCandidates
1872 * Given a possibly-qualified operator name and operator kind,
1873 * retrieve a list of the possible matches.
1874 *
1875 * If oprkind is '\0', we return all operators matching the given name,
1876 * regardless of arguments.
1877 *
1878 * We search a single namespace if the operator name is qualified, else
1879 * all namespaces in the search path. The return list will never contain
1880 * multiple entries with identical argument lists --- in the multiple-
1881 * namespace case, we arrange for entries in earlier namespaces to mask
1882 * identical entries in later namespaces.
1883 *
1884 * The returned items always have two args[] entries --- the first will be
1885 * InvalidOid for a prefix oprkind. nargs is always 2, too.
1886 */
1887 FuncCandidateList
1888 OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
1889 {
1890 FuncCandidateList resultList = NULL;
1891 char *resultSpace = NULL;
1892 int nextResult = 0;
1893 char *schemaname;
1894 char *opername;
1895 Oid namespaceId;
1896 CatCList *catlist;
1897 int i;
1898
1899 /* deconstruct the name list */
1900 DeconstructQualifiedName(names, &schemaname, &opername);
1901
1902 if (schemaname)
1903 {
1904 /* use exact schema given */
1905 namespaceId = LookupExplicitNamespace(schemaname, missing_schema_ok);
1906 if (missing_schema_ok && !OidIsValid(namespaceId))
1907 return NULL;
1908 }
1909 else
1910 {
1911 /* flag to indicate we need namespace search */
1912 namespaceId = InvalidOid;
1913 recomputeNamespacePath();
1914 }
1915
1916 /* Search syscache by name only */
1917 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1918
1919 /*
1920 * In typical scenarios, most if not all of the operators found by the
1921 * catcache search will end up getting returned; and there can be quite a
1922 * few, for common operator names such as '=' or '+'. To reduce the time
1923 * spent in palloc, we allocate the result space as an array large enough
1924 * to hold all the operators. The original coding of this routine did a
1925 * separate palloc for each operator, but profiling revealed that the
1926 * pallocs used an unreasonably large fraction of parsing time.
1927 */
1928 #define SPACE_PER_OP MAXALIGN(offsetof(struct _FuncCandidateList, args) + \
1929 2 * sizeof(Oid))
1930
1931 if (catlist->n_members > 0)
1932 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1933
1934 for (i = 0; i < catlist->n_members; i++)
1935 {
1936 HeapTuple opertup = &catlist->members[i]->tuple;
1937 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1938 int pathpos = 0;
1939 FuncCandidateList newResult;
1940
1941 /* Ignore operators of wrong kind, if specific kind requested */
1942 if (oprkind && operform->oprkind != oprkind)
1943 continue;
1944
1945 if (OidIsValid(namespaceId))
1946 {
1947 /* Consider only opers in specified namespace */
1948 if (operform->oprnamespace != namespaceId)
1949 continue;
1950 /* No need to check args, they must all be different */
1951 }
1952 else
1953 {
1954 /*
1955 * Consider only opers that are in the search path and are not in
1956 * the temp namespace.
1957 */
1958 ListCell *nsp;
1959
1960 foreach(nsp, activeSearchPath)
1961 {
1962 if (operform->oprnamespace == lfirst_oid(nsp) &&
1963 operform->oprnamespace != myTempNamespace)
1964 break;
1965 pathpos++;
1966 }
1967 if (nsp == NULL)
1968 continue; /* oper is not in search path */
1969
1970 /*
1971 * Okay, it's in the search path, but does it have the same
1972 * arguments as something we already accepted? If so, keep only
1973 * the one that appears earlier in the search path.
1974 *
1975 * If we have an ordered list from SearchSysCacheList (the normal
1976 * case), then any conflicting oper must immediately adjoin this
1977 * one in the list, so we only need to look at the newest result
1978 * item. If we have an unordered list, we have to scan the whole
1979 * result list.
1980 */
1981 if (resultList)
1982 {
1983 FuncCandidateList prevResult;
1984
1985 if (catlist->ordered)
1986 {
1987 if (operform->oprleft == resultList->args[0] &&
1988 operform->oprright == resultList->args[1])
1989 prevResult = resultList;
1990 else
1991 prevResult = NULL;
1992 }
1993 else
1994 {
1995 for (prevResult = resultList;
1996 prevResult;
1997 prevResult = prevResult->next)
1998 {
1999 if (operform->oprleft == prevResult->args[0] &&
2000 operform->oprright == prevResult->args[1])
2001 break;
2002 }
2003 }
2004 if (prevResult)
2005 {
2006 /* We have a match with a previous result */
2007 Assert(pathpos != prevResult->pathpos);
2008 if (pathpos > prevResult->pathpos)
2009 continue; /* keep previous result */
2010 /* replace previous result */
2011 prevResult->pathpos = pathpos;
2012 prevResult->oid = operform->oid;
2013 continue; /* args are same, of course */
2014 }
2015 }
2016 }
2017
2018 /*
2019 * Okay to add it to result list
2020 */
2021 newResult = (FuncCandidateList) (resultSpace + nextResult);
2022 nextResult += SPACE_PER_OP;
2023
2024 newResult->pathpos = pathpos;
2025 newResult->oid = operform->oid;
2026 newResult->nominalnargs = 2;
2027 newResult->nargs = 2;
2028 newResult->nvargs = 0;
2029 newResult->ndargs = 0;
2030 newResult->argnumbers = NULL;
2031 newResult->args[0] = operform->oprleft;
2032 newResult->args[1] = operform->oprright;
2033 newResult->next = resultList;
2034 resultList = newResult;
2035 }
2036
2037 ReleaseSysCacheList(catlist);
2038
2039 return resultList;
2040 }
2041
2042 /*
2043 * OperatorIsVisible
2044 * Determine whether an operator (identified by OID) is visible in the
2045 * current search path. Visible means "would be found by searching
2046 * for the unqualified operator name with exact argument matches".
2047 */
2048 bool
2049 OperatorIsVisible(Oid oprid)
2050 {
2051 return OperatorIsVisibleExt(oprid, NULL);
2052 }
2053
2054 /*
2055 * OperatorIsVisibleExt
2056 * As above, but if the operator isn't found and is_missing is not NULL,
2057 * then set *is_missing = true and return false instead of throwing
2058 * an error. (Caller must initialize *is_missing = false.)
2059 */
2060 static bool
2061 OperatorIsVisibleExt(Oid oprid, bool *is_missing)
2062 {
2063 HeapTuple oprtup;
2064 Form_pg_operator oprform;
2065 Oid oprnamespace;
2066 bool visible;
2067
2068 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
2069 if (!HeapTupleIsValid(oprtup))
2070 {
2071 if (is_missing != NULL)
2072 {
2073 *is_missing = true;
2074 return false;
2075 }
2076 elog(ERROR, "cache lookup failed for operator %u", oprid);
2077 }
2078 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
2079
2080 recomputeNamespacePath();
2081
2082 /*
2083 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2084 * the system namespace are surely in the path and so we needn't even do
2085 * list_member_oid() for them.
2086 */
2087 oprnamespace = oprform->oprnamespace;
2088 if (oprnamespace != PG_CATALOG_NAMESPACE &&
2089 !list_member_oid(activeSearchPath, oprnamespace))
2090 visible = false;
2091 else
2092 {
2093 /*
2094 * If it is in the path, it might still not be visible; it could be
2095 * hidden by another operator of the same name and arguments earlier
2096 * in the path. So we must do a slow check to see if this is the same
2097 * operator that would be found by OpernameGetOprid.
2098 */
2099 char *oprname = NameStr(oprform->oprname);
2100
2101 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
2102 oprform->oprleft, oprform->oprright)
2103 == oprid);
2104 }
2105
2106 ReleaseSysCache(oprtup);
2107
2108 return visible;
2109 }
2110
2111
2112 /*
2113 * OpclassnameGetOpcid
2114 * Try to resolve an unqualified index opclass name.
2115 * Returns OID if opclass found in search path, else InvalidOid.
2116 *
2117 * This is essentially the same as TypenameGetTypid, but we have to have
2118 * an extra argument for the index AM OID.
2119 */
2120 Oid
2121 OpclassnameGetOpcid(Oid amid, const char *opcname)
2122 {
2123 Oid opcid;
2124 ListCell *l;
2125
2126 recomputeNamespacePath();
2127
2128 foreach(l, activeSearchPath)
2129 {
2130 Oid namespaceId = lfirst_oid(l);
2131
2132 if (namespaceId == myTempNamespace)
2133 continue; /* do not look in temp namespace */
2134
2135 opcid = GetSysCacheOid3(CLAAMNAMENSP, Anum_pg_opclass_oid,
2136 ObjectIdGetDatum(amid),
2137 PointerGetDatum(opcname),
2138 ObjectIdGetDatum(namespaceId));
2139 if (OidIsValid(opcid))
2140 return opcid;
2141 }
2142
2143 /* Not found in path */
2144 return InvalidOid;
2145 }
2146
2147 /*
2148 * OpclassIsVisible
2149 * Determine whether an opclass (identified by OID) is visible in the
2150 * current search path. Visible means "would be found by searching
2151 * for the unqualified opclass name".
2152 */
2153 bool
2154 OpclassIsVisible(Oid opcid)
2155 {
2156 return OpclassIsVisibleExt(opcid, NULL);
2157 }
2158
2159 /*
2160 * OpclassIsVisibleExt
2161 * As above, but if the opclass isn't found and is_missing is not NULL,
2162 * then set *is_missing = true and return false instead of throwing
2163 * an error. (Caller must initialize *is_missing = false.)
2164 */
2165 static bool
2166 OpclassIsVisibleExt(Oid opcid, bool *is_missing)
2167 {
2168 HeapTuple opctup;
2169 Form_pg_opclass opcform;
2170 Oid opcnamespace;
2171 bool visible;
2172
2173 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
2174 if (!HeapTupleIsValid(opctup))
2175 {
2176 if (is_missing != NULL)
2177 {
2178 *is_missing = true;
2179 return false;
2180 }
2181 elog(ERROR, "cache lookup failed for opclass %u", opcid);
2182 }
2183 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
2184
2185 recomputeNamespacePath();
2186
2187 /*
2188 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2189 * the system namespace are surely in the path and so we needn't even do
2190 * list_member_oid() for them.
2191 */
2192 opcnamespace = opcform->opcnamespace;
2193 if (opcnamespace != PG_CATALOG_NAMESPACE &&
2194 !list_member_oid(activeSearchPath, opcnamespace))
2195 visible = false;
2196 else
2197 {
2198 /*
2199 * If it is in the path, it might still not be visible; it could be
2200 * hidden by another opclass of the same name earlier in the path. So
2201 * we must do a slow check to see if this opclass would be found by
2202 * OpclassnameGetOpcid.
2203 */
2204 char *opcname = NameStr(opcform->opcname);
2205
2206 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
2207 }
2208
2209 ReleaseSysCache(opctup);
2210
2211 return visible;
2212 }
2213
2214 /*
2215 * OpfamilynameGetOpfid
2216 * Try to resolve an unqualified index opfamily name.
2217 * Returns OID if opfamily found in search path, else InvalidOid.
2218 *
2219 * This is essentially the same as TypenameGetTypid, but we have to have
2220 * an extra argument for the index AM OID.
2221 */
2222 Oid
2223 OpfamilynameGetOpfid(Oid amid, const char *opfname)
2224 {
2225 Oid opfid;
2226 ListCell *l;
2227
2228 recomputeNamespacePath();
2229
2230 foreach(l, activeSearchPath)
2231 {
2232 Oid namespaceId = lfirst_oid(l);
2233
2234 if (namespaceId == myTempNamespace)
2235 continue; /* do not look in temp namespace */
2236
2237 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP, Anum_pg_opfamily_oid,
2238 ObjectIdGetDatum(amid),
2239 PointerGetDatum(opfname),
2240 ObjectIdGetDatum(namespaceId));
2241 if (OidIsValid(opfid))
2242 return opfid;
2243 }
2244
2245 /* Not found in path */
2246 return InvalidOid;
2247 }
2248
2249 /*
2250 * OpfamilyIsVisible
2251 * Determine whether an opfamily (identified by OID) is visible in the
2252 * current search path. Visible means "would be found by searching
2253 * for the unqualified opfamily name".
2254 */
2255 bool
2256 OpfamilyIsVisible(Oid opfid)
2257 {
2258 return OpfamilyIsVisibleExt(opfid, NULL);
2259 }
2260
2261 /*
2262 * OpfamilyIsVisibleExt
2263 * As above, but if the opfamily isn't found and is_missing is not NULL,
2264 * then set *is_missing = true and return false instead of throwing
2265 * an error. (Caller must initialize *is_missing = false.)
2266 */
2267 static bool
2268 OpfamilyIsVisibleExt(Oid opfid, bool *is_missing)
2269 {
2270 HeapTuple opftup;
2271 Form_pg_opfamily opfform;
2272 Oid opfnamespace;
2273 bool visible;
2274
2275 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
2276 if (!HeapTupleIsValid(opftup))
2277 {
2278 if (is_missing != NULL)
2279 {
2280 *is_missing = true;
2281 return false;
2282 }
2283 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
2284 }
2285 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
2286
2287 recomputeNamespacePath();
2288
2289 /*
2290 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2291 * the system namespace are surely in the path and so we needn't even do
2292 * list_member_oid() for them.
2293 */
2294 opfnamespace = opfform->opfnamespace;
2295 if (opfnamespace != PG_CATALOG_NAMESPACE &&
2296 !list_member_oid(activeSearchPath, opfnamespace))
2297 visible = false;
2298 else
2299 {
2300 /*
2301 * If it is in the path, it might still not be visible; it could be
2302 * hidden by another opfamily of the same name earlier in the path. So
2303 * we must do a slow check to see if this opfamily would be found by
2304 * OpfamilynameGetOpfid.
2305 */
2306 char *opfname = NameStr(opfform->opfname);
2307
2308 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
2309 }
2310
2311 ReleaseSysCache(opftup);
2312
2313 return visible;
2314 }
2315
2316 /*
2317 * lookup_collation
2318 * If there's a collation of the given name/namespace, and it works
2319 * with the given encoding, return its OID. Else return InvalidOid.
2320 */
2321 static Oid
2322 lookup_collation(const char *collname, Oid collnamespace, int32 encoding)
2323 {
2324 Oid collid;
2325 HeapTuple colltup;
2326 Form_pg_collation collform;
2327
2328 /* Check for encoding-specific entry (exact match) */
2329 collid = GetSysCacheOid3(COLLNAMEENCNSP, Anum_pg_collation_oid,
2330 PointerGetDatum(collname),
2331 Int32GetDatum(encoding),
2332 ObjectIdGetDatum(collnamespace));
2333 if (OidIsValid(collid))
2334 return collid;
2335
2336 /*
2337 * Check for any-encoding entry. This takes a bit more work: while libc
2338 * collations with collencoding = -1 do work with all encodings, ICU
2339 * collations only work with certain encodings, so we have to check that
2340 * aspect before deciding it's a match.
2341 */
2342 colltup = SearchSysCache3(COLLNAMEENCNSP,
2343 PointerGetDatum(collname),
2344 Int32GetDatum(-1),
2345 ObjectIdGetDatum(collnamespace));
2346 if (!HeapTupleIsValid(colltup))
2347 return InvalidOid;
2348 collform = (Form_pg_collation) GETSTRUCT(colltup);
2349 if (collform->collprovider == COLLPROVIDER_ICU)
2350 {
2351 if (is_encoding_supported_by_icu(encoding))
2352 collid = collform->oid;
2353 else
2354 collid = InvalidOid;
2355 }
2356 else
2357 {
2358 collid = collform->oid;
2359 }
2360 ReleaseSysCache(colltup);
2361 return collid;
2362 }
2363
2364 /*
2365 * CollationGetCollid
2366 * Try to resolve an unqualified collation name.
2367 * Returns OID if collation found in search path, else InvalidOid.
2368 *
2369 * Note that this will only find collations that work with the current
2370 * database's encoding.
2371 */
2372 Oid
2373 CollationGetCollid(const char *collname)
2374 {
2375 int32 dbencoding = GetDatabaseEncoding();
2376 ListCell *l;
2377
2378 recomputeNamespacePath();
2379
2380 foreach(l, activeSearchPath)
2381 {
2382 Oid namespaceId = lfirst_oid(l);
2383 Oid collid;
2384
2385 if (namespaceId == myTempNamespace)
2386 continue; /* do not look in temp namespace */
2387
2388 collid = lookup_collation(collname, namespaceId, dbencoding);
2389 if (OidIsValid(collid))
2390 return collid;
2391 }
2392
2393 /* Not found in path */
2394 return InvalidOid;
2395 }
2396
2397 /*
2398 * CollationIsVisible
2399 * Determine whether a collation (identified by OID) is visible in the
2400 * current search path. Visible means "would be found by searching
2401 * for the unqualified collation name".
2402 *
2403 * Note that only collations that work with the current database's encoding
2404 * will be considered visible.
2405 */
2406 bool
2407 CollationIsVisible(Oid collid)
2408 {
2409 return CollationIsVisibleExt(collid, NULL);
2410 }
2411
2412 /*
2413 * CollationIsVisibleExt
2414 * As above, but if the collation isn't found and is_missing is not NULL,
2415 * then set *is_missing = true and return false instead of throwing
2416 * an error. (Caller must initialize *is_missing = false.)
2417 */
2418 static bool
2419 CollationIsVisibleExt(Oid collid, bool *is_missing)
2420 {
2421 HeapTuple colltup;
2422 Form_pg_collation collform;
2423 Oid collnamespace;
2424 bool visible;
2425
2426 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
2427 if (!HeapTupleIsValid(colltup))
2428 {
2429 if (is_missing != NULL)
2430 {
2431 *is_missing = true;
2432 return false;
2433 }
2434 elog(ERROR, "cache lookup failed for collation %u", collid);
2435 }
2436 collform = (Form_pg_collation) GETSTRUCT(colltup);
2437
2438 recomputeNamespacePath();
2439
2440 /*
2441 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2442 * the system namespace are surely in the path and so we needn't even do
2443 * list_member_oid() for them.
2444 */
2445 collnamespace = collform->collnamespace;
2446 if (collnamespace != PG_CATALOG_NAMESPACE &&
2447 !list_member_oid(activeSearchPath, collnamespace))
2448 visible = false;
2449 else
2450 {
2451 /*
2452 * If it is in the path, it might still not be visible; it could be
2453 * hidden by another collation of the same name earlier in the path,
2454 * or it might not work with the current DB encoding. So we must do a
2455 * slow check to see if this collation would be found by
2456 * CollationGetCollid.
2457 */
2458 char *collname = NameStr(collform->collname);
2459
2460 visible = (CollationGetCollid(collname) == collid);
2461 }
2462
2463 ReleaseSysCache(colltup);
2464
2465 return visible;
2466 }
2467
2468
2469 /*
2470 * ConversionGetConid
2471 * Try to resolve an unqualified conversion name.
2472 * Returns OID if conversion found in search path, else InvalidOid.
2473 *
2474 * This is essentially the same as RelnameGetRelid.
2475 */
2476 Oid
2477 ConversionGetConid(const char *conname)
2478 {
2479 Oid conid;
2480 ListCell *l;
2481
2482 recomputeNamespacePath();
2483
2484 foreach(l, activeSearchPath)
2485 {
2486 Oid namespaceId = lfirst_oid(l);
2487
2488 if (namespaceId == myTempNamespace)
2489 continue; /* do not look in temp namespace */
2490
2491 conid = GetSysCacheOid2(CONNAMENSP, Anum_pg_conversion_oid,
2492 PointerGetDatum(conname),
2493 ObjectIdGetDatum(namespaceId));
2494 if (OidIsValid(conid))
2495 return conid;
2496 }
2497
2498 /* Not found in path */
2499 return InvalidOid;
2500 }
2501
2502 /*
2503 * ConversionIsVisible
2504 * Determine whether a conversion (identified by OID) is visible in the
2505 * current search path. Visible means "would be found by searching
2506 * for the unqualified conversion name".
2507 */
2508 bool
2509 ConversionIsVisible(Oid conid)
2510 {
2511 return ConversionIsVisibleExt(conid, NULL);
2512 }
2513
2514 /*
2515 * ConversionIsVisibleExt
2516 * As above, but if the conversion isn't found and is_missing is not NULL,
2517 * then set *is_missing = true and return false instead of throwing
2518 * an error. (Caller must initialize *is_missing = false.)
2519 */
2520 static bool
2521 ConversionIsVisibleExt(Oid conid, bool *is_missing)
2522 {
2523 HeapTuple contup;
2524 Form_pg_conversion conform;
2525 Oid connamespace;
2526 bool visible;
2527
2528 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2529 if (!HeapTupleIsValid(contup))
2530 {
2531 if (is_missing != NULL)
2532 {
2533 *is_missing = true;
2534 return false;
2535 }
2536 elog(ERROR, "cache lookup failed for conversion %u", conid);
2537 }
2538 conform = (Form_pg_conversion) GETSTRUCT(contup);
2539
2540 recomputeNamespacePath();
2541
2542 /*
2543 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2544 * the system namespace are surely in the path and so we needn't even do
2545 * list_member_oid() for them.
2546 */
2547 connamespace = conform->connamespace;
2548 if (connamespace != PG_CATALOG_NAMESPACE &&
2549 !list_member_oid(activeSearchPath, connamespace))
2550 visible = false;
2551 else
2552 {
2553 /*
2554 * If it is in the path, it might still not be visible; it could be
2555 * hidden by another conversion of the same name earlier in the path.
2556 * So we must do a slow check to see if this conversion would be found
2557 * by ConversionGetConid.
2558 */
2559 char *conname = NameStr(conform->conname);
2560
2561 visible = (ConversionGetConid(conname) == conid);
2562 }
2563
2564 ReleaseSysCache(contup);
2565
2566 return visible;
2567 }
2568
2569 /*
2570 * get_statistics_object_oid - find a statistics object by possibly qualified name
2571 *
2572 * If not found, returns InvalidOid if missing_ok, else throws error
2573 */
2574 Oid
2575 get_statistics_object_oid(List *names, bool missing_ok)
2576 {
2577 char *schemaname;
2578 char *stats_name;
2579 Oid namespaceId;
2580 Oid stats_oid = InvalidOid;
2581 ListCell *l;
2582
2583 /* deconstruct the name list */
2584 DeconstructQualifiedName(names, &schemaname, &stats_name);
2585
2586 if (schemaname)
2587 {
2588 /* use exact schema given */
2589 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2590 if (missing_ok && !OidIsValid(namespaceId))
2591 stats_oid = InvalidOid;
2592 else
2593 stats_oid = GetSysCacheOid2(STATEXTNAMENSP, Anum_pg_statistic_ext_oid,
2594 PointerGetDatum(stats_name),
2595 ObjectIdGetDatum(namespaceId));
2596 }
2597 else
2598 {
2599 /* search for it in search path */
2600 recomputeNamespacePath();
2601
2602 foreach(l, activeSearchPath)
2603 {
2604 namespaceId = lfirst_oid(l);
2605
2606 if (namespaceId == myTempNamespace)
2607 continue; /* do not look in temp namespace */
2608 stats_oid = GetSysCacheOid2(STATEXTNAMENSP, Anum_pg_statistic_ext_oid,
2609 PointerGetDatum(stats_name),
2610 ObjectIdGetDatum(namespaceId));
2611 if (OidIsValid(stats_oid))
2612 break;
2613 }
2614 }
2615
2616 if (!OidIsValid(stats_oid) && !missing_ok)
2617 ereport(ERROR,
2618 (errcode(ERRCODE_UNDEFINED_OBJECT),
2619 errmsg("statistics object \"%s\" does not exist",
2620 NameListToString(names))));
2621
2622 return stats_oid;
2623 }
2624
2625 /*
2626 * StatisticsObjIsVisible
2627 * Determine whether a statistics object (identified by OID) is visible in
2628 * the current search path. Visible means "would be found by searching
2629 * for the unqualified statistics object name".
2630 */
2631 bool
2632 StatisticsObjIsVisible(Oid stxid)
2633 {
2634 return StatisticsObjIsVisibleExt(stxid, NULL);
2635 }
2636
2637 /*
2638 * StatisticsObjIsVisibleExt
2639 * As above, but if the statistics object isn't found and is_missing is
2640 * not NULL, then set *is_missing = true and return false instead of
2641 * throwing an error. (Caller must initialize *is_missing = false.)
2642 */
2643 static bool
2644 StatisticsObjIsVisibleExt(Oid stxid, bool *is_missing)
2645 {
2646 HeapTuple stxtup;
2647 Form_pg_statistic_ext stxform;
2648 Oid stxnamespace;
2649 bool visible;
2650
2651 stxtup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxid));
2652 if (!HeapTupleIsValid(stxtup))
2653 {
2654 if (is_missing != NULL)
2655 {
2656 *is_missing = true;
2657 return false;
2658 }
2659 elog(ERROR, "cache lookup failed for statistics object %u", stxid);
2660 }
2661 stxform = (Form_pg_statistic_ext) GETSTRUCT(stxtup);
2662
2663 recomputeNamespacePath();
2664
2665 /*
2666 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2667 * the system namespace are surely in the path and so we needn't even do
2668 * list_member_oid() for them.
2669 */
2670 stxnamespace = stxform->stxnamespace;
2671 if (stxnamespace != PG_CATALOG_NAMESPACE &&
2672 !list_member_oid(activeSearchPath, stxnamespace))
2673 visible = false;
2674 else
2675 {
2676 /*
2677 * If it is in the path, it might still not be visible; it could be
2678 * hidden by another statistics object of the same name earlier in the
2679 * path. So we must do a slow check for conflicting objects.
2680 */
2681 char *stxname = NameStr(stxform->stxname);
2682 ListCell *l;
2683
2684 visible = false;
2685 foreach(l, activeSearchPath)
2686 {
2687 Oid namespaceId = lfirst_oid(l);
2688
2689 if (namespaceId == myTempNamespace)
2690 continue; /* do not look in temp namespace */
2691
2692 if (namespaceId == stxnamespace)
2693 {
2694 /* Found it first in path */
2695 visible = true;
2696 break;
2697 }
2698 if (SearchSysCacheExists2(STATEXTNAMENSP,
2699 PointerGetDatum(stxname),
2700 ObjectIdGetDatum(namespaceId)))
2701 {
2702 /* Found something else first in path */
2703 break;
2704 }
2705 }
2706 }
2707
2708 ReleaseSysCache(stxtup);
2709
2710 return visible;
2711 }
2712
2713 /*
2714 * get_ts_parser_oid - find a TS parser by possibly qualified name
2715 *
2716 * If not found, returns InvalidOid if missing_ok, else throws error
2717 */
2718 Oid
2719 get_ts_parser_oid(List *names, bool missing_ok)
2720 {
2721 char *schemaname;
2722 char *parser_name;
2723 Oid namespaceId;
2724 Oid prsoid = InvalidOid;
2725 ListCell *l;
2726
2727 /* deconstruct the name list */
2728 DeconstructQualifiedName(names, &schemaname, &parser_name);
2729
2730 if (schemaname)
2731 {
2732 /* use exact schema given */
2733 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2734 if (missing_ok && !OidIsValid(namespaceId))
2735 prsoid = InvalidOid;
2736 else
2737 prsoid = GetSysCacheOid2(TSPARSERNAMENSP, Anum_pg_ts_parser_oid,
2738 PointerGetDatum(parser_name),
2739 ObjectIdGetDatum(namespaceId));
2740 }
2741 else
2742 {
2743 /* search for it in search path */
2744 recomputeNamespacePath();
2745
2746 foreach(l, activeSearchPath)
2747 {
2748 namespaceId = lfirst_oid(l);
2749
2750 if (namespaceId == myTempNamespace)
2751 continue; /* do not look in temp namespace */
2752
2753 prsoid = GetSysCacheOid2(TSPARSERNAMENSP, Anum_pg_ts_parser_oid,
2754 PointerGetDatum(parser_name),
2755 ObjectIdGetDatum(namespaceId));
2756 if (OidIsValid(prsoid))
2757 break;
2758 }
2759 }
2760
2761 if (!OidIsValid(prsoid) && !missing_ok)
2762 ereport(ERROR,
2763 (errcode(ERRCODE_UNDEFINED_OBJECT),
2764 errmsg("text search parser \"%s\" does not exist",
2765 NameListToString(names))));
2766
2767 return prsoid;
2768 }
2769
2770 /*
2771 * TSParserIsVisible
2772 * Determine whether a parser (identified by OID) is visible in the
2773 * current search path. Visible means "would be found by searching
2774 * for the unqualified parser name".
2775 */
2776 bool
2777 TSParserIsVisible(Oid prsId)
2778 {
2779 return TSParserIsVisibleExt(prsId, NULL);
2780 }
2781
2782 /*
2783 * TSParserIsVisibleExt
2784 * As above, but if the parser isn't found and is_missing is not NULL,
2785 * then set *is_missing = true and return false instead of throwing
2786 * an error. (Caller must initialize *is_missing = false.)
2787 */
2788 static bool
2789 TSParserIsVisibleExt(Oid prsId, bool *is_missing)
2790 {
2791 HeapTuple tup;
2792 Form_pg_ts_parser form;
2793 Oid namespace;
2794 bool visible;
2795
2796 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2797 if (!HeapTupleIsValid(tup))
2798 {
2799 if (is_missing != NULL)
2800 {
2801 *is_missing = true;
2802 return false;
2803 }
2804 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2805 }
2806 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2807
2808 recomputeNamespacePath();
2809
2810 /*
2811 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2812 * the system namespace are surely in the path and so we needn't even do
2813 * list_member_oid() for them.
2814 */
2815 namespace = form->prsnamespace;
2816 if (namespace != PG_CATALOG_NAMESPACE &&
2817 !list_member_oid(activeSearchPath, namespace))
2818 visible = false;
2819 else
2820 {
2821 /*
2822 * If it is in the path, it might still not be visible; it could be
2823 * hidden by another parser of the same name earlier in the path. So
2824 * we must do a slow check for conflicting parsers.
2825 */
2826 char *name = NameStr(form->prsname);
2827 ListCell *l;
2828
2829 visible = false;
2830 foreach(l, activeSearchPath)
2831 {
2832 Oid namespaceId = lfirst_oid(l);
2833
2834 if (namespaceId == myTempNamespace)
2835 continue; /* do not look in temp namespace */
2836
2837 if (namespaceId == namespace)
2838 {
2839 /* Found it first in path */
2840 visible = true;
2841 break;
2842 }
2843 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2844 PointerGetDatum(name),
2845 ObjectIdGetDatum(namespaceId)))
2846 {
2847 /* Found something else first in path */
2848 break;
2849 }
2850 }
2851 }
2852
2853 ReleaseSysCache(tup);
2854
2855 return visible;
2856 }
2857
2858 /*
2859 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2860 *
2861 * If not found, returns InvalidOid if missing_ok, else throws error
2862 */
2863 Oid
2864 get_ts_dict_oid(List *names, bool missing_ok)
2865 {
2866 char *schemaname;
2867 char *dict_name;
2868 Oid namespaceId;
2869 Oid dictoid = InvalidOid;
2870 ListCell *l;
2871
2872 /* deconstruct the name list */
2873 DeconstructQualifiedName(names, &schemaname, &dict_name);
2874
2875 if (schemaname)
2876 {
2877 /* use exact schema given */
2878 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2879 if (missing_ok && !OidIsValid(namespaceId))
2880 dictoid = InvalidOid;
2881 else
2882 dictoid = GetSysCacheOid2(TSDICTNAMENSP, Anum_pg_ts_dict_oid,
2883 PointerGetDatum(dict_name),
2884 ObjectIdGetDatum(namespaceId));
2885 }
2886 else
2887 {
2888 /* search for it in search path */
2889 recomputeNamespacePath();
2890
2891 foreach(l, activeSearchPath)
2892 {
2893 namespaceId = lfirst_oid(l);
2894
2895 if (namespaceId == myTempNamespace)
2896 continue; /* do not look in temp namespace */
2897
2898 dictoid = GetSysCacheOid2(TSDICTNAMENSP, Anum_pg_ts_dict_oid,
2899 PointerGetDatum(dict_name),
2900 ObjectIdGetDatum(namespaceId));
2901 if (OidIsValid(dictoid))
2902 break;
2903 }
2904 }
2905
2906 if (!OidIsValid(dictoid) && !missing_ok)
2907 ereport(ERROR,
2908 (errcode(ERRCODE_UNDEFINED_OBJECT),
2909 errmsg("text search dictionary \"%s\" does not exist",
2910 NameListToString(names))));
2911
2912 return dictoid;
2913 }
2914
2915 /*
2916 * TSDictionaryIsVisible
2917 * Determine whether a dictionary (identified by OID) is visible in the
2918 * current search path. Visible means "would be found by searching
2919 * for the unqualified dictionary name".
2920 */
2921 bool
2922 TSDictionaryIsVisible(Oid dictId)
2923 {
2924 return TSDictionaryIsVisibleExt(dictId, NULL);
2925 }
2926
2927 /*
2928 * TSDictionaryIsVisibleExt
2929 * As above, but if the dictionary isn't found and is_missing is not NULL,
2930 * then set *is_missing = true and return false instead of throwing
2931 * an error. (Caller must initialize *is_missing = false.)
2932 */
2933 static bool
2934 TSDictionaryIsVisibleExt(Oid dictId, bool *is_missing)
2935 {
2936 HeapTuple tup;
2937 Form_pg_ts_dict form;
2938 Oid namespace;
2939 bool visible;
2940
2941 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2942 if (!HeapTupleIsValid(tup))
2943 {
2944 if (is_missing != NULL)
2945 {
2946 *is_missing = true;
2947 return false;
2948 }
2949 elog(ERROR, "cache lookup failed for text search dictionary %u",
2950 dictId);
2951 }
2952 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2953
2954 recomputeNamespacePath();
2955
2956 /*
2957 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2958 * the system namespace are surely in the path and so we needn't even do
2959 * list_member_oid() for them.
2960 */
2961 namespace = form->dictnamespace;
2962 if (namespace != PG_CATALOG_NAMESPACE &&
2963 !list_member_oid(activeSearchPath, namespace))
2964 visible = false;
2965 else
2966 {
2967 /*
2968 * If it is in the path, it might still not be visible; it could be
2969 * hidden by another dictionary of the same name earlier in the path.
2970 * So we must do a slow check for conflicting dictionaries.
2971 */
2972 char *name = NameStr(form->dictname);
2973 ListCell *l;
2974
2975 visible = false;
2976 foreach(l, activeSearchPath)
2977 {
2978 Oid namespaceId = lfirst_oid(l);
2979
2980 if (namespaceId == myTempNamespace)
2981 continue; /* do not look in temp namespace */
2982
2983 if (namespaceId == namespace)
2984 {
2985 /* Found it first in path */
2986 visible = true;
2987 break;
2988 }
2989 if (SearchSysCacheExists2(TSDICTNAMENSP,
2990 PointerGetDatum(name),
2991 ObjectIdGetDatum(namespaceId)))
2992 {
2993 /* Found something else first in path */
2994 break;
2995 }
2996 }
2997 }
2998
2999 ReleaseSysCache(tup);
3000
3001 return visible;
3002 }
3003
3004 /*
3005 * get_ts_template_oid - find a TS template by possibly qualified name
3006 *
3007 * If not found, returns InvalidOid if missing_ok, else throws error
3008 */
3009 Oid
3010 get_ts_template_oid(List *names, bool missing_ok)
3011 {
3012 char *schemaname;
3013 char *template_name;
3014 Oid namespaceId;
3015 Oid tmploid = InvalidOid;
3016 ListCell *l;
3017
3018 /* deconstruct the name list */
3019 DeconstructQualifiedName(names, &schemaname, &template_name);
3020
3021 if (schemaname)
3022 {
3023 /* use exact schema given */
3024 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3025 if (missing_ok && !OidIsValid(namespaceId))
3026 tmploid = InvalidOid;
3027 else
3028 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP, Anum_pg_ts_template_oid,
3029 PointerGetDatum(template_name),
3030 ObjectIdGetDatum(namespaceId));
3031 }
3032 else
3033 {
3034 /* search for it in search path */
3035 recomputeNamespacePath();
3036
3037 foreach(l, activeSearchPath)
3038 {
3039 namespaceId = lfirst_oid(l);
3040
3041 if (namespaceId == myTempNamespace)
3042 continue; /* do not look in temp namespace */
3043
3044 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP, Anum_pg_ts_template_oid,
3045 PointerGetDatum(template_name),
3046 ObjectIdGetDatum(namespaceId));
3047 if (OidIsValid(tmploid))
3048 break;
3049 }
3050 }
3051
3052 if (!OidIsValid(tmploid) && !missing_ok)
3053 ereport(ERROR,
3054 (errcode(ERRCODE_UNDEFINED_OBJECT),
3055 errmsg("text search template \"%s\" does not exist",
3056 NameListToString(names))));
3057
3058 return tmploid;
3059 }
3060
3061 /*
3062 * TSTemplateIsVisible
3063 * Determine whether a template (identified by OID) is visible in the
3064 * current search path. Visible means "would be found by searching
3065 * for the unqualified template name".
3066 */
3067 bool
3068 TSTemplateIsVisible(Oid tmplId)
3069 {
3070 return TSTemplateIsVisibleExt(tmplId, NULL);
3071 }
3072
3073 /*
3074 * TSTemplateIsVisibleExt
3075 * As above, but if the template isn't found and is_missing is not NULL,
3076 * then set *is_missing = true and return false instead of throwing
3077 * an error. (Caller must initialize *is_missing = false.)
3078 */
3079 static bool
3080 TSTemplateIsVisibleExt(Oid tmplId, bool *is_missing)
3081 {
3082 HeapTuple tup;
3083 Form_pg_ts_template form;
3084 Oid namespace;
3085 bool visible;
3086
3087 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
3088 if (!HeapTupleIsValid(tup))
3089 {
3090 if (is_missing != NULL)
3091 {
3092 *is_missing = true;
3093 return false;
3094 }
3095 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
3096 }
3097 form = (Form_pg_ts_template) GETSTRUCT(tup);
3098
3099 recomputeNamespacePath();
3100
3101 /*
3102 * Quick check: if it ain't in the path at all, it ain't visible. Items in
3103 * the system namespace are surely in the path and so we needn't even do
3104 * list_member_oid() for them.
3105 */
3106 namespace = form->tmplnamespace;
3107 if (namespace != PG_CATALOG_NAMESPACE &&
3108 !list_member_oid(activeSearchPath, namespace))
3109 visible = false;
3110 else
3111 {
3112 /*
3113 * If it is in the path, it might still not be visible; it could be
3114 * hidden by another template of the same name earlier in the path. So
3115 * we must do a slow check for conflicting templates.
3116 */
3117 char *name = NameStr(form->tmplname);
3118 ListCell *l;
3119
3120 visible = false;
3121 foreach(l, activeSearchPath)
3122 {
3123 Oid namespaceId = lfirst_oid(l);
3124
3125 if (namespaceId == myTempNamespace)
3126 continue; /* do not look in temp namespace */
3127
3128 if (namespaceId == namespace)
3129 {
3130 /* Found it first in path */
3131 visible = true;
3132 break;
3133 }
3134 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
3135 PointerGetDatum(name),
3136 ObjectIdGetDatum(namespaceId)))
3137 {
3138 /* Found something else first in path */
3139 break;
3140 }
3141 }
3142 }
3143
3144 ReleaseSysCache(tup);
3145
3146 return visible;
3147 }
3148
3149 /*
3150 * get_ts_config_oid - find a TS config by possibly qualified name
3151 *
3152 * If not found, returns InvalidOid if missing_ok, else throws error
3153 */
3154 Oid
3155 get_ts_config_oid(List *names, bool missing_ok)
3156 {
3157 char *schemaname;
3158 char *config_name;
3159 Oid namespaceId;
3160 Oid cfgoid = InvalidOid;
3161 ListCell *l;
3162
3163 /* deconstruct the name list */
3164 DeconstructQualifiedName(names, &schemaname, &config_name);
3165
3166 if (schemaname)
3167 {
3168 /* use exact schema given */
3169 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3170 if (missing_ok && !OidIsValid(namespaceId))
3171 cfgoid = InvalidOid;
3172 else
3173 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP, Anum_pg_ts_config_oid,
3174 PointerGetDatum(config_name),
3175 ObjectIdGetDatum(namespaceId));
3176 }
3177 else
3178 {
3179 /* search for it in search path */
3180 recomputeNamespacePath();
3181
3182 foreach(l, activeSearchPath)
3183 {
3184 namespaceId = lfirst_oid(l);
3185
3186 if (namespaceId == myTempNamespace)
3187 continue; /* do not look in temp namespace */
3188
3189 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP, Anum_pg_ts_config_oid,
3190 PointerGetDatum(config_name),
3191 ObjectIdGetDatum(namespaceId));
3192 if (OidIsValid(cfgoid))
3193 break;
3194 }
3195 }
3196
3197 if (!OidIsValid(cfgoid) && !missing_ok)
3198 ereport(ERROR,
3199 (errcode(ERRCODE_UNDEFINED_OBJECT),
3200 errmsg("text search configuration \"%s\" does not exist",
3201 NameListToString(names))));
3202
3203 return cfgoid;
3204 }
3205
3206 /*
3207 * TSConfigIsVisible
3208 * Determine whether a text search configuration (identified by OID)
3209 * is visible in the current search path. Visible means "would be found
3210 * by searching for the unqualified text search configuration name".
3211 */
3212 bool
3213 TSConfigIsVisible(Oid cfgid)
3214 {
3215 return TSConfigIsVisibleExt(cfgid, NULL);
3216 }
3217
3218 /*
3219 * TSConfigIsVisibleExt
3220 * As above, but if the configuration isn't found and is_missing is not
3221 * NULL, then set *is_missing = true and return false instead of throwing
3222 * an error. (Caller must initialize *is_missing = false.)
3223 */
3224 static bool
3225 TSConfigIsVisibleExt(Oid cfgid, bool *is_missing)
3226 {
3227 HeapTuple tup;
3228 Form_pg_ts_config form;
3229 Oid namespace;
3230 bool visible;
3231
3232 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
3233 if (!HeapTupleIsValid(tup))
3234 {
3235 if (is_missing != NULL)
3236 {
3237 *is_missing = true;
3238 return false;
3239 }
3240 elog(ERROR, "cache lookup failed for text search configuration %u",
3241 cfgid);
3242 }
3243 form = (Form_pg_ts_config) GETSTRUCT(tup);
3244
3245 recomputeNamespacePath();
3246
3247 /*
3248 * Quick check: if it ain't in the path at all, it ain't visible. Items in
3249 * the system namespace are surely in the path and so we needn't even do
3250 * list_member_oid() for them.
3251 */
3252 namespace = form->cfgnamespace;
3253 if (namespace != PG_CATALOG_NAMESPACE &&
3254 !list_member_oid(activeSearchPath, namespace))
3255 visible = false;
3256 else
3257 {
3258 /*
3259 * If it is in the path, it might still not be visible; it could be
3260 * hidden by another configuration of the same name earlier in the
3261 * path. So we must do a slow check for conflicting configurations.
3262 */
3263 char *name = NameStr(form->cfgname);
3264 ListCell *l;
3265
3266 visible = false;
3267 foreach(l, activeSearchPath)
3268 {
3269 Oid namespaceId = lfirst_oid(l);
3270
3271 if (namespaceId == myTempNamespace)
3272 continue; /* do not look in temp namespace */
3273
3274 if (namespaceId == namespace)
3275 {
3276 /* Found it first in path */
3277 visible = true;
3278 break;
3279 }
3280 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
3281 PointerGetDatum(name),
3282 ObjectIdGetDatum(namespaceId)))
3283 {
3284 /* Found something else first in path */
3285 break;
3286 }
3287 }
3288 }
3289
3290 ReleaseSysCache(tup);
3291
3292 return visible;
3293 }
3294
3295
3296 /*
3297 * DeconstructQualifiedName
3298 * Given a possibly-qualified name expressed as a list of String nodes,
3299 * extract the schema name and object name.
3300 *
3301 * *nspname_p is set to NULL if there is no explicit schema name.
3302 */
3303 void
3304 DeconstructQualifiedName(const List *names,
3305 char **nspname_p,
3306 char **objname_p)
3307 {
3308 char *catalogname;
3309 char *schemaname = NULL;
3310 char *objname = NULL;
3311
3312 switch (list_length(names))
3313 {
3314 case 1:
3315 objname = strVal(linitial(names));
3316 break;
3317 case 2:
3318 schemaname = strVal(linitial(names));
3319 objname = strVal(lsecond(names));
3320 break;
3321 case 3:
3322 catalogname = strVal(linitial(names));
3323 schemaname = strVal(lsecond(names));
3324 objname = strVal(lthird(names));
3325
3326 /*
3327 * We check the catalog name and then ignore it.
3328 */
3329 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
3330 ereport(ERROR,
3331 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3332 errmsg("cross-database references are not implemented: %s",
3333 NameListToString(names))));
3334 break;
3335 default:
3336 ereport(ERROR,
3337 (errcode(ERRCODE_SYNTAX_ERROR),
3338 errmsg("improper qualified name (too many dotted names): %s",
3339 NameListToString(names))));
3340 break;
3341 }
3342
3343 *nspname_p = schemaname;
3344 *objname_p = objname;
3345 }
3346
3347 /*
3348 * LookupNamespaceNoError
3349 * Look up a schema name.
3350 *
3351 * Returns the namespace OID, or InvalidOid if not found.
3352 *
3353 * Note this does NOT perform any permissions check --- callers are
3354 * responsible for being sure that an appropriate check is made.
3355 * In the majority of cases LookupExplicitNamespace is preferable.
3356 */
3357 Oid
3358 LookupNamespaceNoError(const char *nspname)
3359 {
3360 /* check for pg_temp alias */
3361 if (strcmp(nspname, "pg_temp") == 0)
3362 {
3363 if (OidIsValid(myTempNamespace))
3364 {
3365 InvokeNamespaceSearchHook(myTempNamespace, true);
3366 return myTempNamespace;
3367 }
3368
3369 /*
3370 * Since this is used only for looking up existing objects, there is
3371 * no point in trying to initialize the temp namespace here; and doing
3372 * so might create problems for some callers. Just report "not found".
3373 */
3374 return InvalidOid;
3375 }
3376
3377 return get_namespace_oid(nspname, true);
3378 }
3379
3380 /*
3381 * LookupExplicitNamespace
3382 * Process an explicitly-specified schema name: look up the schema
3383 * and verify we have USAGE (lookup) rights in it.
3384 *
3385 * Returns the namespace OID
3386 */
3387 Oid
3388 LookupExplicitNamespace(const char *nspname, bool missing_ok)
3389 {
3390 Oid namespaceId;
3391 AclResult aclresult;
3392
3393 /* check for pg_temp alias */
3394 if (strcmp(nspname, "pg_temp") == 0)
3395 {
3396 if (OidIsValid(myTempNamespace))
3397 return myTempNamespace;
3398
3399 /*
3400 * Since this is used only for looking up existing objects, there is
3401 * no point in trying to initialize the temp namespace here; and doing
3402 * so might create problems for some callers --- just fall through.
3403 */
3404 }
3405
3406 namespaceId = get_namespace_oid(nspname, missing_ok);
3407 if (missing_ok && !OidIsValid(namespaceId))
3408 return InvalidOid;
3409
3410 aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(), ACL_USAGE);
3411 if (aclresult != ACLCHECK_OK)
3412 aclcheck_error(aclresult, OBJECT_SCHEMA,
3413 nspname);
3414 /* Schema search hook for this lookup */
3415 InvokeNamespaceSearchHook(namespaceId, true);
3416
3417 return namespaceId;
3418 }
3419
3420 /*
3421 * LookupCreationNamespace
3422 * Look up the schema and verify we have CREATE rights on it.
3423 *
3424 * This is just like LookupExplicitNamespace except for the different
3425 * permission check, and that we are willing to create pg_temp if needed.
3426 *
3427 * Note: calling this may result in a CommandCounterIncrement operation,
3428 * if we have to create or clean out the temp namespace.
3429 */
3430 Oid
3431 LookupCreationNamespace(const char *nspname)
3432 {
3433 Oid namespaceId;
3434 AclResult aclresult;
3435
3436 /* check for pg_temp alias */
3437 if (strcmp(nspname, "pg_temp") == 0)
3438 {
3439 /* Initialize temp namespace */
3440 AccessTempTableNamespace(false);
3441 return myTempNamespace;
3442 }
3443
3444 namespaceId = get_namespace_oid(nspname, false);
3445
3446 aclresult = object_aclcheck(NamespaceRelationId, namespaceId, GetUserId(), ACL_CREATE);
3447 if (aclresult != ACLCHECK_OK)
3448 aclcheck_error(aclresult, OBJECT_SCHEMA,
3449 nspname);
3450
3451 return namespaceId;
3452 }
3453
3454 /*
3455 * Common checks on switching namespaces.
3456 *
3457 * We complain if either the old or new namespaces is a temporary schema
3458 * (or temporary toast schema), or if either the old or new namespaces is the
3459 * TOAST schema.
3460 */
3461 void
3462 CheckSetNamespace(Oid oldNspOid, Oid nspOid)
3463 {
3464 /* disallow renaming into or out of temp schemas */
3465 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
3466 ereport(ERROR,
3467 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3468 errmsg("cannot move objects into or out of temporary schemas")));
3469
3470 /* same for TOAST schema */
3471 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
3472 ereport(ERROR,
3473 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3474 errmsg("cannot move objects into or out of TOAST schema")));
3475 }
3476
3477 /*
3478 * QualifiedNameGetCreationNamespace
3479 * Given a possibly-qualified name for an object (in List-of-Strings
3480 * format), determine what namespace the object should be created in.
3481 * Also extract and return the object name (last component of list).
3482 *
3483 * Note: this does not apply any permissions check. Callers must check
3484 * for CREATE rights on the selected namespace when appropriate.
3485 *
3486 * Note: calling this may result in a CommandCounterIncrement operation,
3487 * if we have to create or clean out the temp namespace.
3488 */
3489 Oid
3490 QualifiedNameGetCreationNamespace(const List *names, char **objname_p)
3491 {
3492 char *schemaname;
3493 Oid namespaceId;
3494
3495 /* deconstruct the name list */
3496 DeconstructQualifiedName(names, &schemaname, objname_p);
3497
3498 if (schemaname)
3499 {
3500 /* check for pg_temp alias */
3501 if (strcmp(schemaname, "pg_temp") == 0)
3502 {
3503 /* Initialize temp namespace */
3504 AccessTempTableNamespace(false);
3505 return myTempNamespace;
3506 }
3507 /* use exact schema given */
3508 namespaceId = get_namespace_oid(schemaname, false);
3509 /* we do not check for USAGE rights here! */
3510 }
3511 else
3512 {
3513 /* use the default creation namespace */
3514 recomputeNamespacePath();
3515 if (activeTempCreationPending)
3516 {
3517 /* Need to initialize temp namespace */
3518 AccessTempTableNamespace(true);
3519 return myTempNamespace;
3520 }
3521 namespaceId = activeCreationNamespace;
3522 if (!OidIsValid(namespaceId))
3523 ereport(ERROR,
3524 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3525 errmsg("no schema has been selected to create in")));
3526 }
3527
3528 return namespaceId;
3529 }
3530
3531 /*
3532 * get_namespace_oid - given a namespace name, look up the OID
3533 *
3534 * If missing_ok is false, throw an error if namespace name not found. If
3535 * true, just return InvalidOid.
3536 */
3537 Oid
3538 get_namespace_oid(const char *nspname, bool missing_ok)
3539 {
3540 Oid oid;
3541
3542 oid = GetSysCacheOid1(NAMESPACENAME, Anum_pg_namespace_oid,
3543 CStringGetDatum(nspname));
3544 if (!OidIsValid(oid) && !missing_ok)
3545 ereport(ERROR,
3546 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3547 errmsg("schema \"%s\" does not exist", nspname)));
3548
3549 return oid;
3550 }
3551
3552 /*
3553 * makeRangeVarFromNameList
3554 * Utility routine to convert a qualified-name list into RangeVar form.
3555 */
3556 RangeVar *
3557 makeRangeVarFromNameList(const List *names)
3558 {
3559 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
3560
3561 switch (list_length(names))
3562 {
3563 case 1:
3564 rel->relname = strVal(linitial(names));
3565 break;
3566 case 2:
3567 rel->schemaname = strVal(linitial(names));
3568 rel->relname = strVal(lsecond(names));
3569 break;
3570 case 3:
3571 rel->catalogname = strVal(linitial(names));
3572 rel->schemaname = strVal(lsecond(names));
3573 rel->relname = strVal(lthird(names));
3574 break;
3575 default:
3576 ereport(ERROR,
3577 (errcode(ERRCODE_SYNTAX_ERROR),
3578 errmsg("improper relation name (too many dotted names): %s",
3579 NameListToString(names))));
3580 break;
3581 }
3582
3583 return rel;
3584 }
3585
3586 /*
3587 * NameListToString
3588 * Utility routine to convert a qualified-name list into a string.
3589 *
3590 * This is used primarily to form error messages, and so we do not quote
3591 * the list elements, for the sake of legibility.
3592 *
3593 * In most scenarios the list elements should always be String values,
3594 * but we also allow A_Star for the convenience of ColumnRef processing.
3595 */
3596 char *
3597 NameListToString(const List *names)
3598 {
3599 StringInfoData string;
3600 ListCell *l;
3601
3602 initStringInfo(&string);
3603
3604 foreach(l, names)
3605 {
3606 Node *name = (Node *) lfirst(l);
3607
3608 if (l != list_head(names))
3609 appendStringInfoChar(&string, '.');
3610
3611 if (IsA(name, String))
3612 appendStringInfoString(&string, strVal(name));
3613 else if (IsA(name, A_Star))
3614 appendStringInfoChar(&string, '*');
3615 else
3616 elog(ERROR, "unexpected node type in name list: %d",
3617 (int) nodeTag(name));
3618 }
3619
3620 return string.data;
3621 }
3622
3623 /*
3624 * NameListToQuotedString
3625 * Utility routine to convert a qualified-name list into a string.
3626 *
3627 * Same as above except that names will be double-quoted where necessary,
3628 * so the string could be re-parsed (eg, by textToQualifiedNameList).
3629 */
3630 char *
3631 NameListToQuotedString(const List *names)
3632 {
3633 StringInfoData string;
3634 ListCell *l;
3635
3636 initStringInfo(&string);
3637
3638 foreach(l, names)
3639 {
3640 if (l != list_head(names))
3641 appendStringInfoChar(&string, '.');
3642 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
3643 }
3644
3645 return string.data;
3646 }
3647
3648 /*
3649 * isTempNamespace - is the given namespace my temporary-table namespace?
3650 */
3651 bool
3652 isTempNamespace(Oid namespaceId)
3653 {
3654 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
3655 return true;
3656 return false;
3657 }
3658
3659 /*
3660 * isTempToastNamespace - is the given namespace my temporary-toast-table
3661 * namespace?
3662 */
3663 bool
3664 isTempToastNamespace(Oid namespaceId)
3665 {
3666 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
3667 return true;
3668 return false;
3669 }
3670
3671 /*
3672 * isTempOrTempToastNamespace - is the given namespace my temporary-table
3673 * namespace or my temporary-toast-table namespace?
3674 */
3675 bool
3676 isTempOrTempToastNamespace(Oid namespaceId)
3677 {
3678 if (OidIsValid(myTempNamespace) &&
3679 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3680 return true;
3681 return false;
3682 }
3683
3684 /*
3685 * isAnyTempNamespace - is the given namespace a temporary-table namespace
3686 * (either my own, or another backend's)? Temporary-toast-table namespaces
3687 * are included, too.
3688 */
3689 bool
3690 isAnyTempNamespace(Oid namespaceId)
3691 {
3692 bool result;
3693 char *nspname;
3694
3695 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3696 nspname = get_namespace_name(namespaceId);
3697 if (!nspname)
3698 return false; /* no such namespace? */
3699 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3700 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3701 pfree(nspname);
3702 return result;
3703 }
3704
3705 /*
3706 * isOtherTempNamespace - is the given namespace some other backend's
3707 * temporary-table namespace (including temporary-toast-table namespaces)?
3708 *
3709 * Note: for most purposes in the C code, this function is obsolete. Use
3710 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3711 */
3712 bool
3713 isOtherTempNamespace(Oid namespaceId)
3714 {
3715 /* If it's my own temp namespace, say "false" */
3716 if (isTempOrTempToastNamespace(namespaceId))
3717 return false;
3718 /* Else, if it's any temp namespace, say "true" */
3719 return isAnyTempNamespace(namespaceId);
3720 }
3721
3722 /*
3723 * checkTempNamespaceStatus - is the given namespace owned and actively used
3724 * by a backend?
3725 *
3726 * Note: this can be used while scanning relations in pg_class to detect
3727 * orphaned temporary tables or namespaces with a backend connected to a
3728 * given database. The result may be out of date quickly, so the caller
3729 * must be careful how to handle this information.
3730 */
3731 TempNamespaceStatus
3732 checkTempNamespaceStatus(Oid namespaceId)
3733 {
3734 PGPROC *proc;
3735 ProcNumber procNumber;
3736
3737 Assert(OidIsValid(MyDatabaseId));
3738
3739 procNumber = GetTempNamespaceProcNumber(namespaceId);
3740
3741 /* No such namespace, or its name shows it's not temp? */
3742 if (procNumber == INVALID_PROC_NUMBER)
3743 return TEMP_NAMESPACE_NOT_TEMP;
3744
3745 /* Is the backend alive? */
3746 proc = ProcNumberGetProc(procNumber);
3747 if (proc == NULL)
3748 return TEMP_NAMESPACE_IDLE;
3749
3750 /* Is the backend connected to the same database we are looking at? */
3751 if (proc->databaseId != MyDatabaseId)
3752 return TEMP_NAMESPACE_IDLE;
3753
3754 /* Does the backend own the temporary namespace? */
3755 if (proc->tempNamespaceId != namespaceId)
3756 return TEMP_NAMESPACE_IDLE;
3757
3758 /* Yup, so namespace is busy */
3759 return TEMP_NAMESPACE_IN_USE;
3760 }
3761
3762 /*
3763 * GetTempNamespaceProcNumber - if the given namespace is a temporary-table
3764 * namespace (either my own, or another backend's), return the proc number
3765 * that owns it. Temporary-toast-table namespaces are included, too.
3766 * If it isn't a temp namespace, return INVALID_PROC_NUMBER.
3767 */
3768 ProcNumber
3769 GetTempNamespaceProcNumber(Oid namespaceId)
3770 {
3771 int result;
3772 char *nspname;
3773
3774 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3775 nspname = get_namespace_name(namespaceId);
3776 if (!nspname)
3777 return INVALID_PROC_NUMBER; /* no such namespace? */
3778 if (strncmp(nspname, "pg_temp_", 8) == 0)
3779 result = atoi(nspname + 8);
3780 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3781 result = atoi(nspname + 14);
3782 else
3783 result = INVALID_PROC_NUMBER;
3784 pfree(nspname);
3785 return result;
3786 }
3787
3788 /*
3789 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3790 * which must already be assigned. (This is only used when creating a toast
3791 * table for a temp table, so we must have already done InitTempTableNamespace)
3792 */
3793 Oid
3794 GetTempToastNamespace(void)
3795 {
3796 Assert(OidIsValid(myTempToastNamespace));
3797 return myTempToastNamespace;
3798 }
3799
3800
3801 /*
3802 * GetTempNamespaceState - fetch status of session's temporary namespace
3803 *
3804 * This is used for conveying state to a parallel worker, and is not meant
3805 * for general-purpose access.
3806 */
3807 void
3808 GetTempNamespaceState(Oid *tempNamespaceId, Oid *tempToastNamespaceId)
3809 {
3810 /* Return namespace OIDs, or 0 if session has not created temp namespace */
3811 *tempNamespaceId = myTempNamespace;
3812 *tempToastNamespaceId = myTempToastNamespace;
3813 }
3814
3815 /*
3816 * SetTempNamespaceState - set status of session's temporary namespace
3817 *
3818 * This is used for conveying state to a parallel worker, and is not meant for
3819 * general-purpose access. By transferring these namespace OIDs to workers,
3820 * we ensure they will have the same notion of the search path as their leader
3821 * does.
3822 */
3823 void
3824 SetTempNamespaceState(Oid tempNamespaceId, Oid tempToastNamespaceId)
3825 {
3826 /* Worker should not have created its own namespaces ... */
3827 Assert(myTempNamespace == InvalidOid);
3828 Assert(myTempToastNamespace == InvalidOid);
3829 Assert(myTempNamespaceSubID == InvalidSubTransactionId);
3830
3831 /* Assign same namespace OIDs that leader has */
3832 myTempNamespace = tempNamespaceId;
3833 myTempToastNamespace = tempToastNamespaceId;
3834
3835 /*
3836 * It's fine to leave myTempNamespaceSubID == InvalidSubTransactionId.
3837 * Even if the namespace is new so far as the leader is concerned, it's
3838 * not new to the worker, and we certainly wouldn't want the worker trying
3839 * to destroy it.
3840 */
3841
3842 baseSearchPathValid = false; /* may need to rebuild list */
3843 searchPathCacheValid = false;
3844 }
3845
3846
3847 /*
3848 * GetSearchPathMatcher - fetch current search path definition.
3849 *
3850 * The result structure is allocated in the specified memory context
3851 * (which might or might not be equal to CurrentMemoryContext); but any
3852 * junk created by revalidation calculations will be in CurrentMemoryContext.
3853 */
3854 SearchPathMatcher *
3855 GetSearchPathMatcher(MemoryContext context)
3856 {
3857 SearchPathMatcher *result;
3858 List *schemas;
3859 MemoryContext oldcxt;
3860
3861 recomputeNamespacePath();
3862
3863 oldcxt = MemoryContextSwitchTo(context);
3864
3865 result = (SearchPathMatcher *) palloc0(sizeof(SearchPathMatcher));
3866 schemas = list_copy(activeSearchPath);
3867 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3868 {
3869 if (linitial_oid(schemas) == myTempNamespace)
3870 result->addTemp = true;
3871 else
3872 {
3873 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3874 result->addCatalog = true;
3875 }
3876 schemas = list_delete_first(schemas);
3877 }
3878 result->schemas = schemas;
3879 result->generation = activePathGeneration;
3880
3881 MemoryContextSwitchTo(oldcxt);
3882
3883 return result;
3884 }
3885
3886 /*
3887 * CopySearchPathMatcher - copy the specified SearchPathMatcher.
3888 *
3889 * The result structure is allocated in CurrentMemoryContext.
3890 */
3891 SearchPathMatcher *
3892 CopySearchPathMatcher(SearchPathMatcher *path)
3893 {
3894 SearchPathMatcher *result;
3895
3896 result = (SearchPathMatcher *) palloc(sizeof(SearchPathMatcher));
3897 result->schemas = list_copy(path->schemas);
3898 result->addCatalog = path->addCatalog;
3899 result->addTemp = path->addTemp;
3900 result->generation = path->generation;
3901
3902 return result;
3903 }
3904
3905 /*
3906 * SearchPathMatchesCurrentEnvironment - does path match current environment?
3907 *
3908 * This is tested over and over in some common code paths, and in the typical
3909 * scenario where the active search path seldom changes, it'll always succeed.
3910 * We make that case fast by keeping a generation counter that is advanced
3911 * whenever the active search path changes.
3912 */
3913 bool
3914 SearchPathMatchesCurrentEnvironment(SearchPathMatcher *path)
3915 {
3916 ListCell *lc,
3917 *lcp;
3918
3919 recomputeNamespacePath();
3920
3921 /* Quick out if already known equal to active path. */
3922 if (path->generation == activePathGeneration)
3923 return true;
3924
3925 /* We scan down the activeSearchPath to see if it matches the input. */
3926 lc = list_head(activeSearchPath);
3927
3928 /* If path->addTemp, first item should be my temp namespace. */
3929 if (path->addTemp)
3930 {
3931 if (lc && lfirst_oid(lc) == myTempNamespace)
3932 lc = lnext(activeSearchPath, lc);
3933 else
3934 return false;
3935 }
3936 /* If path->addCatalog, next item should be pg_catalog. */
3937 if (path->addCatalog)
3938 {
3939 if (lc && lfirst_oid(lc) == PG_CATALOG_NAMESPACE)
3940 lc = lnext(activeSearchPath, lc);
3941 else
3942 return false;
3943 }
3944 /* We should now be looking at the activeCreationNamespace. */
3945 if (activeCreationNamespace != (lc ? lfirst_oid(lc) : InvalidOid))
3946 return false;
3947 /* The remainder of activeSearchPath should match path->schemas. */
3948 foreach(lcp, path->schemas)
3949 {
3950 if (lc && lfirst_oid(lc) == lfirst_oid(lcp))
3951 lc = lnext(activeSearchPath, lc);
3952 else
3953 return false;
3954 }
3955 if (lc)
3956 return false;
3957
3958 /*
3959 * Update path->generation so that future tests will return quickly, so
3960 * long as the active search path doesn't change.
3961 */
3962 path->generation = activePathGeneration;
3963
3964 return true;
3965 }
3966
3967 /*
3968 * get_collation_oid - find a collation by possibly qualified name
3969 *
3970 * Note that this will only find collations that work with the current
3971 * database's encoding.
3972 */
3973 Oid
3974 get_collation_oid(List *collname, bool missing_ok)
3975 {
3976 char *schemaname;
3977 char *collation_name;
3978 int32 dbencoding = GetDatabaseEncoding();
3979 Oid namespaceId;
3980 Oid colloid;
3981 ListCell *l;
3982
3983 /* deconstruct the name list */
3984 DeconstructQualifiedName(collname, &schemaname, &collation_name);
3985
3986 if (schemaname)
3987 {
3988 /* use exact schema given */
3989 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3990 if (missing_ok && !OidIsValid(namespaceId))
3991 return InvalidOid;
3992
3993 colloid = lookup_collation(collation_name, namespaceId, dbencoding);
3994 if (OidIsValid(colloid))
3995 return colloid;
3996 }
3997 else
3998 {
3999 /* search for it in search path */
4000 recomputeNamespacePath();
4001
4002 foreach(l, activeSearchPath)
4003 {
4004 namespaceId = lfirst_oid(l);
4005
4006 if (namespaceId == myTempNamespace)
4007 continue; /* do not look in temp namespace */
4008
4009 colloid = lookup_collation(collation_name, namespaceId, dbencoding);
4010 if (OidIsValid(colloid))
4011 return colloid;
4012 }
4013 }
4014
4015 /* Not found in path */
4016 if (!missing_ok)
4017 ereport(ERROR,
4018 (errcode(ERRCODE_UNDEFINED_OBJECT),
4019 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
4020 NameListToString(collname), GetDatabaseEncodingName())));
4021 return InvalidOid;
4022 }
4023
4024 /*
4025 * get_conversion_oid - find a conversion by possibly qualified name
4026 */
4027 Oid
4028 get_conversion_oid(List *conname, bool missing_ok)
4029 {
4030 char *schemaname;
4031 char *conversion_name;
4032 Oid namespaceId;
4033 Oid conoid = InvalidOid;
4034 ListCell *l;
4035
4036 /* deconstruct the name list */
4037 DeconstructQualifiedName(conname, &schemaname, &conversion_name);
4038
4039 if (schemaname)
4040 {
4041 /* use exact schema given */
4042 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
4043 if (missing_ok && !OidIsValid(namespaceId))
4044 conoid = InvalidOid;
4045 else
4046 conoid = GetSysCacheOid2(CONNAMENSP, Anum_pg_conversion_oid,
4047 PointerGetDatum(conversion_name),
4048 ObjectIdGetDatum(namespaceId));
4049 }
4050 else
4051 {
4052 /* search for it in search path */
4053 recomputeNamespacePath();
4054
4055 foreach(l, activeSearchPath)
4056 {
4057 namespaceId = lfirst_oid(l);
4058
4059 if (namespaceId == myTempNamespace)
4060 continue; /* do not look in temp namespace */
4061
4062 conoid = GetSysCacheOid2(CONNAMENSP, Anum_pg_conversion_oid,
4063 PointerGetDatum(conversion_name),
4064 ObjectIdGetDatum(namespaceId));
4065 if (OidIsValid(conoid))
4066 return conoid;
4067 }
4068 }
4069
4070 /* Not found in path */
4071 if (!OidIsValid(conoid) && !missing_ok)
4072 ereport(ERROR,
4073 (errcode(ERRCODE_UNDEFINED_OBJECT),
4074 errmsg("conversion \"%s\" does not exist",
4075 NameListToString(conname))));
4076 return conoid;
4077 }
4078
4079 /*
4080 * FindDefaultConversionProc - find default encoding conversion proc
4081 */
4082 Oid
4083 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
4084 {
4085 Oid proc;
4086 ListCell *l;
4087
4088 recomputeNamespacePath();
4089
4090 foreach(l, activeSearchPath)
4091 {
4092 Oid namespaceId = lfirst_oid(l);
4093
4094 if (namespaceId == myTempNamespace)
4095 continue; /* do not look in temp namespace */
4096
4097 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
4098 if (OidIsValid(proc))
4099 return proc;
4100 }
4101
4102 /* Not found in path */
4103 return InvalidOid;
4104 }
4105
4106 /*
4107 * Look up namespace IDs and perform ACL checks. Return newly-allocated list.
4108 */
4109 static List *
4110 preprocessNamespacePath(const char *searchPath, Oid roleid,
4111 bool *temp_missing)
4112 {
4113 char *rawname;
4114 List *namelist;
4115 List *oidlist;
4116 ListCell *l;
4117
4118 /* Need a modifiable copy */
4119 rawname = pstrdup(searchPath);
4120
4121 /* Parse string into list of identifiers */
4122 if (!SplitIdentifierString(rawname, ',', &namelist))
4123 {
4124 /* syntax error in name list */
4125 /* this should not happen if GUC checked check_search_path */
4126 elog(ERROR, "invalid list syntax");
4127 }
4128
4129 /*
4130 * Convert the list of names to a list of OIDs. If any names are not
4131 * recognizable or we don't have read access, just leave them out of the
4132 * list. (We can't raise an error, since the search_path setting has
4133 * already been accepted.) Don't make duplicate entries, either.
4134 */
4135 oidlist = NIL;
4136 *temp_missing = false;
4137 foreach(l, namelist)
4138 {
4139 char *curname = (char *) lfirst(l);
4140 Oid namespaceId;
4141
4142 if (strcmp(curname, "$user") == 0)
4143 {
4144 /* $user --- substitute namespace matching user name, if any */
4145 HeapTuple tuple;
4146
4147 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
4148 if (HeapTupleIsValid(tuple))
4149 {
4150 char *rname;
4151
4152 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
4153 namespaceId = get_namespace_oid(rname, true);
4154 ReleaseSysCache(tuple);
4155 if (OidIsValid(namespaceId) &&
4156 object_aclcheck(NamespaceRelationId, namespaceId, roleid,
4157 ACL_USAGE) == ACLCHECK_OK)
4158 oidlist = lappend_oid(oidlist, namespaceId);
4159 }
4160 }
4161 else if (strcmp(curname, "pg_temp") == 0)
4162 {
4163 /* pg_temp --- substitute temp namespace, if any */
4164 if (OidIsValid(myTempNamespace))
4165 oidlist = lappend_oid(oidlist, myTempNamespace);
4166 else
4167 {
4168 /* If it ought to be the creation namespace, set flag */
4169 if (oidlist == NIL)
4170 *temp_missing = true;
4171 }
4172 }
4173 else
4174 {
4175 /* normal namespace reference */
4176 namespaceId = get_namespace_oid(curname, true);
4177 if (OidIsValid(namespaceId) &&
4178 object_aclcheck(NamespaceRelationId, namespaceId, roleid,
4179 ACL_USAGE) == ACLCHECK_OK)
4180 oidlist = lappend_oid(oidlist, namespaceId);
4181 }
4182 }
4183
4184 pfree(rawname);
4185 list_free(namelist);
4186
4187 return oidlist;
4188 }
4189
4190 /*
4191 * Remove duplicates, run namespace search hooks, and prepend
4192 * implicitly-searched namespaces. Return newly-allocated list.
4193 *
4194 * If an object_access_hook is present, this must always be recalculated. It
4195 * may seem that duplicate elimination is not dependent on the result of the
4196 * hook, but if a hook returns different results on different calls for the
4197 * same namespace ID, then it could affect the order in which that namespace
4198 * appears in the final list.
4199 */
4200 static List *
4201 finalNamespacePath(List *oidlist, Oid *firstNS)
4202 {
4203 List *finalPath = NIL;
4204 ListCell *lc;
4205
4206 foreach(lc, oidlist)
4207 {
4208 Oid namespaceId = lfirst_oid(lc);
4209
4210 if (!list_member_oid(finalPath, namespaceId))
4211 {
4212 if (InvokeNamespaceSearchHook(namespaceId, false))
4213 finalPath = lappend_oid(finalPath, namespaceId);
4214 }
4215 }
4216
4217 /*
4218 * Remember the first member of the explicit list. (Note: this is
4219 * nominally wrong if temp_missing, but we need it anyway to distinguish
4220 * explicit from implicit mention of pg_catalog.)
4221 */
4222 if (finalPath == NIL)
4223 *firstNS = InvalidOid;
4224 else
4225 *firstNS = linitial_oid(finalPath);
4226
4227 /*
4228 * Add any implicitly-searched namespaces to the list. Note these go on
4229 * the front, not the back; also notice that we do not check USAGE
4230 * permissions for these.
4231 */
4232 if (!list_member_oid(finalPath, PG_CATALOG_NAMESPACE))
4233 finalPath = lcons_oid(PG_CATALOG_NAMESPACE, finalPath);
4234
4235 if (OidIsValid(myTempNamespace) &&
4236 !list_member_oid(finalPath, myTempNamespace))
4237 finalPath = lcons_oid(myTempNamespace, finalPath);
4238
4239 return finalPath;
4240 }
4241
4242 /*
4243 * Retrieve search path information from the cache; or if not there, fill
4244 * it. The returned entry is valid only until the next call to this function.
4245 */
4246 static const SearchPathCacheEntry *
4247 cachedNamespacePath(const char *searchPath, Oid roleid)
4248 {
4249 MemoryContext oldcxt;
4250 SearchPathCacheEntry *entry;
4251
4252 spcache_init();
4253
4254 entry = spcache_insert(searchPath, roleid);
4255
4256 /*
4257 * An OOM may have resulted in a cache entry with missing 'oidlist' or
4258 * 'finalPath', so just compute whatever is missing.
4259 */
4260
4261 if (entry->oidlist == NIL)
4262 {
4263 oldcxt = MemoryContextSwitchTo(SearchPathCacheContext);
4264 entry->oidlist = preprocessNamespacePath(searchPath, roleid,
4265 &entry->temp_missing);
4266 MemoryContextSwitchTo(oldcxt);
4267 }
4268
4269 /*
4270 * If a hook is set, we must recompute finalPath from the oidlist each
4271 * time, because the hook may affect the result. This is still much faster
4272 * than recomputing from the string (and doing catalog lookups and ACL
4273 * checks).
4274 */
4275 if (entry->finalPath == NIL || object_access_hook ||
4276 entry->forceRecompute)
4277 {
4278 list_free(entry->finalPath);
4279 entry->finalPath = NIL;
4280
4281 oldcxt = MemoryContextSwitchTo(SearchPathCacheContext);
4282 entry->finalPath = finalNamespacePath(entry->oidlist,
4283 &entry->firstNS);
4284 MemoryContextSwitchTo(oldcxt);
4285
4286 /*
4287 * If an object_access_hook is set when finalPath is calculated, the
4288 * result may be affected by the hook. Force recomputation of
4289 * finalPath the next time this cache entry is used, even if the
4290 * object_access_hook is not set at that time.
4291 */
4292 entry->forceRecompute = object_access_hook ? true : false;
4293 }
4294
4295 return entry;
4296 }
4297
4298 /*
4299 * recomputeNamespacePath - recompute path derived variables if needed.
4300 */
4301 static void
4302 recomputeNamespacePath(void)
4303 {
4304 Oid roleid = GetUserId();
4305 bool pathChanged;
4306 const SearchPathCacheEntry *entry;
4307
4308 /* Do nothing if path is already valid. */
4309 if (baseSearchPathValid && namespaceUser == roleid)
4310 return;
4311
4312 entry = cachedNamespacePath(namespace_search_path, roleid);
4313
4314 if (baseCreationNamespace == entry->firstNS &&
4315 baseTempCreationPending == entry->temp_missing &&
4316 equal(entry->finalPath, baseSearchPath))
4317 {
4318 pathChanged = false;
4319 }
4320 else
4321 {
4322 MemoryContext oldcxt;
4323 List *newpath;
4324
4325 pathChanged = true;
4326
4327 /* Must save OID list in permanent storage. */
4328 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
4329 newpath = list_copy(entry->finalPath);
4330 MemoryContextSwitchTo(oldcxt);
4331
4332 /* Now safe to assign to state variables. */
4333 list_free(baseSearchPath);
4334 baseSearchPath = newpath;
4335 baseCreationNamespace = entry->firstNS;
4336 baseTempCreationPending = entry->temp_missing;
4337 }
4338
4339 /* Mark the path valid. */
4340 baseSearchPathValid = true;
4341 namespaceUser = roleid;
4342
4343 /* And make it active. */
4344 activeSearchPath = baseSearchPath;
4345 activeCreationNamespace = baseCreationNamespace;
4346 activeTempCreationPending = baseTempCreationPending;
4347
4348 /*
4349 * Bump the generation only if something actually changed. (Notice that
4350 * what we compared to was the old state of the base path variables.)
4351 */
4352 if (pathChanged)
4353 activePathGeneration++;
4354 }
4355
4356 /*
4357 * AccessTempTableNamespace
4358 * Provide access to a temporary namespace, potentially creating it
4359 * if not present yet. This routine registers if the namespace gets
4360 * in use in this transaction. 'force' can be set to true to allow
4361 * the caller to enforce the creation of the temporary namespace for
4362 * use in this backend, which happens if its creation is pending.
4363 */
4364 static void
4365 AccessTempTableNamespace(bool force)
4366 {
4367 /*
4368 * Make note that this temporary namespace has been accessed in this
4369 * transaction.
4370 */
4371 MyXactFlags |= XACT_FLAGS_ACCESSEDTEMPNAMESPACE;
4372
4373 /*
4374 * If the caller attempting to access a temporary schema expects the
4375 * creation of the namespace to be pending and should be enforced, then go
4376 * through the creation.
4377 */
4378 if (!force && OidIsValid(myTempNamespace))
4379 return;
4380
4381 /*
4382 * The temporary tablespace does not exist yet and is wanted, so
4383 * initialize it.
4384 */
4385 InitTempTableNamespace();
4386 }
4387
4388 /*
4389 * InitTempTableNamespace
4390 * Initialize temp table namespace on first use in a particular backend
4391 */
4392 static void
4393 InitTempTableNamespace(void)
4394 {
4395 char namespaceName[NAMEDATALEN];
4396 Oid namespaceId;
4397 Oid toastspaceId;
4398
4399 Assert(!OidIsValid(myTempNamespace));
4400
4401 /*
4402 * First, do permission check to see if we are authorized to make temp
4403 * tables. We use a nonstandard error message here since "databasename:
4404 * permission denied" might be a tad cryptic.
4405 *
4406 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
4407 * that's necessary since current user ID could change during the session.
4408 * But there's no need to make the namespace in the first place until a
4409 * temp table creation request is made by someone with appropriate rights.
4410 */
4411 if (object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
4412 ACL_CREATE_TEMP) != ACLCHECK_OK)
4413 ereport(ERROR,
4414 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4415 errmsg("permission denied to create temporary tables in database \"%s\"",
4416 get_database_name(MyDatabaseId))));
4417
4418 /*
4419 * Do not allow a Hot Standby session to make temp tables. Aside from
4420 * problems with modifying the system catalogs, there is a naming
4421 * conflict: pg_temp_N belongs to the session with proc number N on the
4422 * primary, not to a hot standby session with the same proc number. We
4423 * should not be able to get here anyway due to XactReadOnly checks, but
4424 * let's just make real sure. Note that this also backstops various
4425 * operations that allow XactReadOnly transactions to modify temp tables;
4426 * they'd need RecoveryInProgress checks if not for this.
4427 */
4428 if (RecoveryInProgress())
4429 ereport(ERROR,
4430 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
4431 errmsg("cannot create temporary tables during recovery")));
4432
4433 /* Parallel workers can't create temporary tables, either. */
4434 if (IsParallelWorker())
4435 ereport(ERROR,
4436 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
4437 errmsg("cannot create temporary tables during a parallel operation")));
4438
4439 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyProcNumber);
4440
4441 namespaceId = get_namespace_oid(namespaceName, true);
4442 if (!OidIsValid(namespaceId))
4443 {
4444 /*
4445 * First use of this temp namespace in this database; create it. The
4446 * temp namespaces are always owned by the superuser. We leave their
4447 * permissions at default --- i.e., no access except to superuser ---
4448 * to ensure that unprivileged users can't peek at other backends'
4449 * temp tables. This works because the places that access the temp
4450 * namespace for my own backend skip permissions checks on it.
4451 */
4452 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
4453 true);
4454 /* Advance command counter to make namespace visible */
4455 CommandCounterIncrement();
4456 }
4457 else
4458 {
4459 /*
4460 * If the namespace already exists, clean it out (in case the former
4461 * owner crashed without doing so).
4462 */
4463 RemoveTempRelations(namespaceId);
4464 }
4465
4466 /*
4467 * If the corresponding toast-table namespace doesn't exist yet, create
4468 * it. (We assume there is no need to clean it out if it does exist, since
4469 * dropping a parent table should make its toast table go away.)
4470 */
4471 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
4472 MyProcNumber);
4473
4474 toastspaceId = get_namespace_oid(namespaceName, true);
4475 if (!OidIsValid(toastspaceId))
4476 {
4477 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
4478 true);
4479 /* Advance command counter to make namespace visible */
4480 CommandCounterIncrement();
4481 }
4482
4483 /*
4484 * Okay, we've prepared the temp namespace ... but it's not committed yet,
4485 * so all our work could be undone by transaction rollback. Set flag for
4486 * AtEOXact_Namespace to know what to do.
4487 */
4488 myTempNamespace = namespaceId;
4489 myTempToastNamespace = toastspaceId;
4490
4491 /*
4492 * Mark MyProc as owning this namespace which other processes can use to
4493 * decide if a temporary namespace is in use or not. We assume that
4494 * assignment of namespaceId is an atomic operation. Even if it is not,
4495 * the temporary relation which resulted in the creation of this temporary
4496 * namespace is still locked until the current transaction commits, and
4497 * its pg_namespace row is not visible yet. However it does not matter:
4498 * this flag makes the namespace as being in use, so no objects created on
4499 * it would be removed concurrently.
4500 */
4501 MyProc->tempNamespaceId = namespaceId;
4502
4503 /* It should not be done already. */
4504 Assert(myTempNamespaceSubID == InvalidSubTransactionId);
4505 myTempNamespaceSubID = GetCurrentSubTransactionId();
4506
4507 baseSearchPathValid = false; /* need to rebuild list */
4508 searchPathCacheValid = false;
4509 }
4510
4511 /*
4512 * End-of-transaction cleanup for namespaces.
4513 */
4514 void
4515 AtEOXact_Namespace(bool isCommit, bool parallel)
4516 {
4517 /*
4518 * If we abort the transaction in which a temp namespace was selected,
4519 * we'll have to do any creation or cleanout work over again. So, just
4520 * forget the namespace entirely until next time. On the other hand, if
4521 * we commit then register an exit callback to clean out the temp tables
4522 * at backend shutdown. (We only want to register the callback once per
4523 * session, so this is a good place to do it.)
4524 */
4525 if (myTempNamespaceSubID != InvalidSubTransactionId && !parallel)
4526 {
4527 if (isCommit)
4528 before_shmem_exit(RemoveTempRelationsCallback, 0);
4529 else
4530 {
4531 myTempNamespace = InvalidOid;
4532 myTempToastNamespace = InvalidOid;
4533 baseSearchPathValid = false; /* need to rebuild list */
4534 searchPathCacheValid = false;
4535
4536 /*
4537 * Reset the temporary namespace flag in MyProc. We assume that
4538 * this operation is atomic.
4539 *
4540 * Because this transaction is aborting, the pg_namespace row is
4541 * not visible to anyone else anyway, but that doesn't matter:
4542 * it's not a problem if objects contained in this namespace are
4543 * removed concurrently.
4544 */
4545 MyProc->tempNamespaceId = InvalidOid;
4546 }
4547 myTempNamespaceSubID = InvalidSubTransactionId;
4548 }
4549
4550 }
4551
4552 /*
4553 * AtEOSubXact_Namespace
4554 *
4555 * At subtransaction commit, propagate the temp-namespace-creation
4556 * flag to the parent subtransaction.
4557 *
4558 * At subtransaction abort, forget the flag if we set it up.
4559 */
4560 void
4561 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
4562 SubTransactionId parentSubid)
4563 {
4564
4565 if (myTempNamespaceSubID == mySubid)
4566 {
4567 if (isCommit)
4568 myTempNamespaceSubID = parentSubid;
4569 else
4570 {
4571 myTempNamespaceSubID = InvalidSubTransactionId;
4572 /* TEMP namespace creation failed, so reset state */
4573 myTempNamespace = InvalidOid;
4574 myTempToastNamespace = InvalidOid;
4575 baseSearchPathValid = false; /* need to rebuild list */
4576 searchPathCacheValid = false;
4577
4578 /*
4579 * Reset the temporary namespace flag in MyProc. We assume that
4580 * this operation is atomic.
4581 *
4582 * Because this subtransaction is aborting, the pg_namespace row
4583 * is not visible to anyone else anyway, but that doesn't matter:
4584 * it's not a problem if objects contained in this namespace are
4585 * removed concurrently.
4586 */
4587 MyProc->tempNamespaceId = InvalidOid;
4588 }
4589 }
4590 }
4591
4592 /*
4593 * Remove all relations in the specified temp namespace.
4594 *
4595 * This is called at backend shutdown (if we made any temp relations).
4596 * It is also called when we begin using a pre-existing temp namespace,
4597 * in order to clean out any relations that might have been created by
4598 * a crashed backend.
4599 */
4600 static void
4601 RemoveTempRelations(Oid tempNamespaceId)
4602 {
4603 ObjectAddress object;
4604
4605 /*
4606 * We want to get rid of everything in the target namespace, but not the
4607 * namespace itself (deleting it only to recreate it later would be a
4608 * waste of cycles). Hence, specify SKIP_ORIGINAL. It's also an INTERNAL
4609 * deletion, and we want to not drop any extensions that might happen to
4610 * own temp objects.
4611 */
4612 object.classId = NamespaceRelationId;
4613 object.objectId = tempNamespaceId;
4614 object.objectSubId = 0;
4615
4616 performDeletion(&object, DROP_CASCADE,
4617 PERFORM_DELETION_INTERNAL |
4618 PERFORM_DELETION_QUIETLY |
4619 PERFORM_DELETION_SKIP_ORIGINAL |
4620 PERFORM_DELETION_SKIP_EXTENSIONS);
4621 }
4622
4623 /*
4624 * Callback to remove temp relations at backend exit.
4625 */
4626 static void
4627 RemoveTempRelationsCallback(int code, Datum arg)
4628 {
4629 if (OidIsValid(myTempNamespace)) /* should always be true */
4630 {
4631 /* Need to ensure we have a usable transaction. */
4632 AbortOutOfAnyTransaction();
4633 StartTransactionCommand();
4634 PushActiveSnapshot(GetTransactionSnapshot());
4635
4636 RemoveTempRelations(myTempNamespace);
4637
4638 PopActiveSnapshot();
4639 CommitTransactionCommand();
4640 }
4641 }
4642
4643 /*
4644 * Remove all temp tables from the temporary namespace.
4645 */
4646 void
4647 ResetTempTableNamespace(void)
4648 {
4649 if (OidIsValid(myTempNamespace))
4650 RemoveTempRelations(myTempNamespace);
4651 }
4652
4653
4654 /*
4655 * Routines for handling the GUC variable 'search_path'.
4656 */
4657
4658 /* check_hook: validate new search_path value */
4659 bool
4660 check_search_path(char **newval, void **extra, GucSource source)
4661 {
4662 Oid roleid = InvalidOid;
4663 const char *searchPath = *newval;
4664 char *rawname;
4665 List *namelist;
4666 bool use_cache = (SearchPathCacheContext != NULL);
4667
4668 /*
4669 * We used to try to check that the named schemas exist, but there are
4670 * many valid use-cases for having search_path settings that include
4671 * schemas that don't exist; and often, we are not inside a transaction
4672 * here and so can't consult the system catalogs anyway. So now, the only
4673 * requirement is syntactic validity of the identifier list.
4674 *
4675 * Checking only the syntactic validity also allows us to use the search
4676 * path cache (if available) to avoid calling SplitIdentifierString() on
4677 * the same string repeatedly.
4678 */
4679 if (use_cache)
4680 {
4681 spcache_init();
4682
4683 roleid = GetUserId();
4684
4685 if (spcache_lookup(searchPath, roleid) != NULL)
4686 return true;
4687 }
4688
4689 /*
4690 * Ensure validity check succeeds before creating cache entry.
4691 */
4692
4693 rawname = pstrdup(searchPath); /* need a modifiable copy */
4694
4695 /* Parse string into list of identifiers */
4696 if (!SplitIdentifierString(rawname, ',', &namelist))
4697 {
4698 /* syntax error in name list */
4699 GUC_check_errdetail("List syntax is invalid.");
4700 pfree(rawname);
4701 list_free(namelist);
4702 return false;
4703 }
4704 pfree(rawname);
4705 list_free(namelist);
4706
4707 /* OK to create empty cache entry */
4708 if (use_cache)
4709 (void) spcache_insert(searchPath, roleid);
4710
4711 return true;
4712 }
4713
4714 /* assign_hook: do extra actions as needed */
4715 void
4716 assign_search_path(const char *newval, void *extra)
4717 {
4718 /* don't access search_path during bootstrap */
4719 Assert(!IsBootstrapProcessingMode());
4720
4721 /*
4722 * We mark the path as needing recomputation, but don't do anything until
4723 * it's needed. This avoids trying to do database access during GUC
4724 * initialization, or outside a transaction.
4725 *
4726 * This does not invalidate the search path cache, so if this value had
4727 * been previously set and no syscache invalidations happened,
4728 * recomputation may not be necessary.
4729 */
4730 baseSearchPathValid = false;
4731 }
4732
4733 /*
4734 * InitializeSearchPath: initialize module during InitPostgres.
4735 *
4736 * This is called after we are up enough to be able to do catalog lookups.
4737 */
4738 void
4739 InitializeSearchPath(void)
4740 {
4741 if (IsBootstrapProcessingMode())
4742 {
4743 /*
4744 * In bootstrap mode, the search path must be 'pg_catalog' so that
4745 * tables are created in the proper namespace; ignore the GUC setting.
4746 */
4747 MemoryContext oldcxt;
4748
4749 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
4750 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
4751 MemoryContextSwitchTo(oldcxt);
4752 baseCreationNamespace = PG_CATALOG_NAMESPACE;
4753 baseTempCreationPending = false;
4754 baseSearchPathValid = true;
4755 namespaceUser = GetUserId();
4756 activeSearchPath = baseSearchPath;
4757 activeCreationNamespace = baseCreationNamespace;
4758 activeTempCreationPending = baseTempCreationPending;
4759 activePathGeneration++; /* pro forma */
4760 }
4761 else
4762 {
4763 /*
4764 * In normal mode, arrange for a callback on any syscache invalidation
4765 * that will affect the search_path cache.
4766 */
4767
4768 /* namespace name or ACLs may have changed */
4769 CacheRegisterSyscacheCallback(NAMESPACEOID,
4770 InvalidationCallback,
4771 (Datum) 0);
4772
4773 /* role name may affect the meaning of "$user" */
4774 CacheRegisterSyscacheCallback(AUTHOID,
4775 InvalidationCallback,
4776 (Datum) 0);
4777
4778 /* role membership may affect ACLs */
4779 CacheRegisterSyscacheCallback(AUTHMEMROLEMEM,
4780 InvalidationCallback,
4781 (Datum) 0);
4782
4783 /* database owner may affect ACLs */
4784 CacheRegisterSyscacheCallback(DATABASEOID,
4785 InvalidationCallback,
4786 (Datum) 0);
4787
4788 /* Force search path to be recomputed on next use */
4789 baseSearchPathValid = false;
4790 searchPathCacheValid = false;
4791 }
4792 }
4793
4794 /*
4795 * InvalidationCallback
4796 * Syscache inval callback function
4797 */
4798 static void
4799 InvalidationCallback(Datum arg, int cacheid, uint32 hashvalue)
4800 {
4801 /*
4802 * Force search path to be recomputed on next use, also invalidating the
4803 * search path cache (because namespace names, ACLs, or role names may
4804 * have changed).
4805 */
4806 baseSearchPathValid = false;
4807 searchPathCacheValid = false;
4808 }
4809
4810 /*
4811 * Fetch the active search path. The return value is a palloc'ed list
4812 * of OIDs; the caller is responsible for freeing this storage as
4813 * appropriate.
4814 *
4815 * The returned list includes the implicitly-prepended namespaces only if
4816 * includeImplicit is true.
4817 *
4818 * Note: calling this may result in a CommandCounterIncrement operation,
4819 * if we have to create or clean out the temp namespace.
4820 */
4821 List *
4822 fetch_search_path(bool includeImplicit)
4823 {
4824 List *result;
4825
4826 recomputeNamespacePath();
4827
4828 /*
4829 * If the temp namespace should be first, force it to exist. This is so
4830 * that callers can trust the result to reflect the actual default
4831 * creation namespace. It's a bit bogus to do this here, since
4832 * current_schema() is supposedly a stable function without side-effects,
4833 * but the alternatives seem worse.
4834 */
4835 if (activeTempCreationPending)
4836 {
4837 AccessTempTableNamespace(true);
4838 recomputeNamespacePath();
4839 }
4840
4841 result = list_copy(activeSearchPath);
4842 if (!includeImplicit)
4843 {
4844 while (result && linitial_oid(result) != activeCreationNamespace)
4845 result = list_delete_first(result);
4846 }
4847
4848 return result;
4849 }
4850
4851 /*
4852 * Fetch the active search path into a caller-allocated array of OIDs.
4853 * Returns the number of path entries. (If this is more than sarray_len,
4854 * then the data didn't fit and is not all stored.)
4855 *
4856 * The returned list always includes the implicitly-prepended namespaces,
4857 * but never includes the temp namespace. (This is suitable for existing
4858 * users, which would want to ignore the temp namespace anyway.) This
4859 * definition allows us to not worry about initializing the temp namespace.
4860 */
4861 int
4862 fetch_search_path_array(Oid *sarray, int sarray_len)
4863 {
4864 int count = 0;
4865 ListCell *l;
4866
4867 recomputeNamespacePath();
4868
4869 foreach(l, activeSearchPath)
4870 {
4871 Oid namespaceId = lfirst_oid(l);
4872
4873 if (namespaceId == myTempNamespace)
4874 continue; /* do not include temp namespace */
4875
4876 if (count < sarray_len)
4877 sarray[count] = namespaceId;
4878 count++;
4879 }
4880
4881 return count;
4882 }
4883
4884
4885 /*
4886 * Export the FooIsVisible functions as SQL-callable functions.
4887 *
4888 * Note: as of Postgres 8.4, these will silently return NULL if called on
4889 * a nonexistent object OID, rather than failing. This is to avoid race
4890 * condition errors when a query that's scanning a catalog using an MVCC
4891 * snapshot uses one of these functions. The underlying IsVisible functions
4892 * always use an up-to-date snapshot and so might see the object as already
4893 * gone when it's still visible to the transaction snapshot.
4894 */
4895
4896 Datum
4897 pg_table_is_visible(PG_FUNCTION_ARGS)
4898 {
4899 Oid oid = PG_GETARG_OID(0);
4900 bool result;
4901 bool is_missing = false;
4902
4903 result = RelationIsVisibleExt(oid, &is_missing);
4904
4905 if (is_missing)
4906 PG_RETURN_NULL();
4907 PG_RETURN_BOOL(result);
4908 }
4909
4910 Datum
4911 pg_type_is_visible(PG_FUNCTION_ARGS)
4912 {
4913 Oid oid = PG_GETARG_OID(0);
4914 bool result;
4915 bool is_missing = false;
4916
4917 result = TypeIsVisibleExt(oid, &is_missing);
4918
4919 if (is_missing)
4920 PG_RETURN_NULL();
4921 PG_RETURN_BOOL(result);
4922 }
4923
4924 Datum
4925 pg_function_is_visible(PG_FUNCTION_ARGS)
4926 {
4927 Oid oid = PG_GETARG_OID(0);
4928 bool result;
4929 bool is_missing = false;
4930
4931 result = FunctionIsVisibleExt(oid, &is_missing);
4932
4933 if (is_missing)
4934 PG_RETURN_NULL();
4935 PG_RETURN_BOOL(result);
4936 }
4937
4938 Datum
4939 pg_operator_is_visible(PG_FUNCTION_ARGS)
4940 {
4941 Oid oid = PG_GETARG_OID(0);
4942 bool result;
4943 bool is_missing = false;
4944
4945 result = OperatorIsVisibleExt(oid, &is_missing);
4946
4947 if (is_missing)
4948 PG_RETURN_NULL();
4949 PG_RETURN_BOOL(result);
4950 }
4951
4952 Datum
4953 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4954 {
4955 Oid oid = PG_GETARG_OID(0);
4956 bool result;
4957 bool is_missing = false;
4958
4959 result = OpclassIsVisibleExt(oid, &is_missing);
4960
4961 if (is_missing)
4962 PG_RETURN_NULL();
4963 PG_RETURN_BOOL(result);
4964 }
4965
4966 Datum
4967 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4968 {
4969 Oid oid = PG_GETARG_OID(0);
4970 bool result;
4971 bool is_missing = false;
4972
4973 result = OpfamilyIsVisibleExt(oid, &is_missing);
4974
4975 if (is_missing)
4976 PG_RETURN_NULL();
4977 PG_RETURN_BOOL(result);
4978 }
4979
4980 Datum
4981 pg_collation_is_visible(PG_FUNCTION_ARGS)
4982 {
4983 Oid oid = PG_GETARG_OID(0);
4984 bool result;
4985 bool is_missing = false;
4986
4987 result = CollationIsVisibleExt(oid, &is_missing);
4988
4989 if (is_missing)
4990 PG_RETURN_NULL();
4991 PG_RETURN_BOOL(result);
4992 }
4993
4994 Datum
4995 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4996 {
4997 Oid oid = PG_GETARG_OID(0);
4998 bool result;
4999 bool is_missing = false;
5000
5001 result = ConversionIsVisibleExt(oid, &is_missing);
5002
5003 if (is_missing)
5004 PG_RETURN_NULL();
5005 PG_RETURN_BOOL(result);
5006 }
5007
5008 Datum
5009 pg_statistics_obj_is_visible(PG_FUNCTION_ARGS)
5010 {
5011 Oid oid = PG_GETARG_OID(0);
5012 bool result;
5013 bool is_missing = false;
5014
5015 result = StatisticsObjIsVisibleExt(oid, &is_missing);
5016
5017 if (is_missing)
5018 PG_RETURN_NULL();
5019 PG_RETURN_BOOL(result);
5020 }
5021
5022 Datum
5023 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
5024 {
5025 Oid oid = PG_GETARG_OID(0);
5026 bool result;
5027 bool is_missing = false;
5028
5029 result = TSParserIsVisibleExt(oid, &is_missing);
5030
5031 if (is_missing)
5032 PG_RETURN_NULL();
5033 PG_RETURN_BOOL(result);
5034 }
5035
5036 Datum
5037 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
5038 {
5039 Oid oid = PG_GETARG_OID(0);
5040 bool result;
5041 bool is_missing = false;
5042
5043 result = TSDictionaryIsVisibleExt(oid, &is_missing);
5044
5045 if (is_missing)
5046 PG_RETURN_NULL();
5047 PG_RETURN_BOOL(result);
5048 }
5049
5050 Datum
5051 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
5052 {
5053 Oid oid = PG_GETARG_OID(0);
5054 bool result;
5055 bool is_missing = false;
5056
5057 result = TSTemplateIsVisibleExt(oid, &is_missing);
5058
5059 if (is_missing)
5060 PG_RETURN_NULL();
5061 PG_RETURN_BOOL(result);
5062 }
5063
5064 Datum
5065 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
5066 {
5067 Oid oid = PG_GETARG_OID(0);
5068 bool result;
5069 bool is_missing = false;
5070
5071 result = TSConfigIsVisibleExt(oid, &is_missing);
5072
5073 if (is_missing)
5074 PG_RETURN_NULL();
5075 PG_RETURN_BOOL(result);
5076 }
5077
5078 Datum
5079 pg_my_temp_schema(PG_FUNCTION_ARGS)
5080 {
5081 PG_RETURN_OID(myTempNamespace);
5082 }
5083
5084 Datum
5085 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
5086 {
5087 Oid oid = PG_GETARG_OID(0);
5088
5089 PG_RETURN_BOOL(isOtherTempNamespace(oid));
5090 }