1 /*-------------------------------------------------------------------------
4 * code to support accessing and searching namespaces
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.
12 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
16 * src/backend/catalog/namespace.c
18 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/dependency.h"
24 #include "catalog/pg_authid.h"
25 #include "catalog/pg_collation.h"
26 #include "catalog/pg_conversion.h"
27 #include "catalog/pg_conversion_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "catalog/pg_opclass.h"
30 #include "catalog/pg_operator.h"
31 #include "catalog/pg_opfamily.h"
32 #include "catalog/pg_proc.h"
33 #include "catalog/pg_ts_config.h"
34 #include "catalog/pg_ts_dict.h"
35 #include "catalog/pg_ts_parser.h"
36 #include "catalog/pg_ts_template.h"
37 #include "catalog/pg_type.h"
38 #include "commands/dbcommands.h"
40 #include "mb/pg_wchar.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "parser/parse_func.h"
44 #include "storage/ipc.h"
45 #include "storage/lmgr.h"
46 #include "storage/sinval.h"
47 #include "utils/acl.h"
48 #include "utils/builtins.h"
49 #include "utils/guc.h"
50 #include "utils/inval.h"
51 #include "utils/lsyscache.h"
52 #include "utils/memutils.h"
53 #include "utils/syscache.h"
57 * The namespace search path is a possibly-empty list of namespace OIDs.
58 * In addition to the explicit list, implicitly-searched namespaces
61 * 1. If a TEMP table namespace has been initialized in this session, it
62 * is implicitly searched first. (The only time this doesn't happen is
63 * when we are obeying an override search path spec that says not to use the
64 * temp namespace, or the temp namespace is included in the explicit list.)
66 * 2. The system catalog namespace is always searched. If the system
67 * namespace is present in the explicit path then it will be searched in
68 * the specified order; otherwise it will be searched after TEMP tables and
69 * *before* the explicit list. (It might seem that the system namespace
70 * should be implicitly last, but this behavior appears to be required by
71 * SQL99. Also, this provides a way to search the system namespace first
72 * without thereby making it the default creation target namespace.)
74 * For security reasons, searches using the search path will ignore the temp
75 * namespace when searching for any object type other than relations and
76 * types. (We must allow types since temp tables have rowtypes.)
78 * The default creation target namespace is always the first element of the
79 * explicit list. If the explicit list is empty, there is no default target.
81 * The textual specification of search_path can include "$user" to refer to
82 * the namespace named the same as the current user, if any. (This is just
83 * ignored if there is no such namespace.) Also, it can include "pg_temp"
84 * to refer to the current backend's temp namespace. This is usually also
85 * ignorable if the temp namespace hasn't been set up, but there's a special
86 * case: if "pg_temp" appears first then it should be the default creation
87 * target. We kluge this case a little bit so that the temp namespace isn't
88 * set up until the first attempt to create something in it. (The reason for
89 * klugery is that we can't create the temp namespace outside a transaction,
90 * but initial GUC processing of search_path happens outside a transaction.)
91 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
92 * but is not reflected in activeCreationNamespace because the namespace isn't
95 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
96 * the system namespace is the only one searched or inserted into.
97 * initdb is also careful to set search_path to "pg_catalog" for its
98 * post-bootstrap standalone backend runs. Otherwise the default search
99 * path is determined by GUC. The factory default path contains the PUBLIC
100 * namespace (if it exists), preceded by the user's personal namespace
103 * We support a stack of "override" search path settings for use within
104 * specific sections of backend code. namespace_search_path is ignored
105 * whenever the override stack is nonempty. activeSearchPath is always
106 * the actually active path; it points either to the search list of the
107 * topmost stack entry, or to baseSearchPath which is the list derived
108 * from namespace_search_path.
110 * If baseSearchPathValid is false, then baseSearchPath (and other
111 * derived variables) need to be recomputed from namespace_search_path.
112 * We mark it invalid upon an assignment to namespace_search_path or receipt
113 * of a syscache invalidation event for pg_namespace. The recomputation
114 * is done during the next non-overridden lookup attempt. Note that an
115 * override spec is never subject to recomputation.
117 * Any namespaces mentioned in namespace_search_path that are not readable
118 * by the current user ID are simply left out of baseSearchPath; so
119 * we have to be willing to recompute the path when current userid changes.
120 * namespaceUser is the userid the path has been computed for.
122 * Note: all data pointed to by these List variables is in TopMemoryContext.
125 /* These variables define the actually active state: */
127 static List *activeSearchPath = NIL;
129 /* default place to create stuff; if InvalidOid, no default */
130 static Oid activeCreationNamespace = InvalidOid;
132 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
133 static bool activeTempCreationPending = false;
135 /* These variables are the values last derived from namespace_search_path: */
137 static List *baseSearchPath = NIL;
139 static Oid baseCreationNamespace = InvalidOid;
141 static bool baseTempCreationPending = false;
143 static Oid namespaceUser = InvalidOid;
145 /* The above four values are valid only if baseSearchPathValid */
146 static bool baseSearchPathValid = true;
148 /* Override requests are remembered in a stack of OverrideStackEntry structs */
152 List *searchPath; /* the desired search path */
153 Oid creationNamespace; /* the desired creation namespace */
154 int nestLevel; /* subtransaction nesting level */
155 } OverrideStackEntry;
157 static List *overrideStack = NIL;
160 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
161 * in a particular backend session (this happens when a CREATE TEMP TABLE
162 * command is first executed). Thereafter it's the OID of the temp namespace.
164 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
165 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
167 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
168 * current subtransaction. The flag propagates up the subtransaction tree,
169 * so the main transaction will correctly recognize the flag if all
170 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
171 * we either haven't made the TEMP namespace yet, or have successfully
172 * committed its creation, depending on whether myTempNamespace is valid.
174 static Oid myTempNamespace = InvalidOid;
176 static Oid myTempToastNamespace = InvalidOid;
178 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
181 * This is the user's textual search path specification --- it's the value
182 * of the GUC variable 'search_path'.
184 char *namespace_search_path = NULL;
187 /* Local functions */
188 static void recomputeNamespacePath(void);
189 static void InitTempTableNamespace(void);
190 static void RemoveTempRelations(Oid tempNamespaceId);
191 static void RemoveTempRelationsCallback(int code, Datum arg);
192 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
193 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
196 /* These don't really need to appear in any header file */
197 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
198 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
199 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
200 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
210 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
215 * Given a RangeVar describing an existing relation,
216 * select the proper namespace and look up the relation OID.
218 * If the relation is not found, return InvalidOid if missing_ok = true,
219 * otherwise raise an error.
221 * If nowait = true, throw an error if we'd have to wait for a lock.
223 * Callback allows caller to check permissions or acquire additional locks
224 * prior to grabbing the relation lock.
227 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
228 bool missing_ok, bool nowait,
229 RangeVarGetRelidCallback callback, void *callback_arg)
233 Oid oldRelId = InvalidOid;
237 * We check the catalog name and then ignore it.
239 if (relation->catalogname)
241 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
243 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
244 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
245 relation->catalogname, relation->schemaname,
246 relation->relname)));
250 * DDL operations can change the results of a name lookup. Since all such
251 * operations will generate invalidation messages, we keep track of
252 * whether any such messages show up while we're performing the operation,
253 * and retry until either (1) no more invalidation messages show up or (2)
254 * the answer doesn't change.
256 * But if lockmode = NoLock, then we assume that either the caller is OK
257 * with the answer changing under them, or that they already hold some
258 * appropriate lock, and therefore return the first answer we get without
259 * checking for invalidation messages. Also, if the requested lock is
260 * already held, no LockRelationOid will not AcceptInvalidationMessages,
261 * so we may fail to notice a change. We could protect against that case
262 * by calling AcceptInvalidationMessages() before beginning this loop, but
263 * that would add a significant amount overhead, so for now we don't.
268 * Remember this value, so that, after looking up the relation name
269 * and locking its OID, we can check whether any invalidation messages
270 * have been processed that might require a do-over.
272 inval_count = SharedInvalidMessageCounter;
275 * Some non-default relpersistence value may have been specified. The
276 * parser never generates such a RangeVar in simple DML, but it can
277 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
278 * KEY)". Such a command will generate an added CREATE INDEX
279 * operation, which must be careful to find the temp table, even when
280 * pg_temp is not first in the search path.
282 if (relation->relpersistence == RELPERSISTENCE_TEMP)
284 if (!OidIsValid(myTempNamespace))
285 relId = InvalidOid; /* this probably can't happen? */
288 if (relation->schemaname)
292 namespaceId = LookupExplicitNamespace(relation->schemaname);
293 if (namespaceId != myTempNamespace)
295 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
296 errmsg("temporary tables cannot specify a schema name")));
299 relId = get_relname_relid(relation->relname, myTempNamespace);
302 else if (relation->schemaname)
306 /* use exact schema given */
307 namespaceId = LookupExplicitNamespace(relation->schemaname);
308 relId = get_relname_relid(relation->relname, namespaceId);
312 /* search the namespace path */
313 relId = RelnameGetRelid(relation->relname);
317 * Invoke caller-supplied callback, if any.
319 * This callback is a good place to check permissions: we haven't
320 * taken the table lock yet (and it's really best to check permissions
321 * before locking anything!), but we've gotten far enough to know what
322 * OID we think we should lock. Of course, concurrent DDL might
323 * change things while we're waiting for the lock, but in that case
324 * the callback will be invoked again for the new OID.
327 callback(relation, relId, oldRelId, callback_arg);
330 * If no lock requested, we assume the caller knows what they're
331 * doing. They should have already acquired a heavyweight lock on
332 * this relation earlier in the processing of this same statement, so
333 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
334 * that might pull the rug out from under them.
336 if (lockmode == NoLock)
340 * If, upon retry, we get back the same OID we did last time, then the
341 * invalidation messages we processed did not change the final answer.
344 * If we got a different OID, we've locked the relation that used to
345 * have this name rather than the one that does now. So release the
350 if (relId == oldRelId)
352 if (OidIsValid(oldRelId))
353 UnlockRelationOid(oldRelId, lockmode);
357 * Lock relation. This will also accept any pending invalidation
358 * messages. If we got back InvalidOid, indicating not found, then
359 * there's nothing to lock, but we accept invalidation messages
360 * anyway, to flush any negative catcache entries that may be
363 if (!OidIsValid(relId))
364 AcceptInvalidationMessages();
366 LockRelationOid(relId, lockmode);
367 else if (!ConditionalLockRelationOid(relId, lockmode))
369 if (relation->schemaname)
371 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
372 errmsg("could not obtain lock on relation \"%s.%s\"",
373 relation->schemaname, relation->relname)));
376 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
377 errmsg("could not obtain lock on relation \"%s\"",
378 relation->relname)));
382 * If no invalidation message were processed, we're done!
384 if (inval_count == SharedInvalidMessageCounter)
388 * Something may have changed. Let's repeat the name lookup, to make
389 * sure this name still references the same relation it did
396 if (!OidIsValid(relId) && !missing_ok)
398 if (relation->schemaname)
400 (errcode(ERRCODE_UNDEFINED_TABLE),
401 errmsg("relation \"%s.%s\" does not exist",
402 relation->schemaname, relation->relname)));
405 (errcode(ERRCODE_UNDEFINED_TABLE),
406 errmsg("relation \"%s\" does not exist",
407 relation->relname)));
413 * RangeVarGetCreationNamespace
414 * Given a RangeVar describing a to-be-created relation,
415 * choose which namespace to create it in.
417 * Note: calling this may result in a CommandCounterIncrement operation.
418 * That will happen on the first request for a temp table in any particular
419 * backend run; we will need to either create or clean out the temp schema.
422 RangeVarGetCreationNamespace(const RangeVar *newRelation)
427 * We check the catalog name and then ignore it.
429 if (newRelation->catalogname)
431 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
433 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
434 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
435 newRelation->catalogname, newRelation->schemaname,
436 newRelation->relname)));
439 if (newRelation->schemaname)
441 /* check for pg_temp alias */
442 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
444 /* Initialize temp namespace if first time through */
445 if (!OidIsValid(myTempNamespace))
446 InitTempTableNamespace();
447 return myTempNamespace;
449 /* use exact schema given */
450 namespaceId = get_namespace_oid(newRelation->schemaname, false);
451 /* we do not check for USAGE rights here! */
453 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
455 /* Initialize temp namespace if first time through */
456 if (!OidIsValid(myTempNamespace))
457 InitTempTableNamespace();
458 return myTempNamespace;
462 /* use the default creation namespace */
463 recomputeNamespacePath();
464 if (activeTempCreationPending)
466 /* Need to initialize temp namespace */
467 InitTempTableNamespace();
468 return myTempNamespace;
470 namespaceId = activeCreationNamespace;
471 if (!OidIsValid(namespaceId))
473 (errcode(ERRCODE_UNDEFINED_SCHEMA),
474 errmsg("no schema has been selected to create in")));
477 /* Note: callers will check for CREATE rights when appropriate */
483 * RangeVarGetAndCheckCreationNamespace
485 * This function returns the OID of the namespace in which a new relation
486 * with a given name should be created. If the user does not have CREATE
487 * permission on the target namespace, this function will instead signal
490 * If non-NULL, *existing_oid is set to the OID of any existing relation with
491 * the same name which already exists in that namespace, or to InvalidOid if
492 * no such relation exists.
494 * If lockmode != NoLock, the specified lock mode is acquire on the existing
495 * relation, if any, provided that the current user owns the target relation.
496 * However, if lockmode != NoLock and the user does not own the target
497 * relation, we throw an ERROR, as we must not try to lock relations the
498 * user does not have permissions on.
500 * As a side effect, this function acquires AccessShareLock on the target
501 * namespace. Without this, the namespace could be dropped before our
502 * transaction commits, leaving behind relations with relnamespace pointing
503 * to a no-longer-exstant namespace.
505 * As a further side-effect, if the select namespace is a temporary namespace,
506 * we mark the RangeVar as RELPERSISTENCE_TEMP.
509 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
511 Oid *existing_relation_id)
515 Oid oldrelid = InvalidOid;
517 Oid oldnspid = InvalidOid;
521 * We check the catalog name and then ignore it.
523 if (relation->catalogname)
525 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
527 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
528 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
529 relation->catalogname, relation->schemaname,
530 relation->relname)));
534 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
535 * operations by tracking whether any invalidation messages are processed
536 * while we're doing the name lookups and acquiring locks. See comments
537 * in that function for a more detailed explanation of this logic.
543 inval_count = SharedInvalidMessageCounter;
545 /* Look up creation namespace and check for existing relation. */
546 nspid = RangeVarGetCreationNamespace(relation);
547 Assert(OidIsValid(nspid));
548 if (existing_relation_id != NULL)
549 relid = get_relname_relid(relation->relname, nspid);
554 * In bootstrap processing mode, we don't bother with permissions or
555 * locking. Permissions might not be working yet, and locking is
558 if (IsBootstrapProcessingMode())
561 /* Check namespace permissions. */
562 aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
563 if (aclresult != ACLCHECK_OK)
564 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
565 get_namespace_name(nspid));
569 /* If nothing changed, we're done. */
570 if (relid == oldrelid && nspid == oldnspid)
572 /* If creation namespace has changed, give up old lock. */
573 if (nspid != oldnspid)
574 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
576 /* If name points to something different, give up old lock. */
577 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
578 UnlockRelationOid(oldrelid, lockmode);
581 /* Lock namespace. */
582 if (nspid != oldnspid)
583 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
585 /* Lock relation, if required if and we have permission. */
586 if (lockmode != NoLock && OidIsValid(relid))
588 if (!pg_class_ownercheck(relid, GetUserId()))
589 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
591 if (relid != oldrelid)
592 LockRelationOid(relid, lockmode);
595 /* If no invalidation message were processed, we're done! */
596 if (inval_count == SharedInvalidMessageCounter)
599 /* Something may have changed, so recheck our work. */
605 RangeVarAdjustRelationPersistence(relation, nspid);
606 if (existing_relation_id != NULL)
607 *existing_relation_id = relid;
612 * Adjust the relpersistence for an about-to-be-created relation based on the
613 * creation namespace, and throw an error for invalid combinations.
616 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
618 switch (newRelation->relpersistence)
620 case RELPERSISTENCE_TEMP:
621 if (!isTempOrToastNamespace(nspid))
623 if (isAnyTempNamespace(nspid))
625 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
626 errmsg("cannot create relations in temporary schemas of other sessions")));
629 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
630 errmsg("cannot create temporary relation in non-temporary schema")));
633 case RELPERSISTENCE_PERMANENT:
634 if (isTempOrToastNamespace(nspid))
635 newRelation->relpersistence = RELPERSISTENCE_TEMP;
636 else if (isAnyTempNamespace(nspid))
638 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
639 errmsg("cannot create relations in temporary schemas of other sessions")));
642 if (isAnyTempNamespace(nspid))
644 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
645 errmsg("only temporary relations may be created in temporary schemas")));
651 * Try to resolve an unqualified relation name.
652 * Returns OID if relation found in search path, else InvalidOid.
655 RelnameGetRelid(const char *relname)
660 recomputeNamespacePath();
662 foreach(l, activeSearchPath)
664 Oid namespaceId = lfirst_oid(l);
666 relid = get_relname_relid(relname, namespaceId);
667 if (OidIsValid(relid))
671 /* Not found in path */
678 * Determine whether a relation (identified by OID) is visible in the
679 * current search path. Visible means "would be found by searching
680 * for the unqualified relation name".
683 RelationIsVisible(Oid relid)
686 Form_pg_class relform;
690 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
691 if (!HeapTupleIsValid(reltup))
692 elog(ERROR, "cache lookup failed for relation %u", relid);
693 relform = (Form_pg_class) GETSTRUCT(reltup);
695 recomputeNamespacePath();
698 * Quick check: if it ain't in the path at all, it ain't visible. Items in
699 * the system namespace are surely in the path and so we needn't even do
700 * list_member_oid() for them.
702 relnamespace = relform->relnamespace;
703 if (relnamespace != PG_CATALOG_NAMESPACE &&
704 !list_member_oid(activeSearchPath, relnamespace))
709 * If it is in the path, it might still not be visible; it could be
710 * hidden by another relation of the same name earlier in the path. So
711 * we must do a slow check for conflicting relations.
713 char *relname = NameStr(relform->relname);
717 foreach(l, activeSearchPath)
719 Oid namespaceId = lfirst_oid(l);
721 if (namespaceId == relnamespace)
723 /* Found it first in path */
727 if (OidIsValid(get_relname_relid(relname, namespaceId)))
729 /* Found something else first in path */
735 ReleaseSysCache(reltup);
743 * Try to resolve an unqualified datatype name.
744 * Returns OID if type found in search path, else InvalidOid.
746 * This is essentially the same as RelnameGetRelid.
749 TypenameGetTypid(const char *typname)
754 recomputeNamespacePath();
756 foreach(l, activeSearchPath)
758 Oid namespaceId = lfirst_oid(l);
760 typid = GetSysCacheOid2(TYPENAMENSP,
761 PointerGetDatum(typname),
762 ObjectIdGetDatum(namespaceId));
763 if (OidIsValid(typid))
767 /* Not found in path */
773 * Determine whether a type (identified by OID) is visible in the
774 * current search path. Visible means "would be found by searching
775 * for the unqualified type name".
778 TypeIsVisible(Oid typid)
781 Form_pg_type typform;
785 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
786 if (!HeapTupleIsValid(typtup))
787 elog(ERROR, "cache lookup failed for type %u", typid);
788 typform = (Form_pg_type) GETSTRUCT(typtup);
790 recomputeNamespacePath();
793 * Quick check: if it ain't in the path at all, it ain't visible. Items in
794 * the system namespace are surely in the path and so we needn't even do
795 * list_member_oid() for them.
797 typnamespace = typform->typnamespace;
798 if (typnamespace != PG_CATALOG_NAMESPACE &&
799 !list_member_oid(activeSearchPath, typnamespace))
804 * If it is in the path, it might still not be visible; it could be
805 * hidden by another type of the same name earlier in the path. So we
806 * must do a slow check for conflicting types.
808 char *typname = NameStr(typform->typname);
812 foreach(l, activeSearchPath)
814 Oid namespaceId = lfirst_oid(l);
816 if (namespaceId == typnamespace)
818 /* Found it first in path */
822 if (SearchSysCacheExists2(TYPENAMENSP,
823 PointerGetDatum(typname),
824 ObjectIdGetDatum(namespaceId)))
826 /* Found something else first in path */
832 ReleaseSysCache(typtup);
839 * FuncnameGetCandidates
840 * Given a possibly-qualified function name and argument count,
841 * retrieve a list of the possible matches.
843 * If nargs is -1, we return all functions matching the given name,
844 * regardless of argument count. (argnames must be NIL, and expand_variadic
845 * and expand_defaults must be false, in this case.)
847 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
848 * and only functions having all the listed argument names will be returned.
849 * (We assume that length(argnames) <= nargs and all the passed-in names are
850 * distinct.) The returned structs will include an argnumbers array showing
851 * the actual argument index for each logical argument position.
853 * If expand_variadic is true, then variadic functions having the same number
854 * or fewer arguments will be retrieved, with the variadic argument and any
855 * additional argument positions filled with the variadic element type.
856 * nvargs in the returned struct is set to the number of such arguments.
857 * If expand_variadic is false, variadic arguments are not treated specially,
858 * and the returned nvargs will always be zero.
860 * If expand_defaults is true, functions that could match after insertion of
861 * default argument values will also be retrieved. In this case the returned
862 * structs could have nargs > passed-in nargs, and ndargs is set to the number
863 * of additional args (which can be retrieved from the function's
864 * proargdefaults entry).
866 * It is not possible for nvargs and ndargs to both be nonzero in the same
867 * list entry, since default insertion allows matches to functions with more
868 * than nargs arguments while the variadic transformation requires the same
871 * When argnames isn't NIL, the returned args[] type arrays are not ordered
872 * according to the functions' declarations, but rather according to the call:
873 * first any positional arguments, then the named arguments, then defaulted
874 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
875 * array can be used to map this back to the catalog information.
876 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
878 * We search a single namespace if the function name is qualified, else
879 * all namespaces in the search path. In the multiple-namespace case,
880 * we arrange for entries in earlier namespaces to mask identical entries in
883 * When expanding variadics, we arrange for non-variadic functions to mask
884 * variadic ones if the expanded argument list is the same. It is still
885 * possible for there to be conflicts between different variadic functions,
888 * It is guaranteed that the return list will never contain multiple entries
889 * with identical argument lists. When expand_defaults is true, the entries
890 * could have more than nargs positions, but we still guarantee that they are
891 * distinct in the first nargs positions. However, if argnames isn't NIL or
892 * either expand_variadic or expand_defaults is true, there might be multiple
893 * candidate functions that expand to identical argument lists. Rather than
894 * throw error here, we report such situations by returning a single entry
895 * with oid = 0 that represents a set of such conflicting candidates.
896 * The caller might end up discarding such an entry anyway, but if it selects
897 * such an entry it should react as though the call were ambiguous.
900 FuncnameGetCandidates(List *names, int nargs, List *argnames,
901 bool expand_variadic, bool expand_defaults)
903 FuncCandidateList resultList = NULL;
904 bool any_special = false;
911 /* check for caller error */
912 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
914 /* deconstruct the name list */
915 DeconstructQualifiedName(names, &schemaname, &funcname);
919 /* use exact schema given */
920 namespaceId = LookupExplicitNamespace(schemaname);
924 /* flag to indicate we need namespace search */
925 namespaceId = InvalidOid;
926 recomputeNamespacePath();
929 /* Search syscache by name only */
930 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
932 for (i = 0; i < catlist->n_members; i++)
934 HeapTuple proctup = &catlist->members[i]->tuple;
935 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
936 int pronargs = procform->pronargs;
942 int *argnumbers = NULL;
943 FuncCandidateList newResult;
945 if (OidIsValid(namespaceId))
947 /* Consider only procs in specified namespace */
948 if (procform->pronamespace != namespaceId)
954 * Consider only procs that are in the search path and are not in
955 * the temp namespace.
959 foreach(nsp, activeSearchPath)
961 if (procform->pronamespace == lfirst_oid(nsp) &&
962 procform->pronamespace != myTempNamespace)
967 continue; /* proc is not in search path */
973 * Call uses named or mixed notation
975 * Named or mixed notation can match a variadic function only if
976 * expand_variadic is off; otherwise there is no way to match the
977 * presumed-nameless parameters expanded from the variadic array.
979 if (OidIsValid(procform->provariadic) && expand_variadic)
981 va_elem_type = InvalidOid;
985 * Check argument count.
987 Assert(nargs >= 0); /* -1 not supported with argnames */
989 if (pronargs > nargs && expand_defaults)
991 /* Ignore if not enough default expressions */
992 if (nargs + procform->pronargdefaults < pronargs)
997 use_defaults = false;
999 /* Ignore if it doesn't match requested argument count */
1000 if (pronargs != nargs && !use_defaults)
1003 /* Check for argument name match, generate positional mapping */
1004 if (!MatchNamedCall(proctup, nargs, argnames,
1008 /* Named argument matching is always "special" */
1014 * Call uses positional notation
1016 * Check if function is variadic, and get variadic element type if
1017 * so. If expand_variadic is false, we should just ignore
1020 if (pronargs <= nargs && expand_variadic)
1022 va_elem_type = procform->provariadic;
1023 variadic = OidIsValid(va_elem_type);
1024 any_special |= variadic;
1028 va_elem_type = InvalidOid;
1033 * Check if function can match by using parameter defaults.
1035 if (pronargs > nargs && expand_defaults)
1037 /* Ignore if not enough default expressions */
1038 if (nargs + procform->pronargdefaults < pronargs)
1040 use_defaults = true;
1044 use_defaults = false;
1046 /* Ignore if it doesn't match requested argument count */
1047 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1052 * We must compute the effective argument list so that we can easily
1053 * compare it to earlier results. We waste a palloc cycle if it gets
1054 * masked by an earlier result, but really that's a pretty infrequent
1055 * case so it's not worth worrying about.
1057 effective_nargs = Max(pronargs, nargs);
1058 newResult = (FuncCandidateList)
1059 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
1060 + effective_nargs * sizeof(Oid));
1061 newResult->pathpos = pathpos;
1062 newResult->oid = HeapTupleGetOid(proctup);
1063 newResult->nargs = effective_nargs;
1064 newResult->argnumbers = argnumbers;
1067 /* Re-order the argument types into call's logical order */
1068 Oid *proargtypes = procform->proargtypes.values;
1071 for (i = 0; i < pronargs; i++)
1072 newResult->args[i] = proargtypes[argnumbers[i]];
1076 /* Simple positional case, just copy proargtypes as-is */
1077 memcpy(newResult->args, procform->proargtypes.values,
1078 pronargs * sizeof(Oid));
1084 newResult->nvargs = effective_nargs - pronargs + 1;
1085 /* Expand variadic argument into N copies of element type */
1086 for (i = pronargs - 1; i < effective_nargs; i++)
1087 newResult->args[i] = va_elem_type;
1090 newResult->nvargs = 0;
1091 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1094 * Does it have the same arguments as something we already accepted?
1095 * If so, decide what to do to avoid returning duplicate argument
1096 * lists. We can skip this check for the single-namespace case if no
1097 * special (named, variadic or defaults) match has been made, since
1098 * then the unique index on pg_proc guarantees all the matches have
1099 * different argument lists.
1101 if (resultList != NULL &&
1102 (any_special || !OidIsValid(namespaceId)))
1105 * If we have an ordered list from SearchSysCacheList (the normal
1106 * case), then any conflicting proc must immediately adjoin this
1107 * one in the list, so we only need to look at the newest result
1108 * item. If we have an unordered list, we have to scan the whole
1109 * result list. Also, if either the current candidate or any
1110 * previous candidate is a special match, we can't assume that
1111 * conflicts are adjacent.
1113 * We ignore defaulted arguments in deciding what is a match.
1115 FuncCandidateList prevResult;
1117 if (catlist->ordered && !any_special)
1119 /* ndargs must be 0 if !any_special */
1120 if (effective_nargs == resultList->nargs &&
1121 memcmp(newResult->args,
1123 effective_nargs * sizeof(Oid)) == 0)
1124 prevResult = resultList;
1130 int cmp_nargs = newResult->nargs - newResult->ndargs;
1132 for (prevResult = resultList;
1134 prevResult = prevResult->next)
1136 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1137 memcmp(newResult->args,
1139 cmp_nargs * sizeof(Oid)) == 0)
1147 * We have a match with a previous result. Decide which one
1148 * to keep, or mark it ambiguous if we can't decide. The
1149 * logic here is preference > 0 means prefer the old result,
1150 * preference < 0 means prefer the new, preference = 0 means
1155 if (pathpos != prevResult->pathpos)
1158 * Prefer the one that's earlier in the search path.
1160 preference = pathpos - prevResult->pathpos;
1162 else if (variadic && prevResult->nvargs == 0)
1165 * With variadic functions we could have, for example,
1166 * both foo(numeric) and foo(variadic numeric[]) in the
1167 * same namespace; if so we prefer the non-variadic match
1168 * on efficiency grounds.
1172 else if (!variadic && prevResult->nvargs > 0)
1179 * We can't decide. This can happen with, for example,
1180 * both foo(numeric, variadic numeric[]) and
1181 * foo(variadic numeric[]) in the same namespace, or
1182 * both foo(int) and foo (int, int default something)
1183 * in the same namespace, or both foo(a int, b text)
1184 * and foo(b text, a int) in the same namespace.
1192 /* keep previous result */
1196 else if (preference < 0)
1198 /* remove previous result from the list */
1199 if (prevResult == resultList)
1200 resultList = prevResult->next;
1203 FuncCandidateList prevPrevResult;
1205 for (prevPrevResult = resultList;
1207 prevPrevResult = prevPrevResult->next)
1209 if (prevResult == prevPrevResult->next)
1211 prevPrevResult->next = prevResult->next;
1215 Assert(prevPrevResult); /* assert we found it */
1218 /* fall through to add newResult to list */
1222 /* mark old result as ambiguous, discard new */
1223 prevResult->oid = InvalidOid;
1231 * Okay to add it to result list
1233 newResult->next = resultList;
1234 resultList = newResult;
1237 ReleaseSysCacheList(catlist);
1244 * Given a pg_proc heap tuple and a call's list of argument names,
1245 * check whether the function could match the call.
1247 * The call could match if all supplied argument names are accepted by
1248 * the function, in positions after the last positional argument, and there
1249 * are defaults for all unsupplied arguments.
1251 * The number of positional arguments is nargs - list_length(argnames).
1252 * Note caller has already done basic checks on argument count.
1254 * On match, return true and fill *argnumbers with a palloc'd array showing
1255 * the mapping from call argument positions to actual function argument
1256 * numbers. Defaulted arguments are included in this map, at positions
1257 * after the last supplied argument.
1260 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1263 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1264 int pronargs = procform->pronargs;
1265 int numposargs = nargs - list_length(argnames);
1270 bool arggiven[FUNC_MAX_ARGS];
1272 int ap; /* call args position */
1273 int pp; /* proargs position */
1276 Assert(argnames != NIL);
1277 Assert(numposargs >= 0);
1278 Assert(nargs <= pronargs);
1280 /* Ignore this function if its proargnames is null */
1281 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1286 /* OK, let's extract the argument names and types */
1287 pronallargs = get_func_arg_info(proctup,
1288 &p_argtypes, &p_argnames, &p_argmodes);
1289 Assert(p_argnames != NULL);
1291 /* initialize state for matching */
1292 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1293 memset(arggiven, false, pronargs * sizeof(bool));
1295 /* there are numposargs positional args before the named args */
1296 for (ap = 0; ap < numposargs; ap++)
1298 (*argnumbers)[ap] = ap;
1299 arggiven[ap] = true;
1302 /* now examine the named args */
1303 foreach(lc, argnames)
1305 char *argname = (char *) lfirst(lc);
1311 for (i = 0; i < pronallargs; i++)
1313 /* consider only input parameters */
1315 (p_argmodes[i] != FUNC_PARAM_IN &&
1316 p_argmodes[i] != FUNC_PARAM_INOUT &&
1317 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1319 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1321 /* fail if argname matches a positional argument */
1324 arggiven[pp] = true;
1325 (*argnumbers)[ap] = pp;
1329 /* increase pp only for input parameters */
1332 /* if name isn't in proargnames, fail */
1338 Assert(ap == nargs); /* processed all actual parameters */
1340 /* Check for default arguments */
1341 if (nargs < pronargs)
1343 int first_arg_with_default = pronargs - procform->pronargdefaults;
1345 for (pp = numposargs; pp < pronargs; pp++)
1349 /* fail if arg not given and no default available */
1350 if (pp < first_arg_with_default)
1352 (*argnumbers)[ap++] = pp;
1356 Assert(ap == pronargs); /* processed all function parameters */
1363 * Determine whether a function (identified by OID) is visible in the
1364 * current search path. Visible means "would be found by searching
1365 * for the unqualified function name with exact argument matches".
1368 FunctionIsVisible(Oid funcid)
1371 Form_pg_proc procform;
1375 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1376 if (!HeapTupleIsValid(proctup))
1377 elog(ERROR, "cache lookup failed for function %u", funcid);
1378 procform = (Form_pg_proc) GETSTRUCT(proctup);
1380 recomputeNamespacePath();
1383 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1384 * the system namespace are surely in the path and so we needn't even do
1385 * list_member_oid() for them.
1387 pronamespace = procform->pronamespace;
1388 if (pronamespace != PG_CATALOG_NAMESPACE &&
1389 !list_member_oid(activeSearchPath, pronamespace))
1394 * If it is in the path, it might still not be visible; it could be
1395 * hidden by another proc of the same name and arguments earlier in
1396 * the path. So we must do a slow check to see if this is the same
1397 * proc that would be found by FuncnameGetCandidates.
1399 char *proname = NameStr(procform->proname);
1400 int nargs = procform->pronargs;
1401 FuncCandidateList clist;
1405 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1406 nargs, NIL, false, false);
1408 for (; clist; clist = clist->next)
1410 if (memcmp(clist->args, procform->proargtypes.values,
1411 nargs * sizeof(Oid)) == 0)
1413 /* Found the expected entry; is it the right proc? */
1414 visible = (clist->oid == funcid);
1420 ReleaseSysCache(proctup);
1428 * Given a possibly-qualified operator name and exact input datatypes,
1429 * look up the operator. Returns InvalidOid if not found.
1431 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1434 * If the operator name is not schema-qualified, it is sought in the current
1435 * namespace search path.
1438 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1445 /* deconstruct the name list */
1446 DeconstructQualifiedName(names, &schemaname, &opername);
1450 /* search only in exact schema given */
1454 namespaceId = LookupExplicitNamespace(schemaname);
1455 opertup = SearchSysCache4(OPERNAMENSP,
1456 CStringGetDatum(opername),
1457 ObjectIdGetDatum(oprleft),
1458 ObjectIdGetDatum(oprright),
1459 ObjectIdGetDatum(namespaceId));
1460 if (HeapTupleIsValid(opertup))
1462 Oid result = HeapTupleGetOid(opertup);
1464 ReleaseSysCache(opertup);
1470 /* Search syscache by name and argument types */
1471 catlist = SearchSysCacheList3(OPERNAMENSP,
1472 CStringGetDatum(opername),
1473 ObjectIdGetDatum(oprleft),
1474 ObjectIdGetDatum(oprright));
1476 if (catlist->n_members == 0)
1478 /* no hope, fall out early */
1479 ReleaseSysCacheList(catlist);
1484 * We have to find the list member that is first in the search path, if
1485 * there's more than one. This doubly-nested loop looks ugly, but in
1486 * practice there should usually be few catlist members.
1488 recomputeNamespacePath();
1490 foreach(l, activeSearchPath)
1492 Oid namespaceId = lfirst_oid(l);
1495 if (namespaceId == myTempNamespace)
1496 continue; /* do not look in temp namespace */
1498 for (i = 0; i < catlist->n_members; i++)
1500 HeapTuple opertup = &catlist->members[i]->tuple;
1501 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1503 if (operform->oprnamespace == namespaceId)
1505 Oid result = HeapTupleGetOid(opertup);
1507 ReleaseSysCacheList(catlist);
1513 ReleaseSysCacheList(catlist);
1518 * OpernameGetCandidates
1519 * Given a possibly-qualified operator name and operator kind,
1520 * retrieve a list of the possible matches.
1522 * If oprkind is '\0', we return all operators matching the given name,
1523 * regardless of arguments.
1525 * We search a single namespace if the operator name is qualified, else
1526 * all namespaces in the search path. The return list will never contain
1527 * multiple entries with identical argument lists --- in the multiple-
1528 * namespace case, we arrange for entries in earlier namespaces to mask
1529 * identical entries in later namespaces.
1531 * The returned items always have two args[] entries --- one or the other
1532 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1535 OpernameGetCandidates(List *names, char oprkind)
1537 FuncCandidateList resultList = NULL;
1538 char *resultSpace = NULL;
1546 /* deconstruct the name list */
1547 DeconstructQualifiedName(names, &schemaname, &opername);
1551 /* use exact schema given */
1552 namespaceId = LookupExplicitNamespace(schemaname);
1556 /* flag to indicate we need namespace search */
1557 namespaceId = InvalidOid;
1558 recomputeNamespacePath();
1561 /* Search syscache by name only */
1562 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1565 * In typical scenarios, most if not all of the operators found by the
1566 * catcache search will end up getting returned; and there can be quite a
1567 * few, for common operator names such as '=' or '+'. To reduce the time
1568 * spent in palloc, we allocate the result space as an array large enough
1569 * to hold all the operators. The original coding of this routine did a
1570 * separate palloc for each operator, but profiling revealed that the
1571 * pallocs used an unreasonably large fraction of parsing time.
1573 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1575 if (catlist->n_members > 0)
1576 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1578 for (i = 0; i < catlist->n_members; i++)
1580 HeapTuple opertup = &catlist->members[i]->tuple;
1581 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1583 FuncCandidateList newResult;
1585 /* Ignore operators of wrong kind, if specific kind requested */
1586 if (oprkind && operform->oprkind != oprkind)
1589 if (OidIsValid(namespaceId))
1591 /* Consider only opers in specified namespace */
1592 if (operform->oprnamespace != namespaceId)
1594 /* No need to check args, they must all be different */
1599 * Consider only opers that are in the search path and are not in
1600 * the temp namespace.
1604 foreach(nsp, activeSearchPath)
1606 if (operform->oprnamespace == lfirst_oid(nsp) &&
1607 operform->oprnamespace != myTempNamespace)
1612 continue; /* oper is not in search path */
1615 * Okay, it's in the search path, but does it have the same
1616 * arguments as something we already accepted? If so, keep only
1617 * the one that appears earlier in the search path.
1619 * If we have an ordered list from SearchSysCacheList (the normal
1620 * case), then any conflicting oper must immediately adjoin this
1621 * one in the list, so we only need to look at the newest result
1622 * item. If we have an unordered list, we have to scan the whole
1627 FuncCandidateList prevResult;
1629 if (catlist->ordered)
1631 if (operform->oprleft == resultList->args[0] &&
1632 operform->oprright == resultList->args[1])
1633 prevResult = resultList;
1639 for (prevResult = resultList;
1641 prevResult = prevResult->next)
1643 if (operform->oprleft == prevResult->args[0] &&
1644 operform->oprright == prevResult->args[1])
1650 /* We have a match with a previous result */
1651 Assert(pathpos != prevResult->pathpos);
1652 if (pathpos > prevResult->pathpos)
1653 continue; /* keep previous result */
1654 /* replace previous result */
1655 prevResult->pathpos = pathpos;
1656 prevResult->oid = HeapTupleGetOid(opertup);
1657 continue; /* args are same, of course */
1663 * Okay to add it to result list
1665 newResult = (FuncCandidateList) (resultSpace + nextResult);
1666 nextResult += SPACE_PER_OP;
1668 newResult->pathpos = pathpos;
1669 newResult->oid = HeapTupleGetOid(opertup);
1670 newResult->nargs = 2;
1671 newResult->nvargs = 0;
1672 newResult->ndargs = 0;
1673 newResult->argnumbers = NULL;
1674 newResult->args[0] = operform->oprleft;
1675 newResult->args[1] = operform->oprright;
1676 newResult->next = resultList;
1677 resultList = newResult;
1680 ReleaseSysCacheList(catlist);
1687 * Determine whether an operator (identified by OID) is visible in the
1688 * current search path. Visible means "would be found by searching
1689 * for the unqualified operator name with exact argument matches".
1692 OperatorIsVisible(Oid oprid)
1695 Form_pg_operator oprform;
1699 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1700 if (!HeapTupleIsValid(oprtup))
1701 elog(ERROR, "cache lookup failed for operator %u", oprid);
1702 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1704 recomputeNamespacePath();
1707 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1708 * the system namespace are surely in the path and so we needn't even do
1709 * list_member_oid() for them.
1711 oprnamespace = oprform->oprnamespace;
1712 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1713 !list_member_oid(activeSearchPath, oprnamespace))
1718 * If it is in the path, it might still not be visible; it could be
1719 * hidden by another operator of the same name and arguments earlier
1720 * in the path. So we must do a slow check to see if this is the same
1721 * operator that would be found by OpernameGetOprId.
1723 char *oprname = NameStr(oprform->oprname);
1725 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1726 oprform->oprleft, oprform->oprright)
1730 ReleaseSysCache(oprtup);
1737 * OpclassnameGetOpcid
1738 * Try to resolve an unqualified index opclass name.
1739 * Returns OID if opclass found in search path, else InvalidOid.
1741 * This is essentially the same as TypenameGetTypid, but we have to have
1742 * an extra argument for the index AM OID.
1745 OpclassnameGetOpcid(Oid amid, const char *opcname)
1750 recomputeNamespacePath();
1752 foreach(l, activeSearchPath)
1754 Oid namespaceId = lfirst_oid(l);
1756 if (namespaceId == myTempNamespace)
1757 continue; /* do not look in temp namespace */
1759 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1760 ObjectIdGetDatum(amid),
1761 PointerGetDatum(opcname),
1762 ObjectIdGetDatum(namespaceId));
1763 if (OidIsValid(opcid))
1767 /* Not found in path */
1773 * Determine whether an opclass (identified by OID) is visible in the
1774 * current search path. Visible means "would be found by searching
1775 * for the unqualified opclass name".
1778 OpclassIsVisible(Oid opcid)
1781 Form_pg_opclass opcform;
1785 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1786 if (!HeapTupleIsValid(opctup))
1787 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1788 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1790 recomputeNamespacePath();
1793 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1794 * the system namespace are surely in the path and so we needn't even do
1795 * list_member_oid() for them.
1797 opcnamespace = opcform->opcnamespace;
1798 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1799 !list_member_oid(activeSearchPath, opcnamespace))
1804 * If it is in the path, it might still not be visible; it could be
1805 * hidden by another opclass of the same name earlier in the path. So
1806 * we must do a slow check to see if this opclass would be found by
1807 * OpclassnameGetOpcid.
1809 char *opcname = NameStr(opcform->opcname);
1811 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1814 ReleaseSysCache(opctup);
1820 * OpfamilynameGetOpfid
1821 * Try to resolve an unqualified index opfamily name.
1822 * Returns OID if opfamily found in search path, else InvalidOid.
1824 * This is essentially the same as TypenameGetTypid, but we have to have
1825 * an extra argument for the index AM OID.
1828 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1833 recomputeNamespacePath();
1835 foreach(l, activeSearchPath)
1837 Oid namespaceId = lfirst_oid(l);
1839 if (namespaceId == myTempNamespace)
1840 continue; /* do not look in temp namespace */
1842 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1843 ObjectIdGetDatum(amid),
1844 PointerGetDatum(opfname),
1845 ObjectIdGetDatum(namespaceId));
1846 if (OidIsValid(opfid))
1850 /* Not found in path */
1856 * Determine whether an opfamily (identified by OID) is visible in the
1857 * current search path. Visible means "would be found by searching
1858 * for the unqualified opfamily name".
1861 OpfamilyIsVisible(Oid opfid)
1864 Form_pg_opfamily opfform;
1868 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1869 if (!HeapTupleIsValid(opftup))
1870 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1871 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1873 recomputeNamespacePath();
1876 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1877 * the system namespace are surely in the path and so we needn't even do
1878 * list_member_oid() for them.
1880 opfnamespace = opfform->opfnamespace;
1881 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1882 !list_member_oid(activeSearchPath, opfnamespace))
1887 * If it is in the path, it might still not be visible; it could be
1888 * hidden by another opfamily of the same name earlier in the path. So
1889 * we must do a slow check to see if this opfamily would be found by
1890 * OpfamilynameGetOpfid.
1892 char *opfname = NameStr(opfform->opfname);
1894 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1897 ReleaseSysCache(opftup);
1903 * CollationGetCollid
1904 * Try to resolve an unqualified collation name.
1905 * Returns OID if collation found in search path, else InvalidOid.
1908 CollationGetCollid(const char *collname)
1910 int32 dbencoding = GetDatabaseEncoding();
1913 recomputeNamespacePath();
1915 foreach(l, activeSearchPath)
1917 Oid namespaceId = lfirst_oid(l);
1920 if (namespaceId == myTempNamespace)
1921 continue; /* do not look in temp namespace */
1923 /* Check for database-encoding-specific entry */
1924 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1925 PointerGetDatum(collname),
1926 Int32GetDatum(dbencoding),
1927 ObjectIdGetDatum(namespaceId));
1928 if (OidIsValid(collid))
1931 /* Check for any-encoding entry */
1932 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1933 PointerGetDatum(collname),
1935 ObjectIdGetDatum(namespaceId));
1936 if (OidIsValid(collid))
1940 /* Not found in path */
1945 * CollationIsVisible
1946 * Determine whether a collation (identified by OID) is visible in the
1947 * current search path. Visible means "would be found by searching
1948 * for the unqualified collation name".
1951 CollationIsVisible(Oid collid)
1954 Form_pg_collation collform;
1958 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1959 if (!HeapTupleIsValid(colltup))
1960 elog(ERROR, "cache lookup failed for collation %u", collid);
1961 collform = (Form_pg_collation) GETSTRUCT(colltup);
1963 recomputeNamespacePath();
1966 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1967 * the system namespace are surely in the path and so we needn't even do
1968 * list_member_oid() for them.
1970 collnamespace = collform->collnamespace;
1971 if (collnamespace != PG_CATALOG_NAMESPACE &&
1972 !list_member_oid(activeSearchPath, collnamespace))
1977 * If it is in the path, it might still not be visible; it could be
1978 * hidden by another conversion of the same name earlier in the path.
1979 * So we must do a slow check to see if this conversion would be found
1980 * by CollationGetCollid.
1982 char *collname = NameStr(collform->collname);
1984 visible = (CollationGetCollid(collname) == collid);
1987 ReleaseSysCache(colltup);
1994 * ConversionGetConid
1995 * Try to resolve an unqualified conversion name.
1996 * Returns OID if conversion found in search path, else InvalidOid.
1998 * This is essentially the same as RelnameGetRelid.
2001 ConversionGetConid(const char *conname)
2006 recomputeNamespacePath();
2008 foreach(l, activeSearchPath)
2010 Oid namespaceId = lfirst_oid(l);
2012 if (namespaceId == myTempNamespace)
2013 continue; /* do not look in temp namespace */
2015 conid = GetSysCacheOid2(CONNAMENSP,
2016 PointerGetDatum(conname),
2017 ObjectIdGetDatum(namespaceId));
2018 if (OidIsValid(conid))
2022 /* Not found in path */
2027 * ConversionIsVisible
2028 * Determine whether a conversion (identified by OID) is visible in the
2029 * current search path. Visible means "would be found by searching
2030 * for the unqualified conversion name".
2033 ConversionIsVisible(Oid conid)
2036 Form_pg_conversion conform;
2040 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2041 if (!HeapTupleIsValid(contup))
2042 elog(ERROR, "cache lookup failed for conversion %u", conid);
2043 conform = (Form_pg_conversion) GETSTRUCT(contup);
2045 recomputeNamespacePath();
2048 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2049 * the system namespace are surely in the path and so we needn't even do
2050 * list_member_oid() for them.
2052 connamespace = conform->connamespace;
2053 if (connamespace != PG_CATALOG_NAMESPACE &&
2054 !list_member_oid(activeSearchPath, connamespace))
2059 * If it is in the path, it might still not be visible; it could be
2060 * hidden by another conversion of the same name earlier in the path.
2061 * So we must do a slow check to see if this conversion would be found
2062 * by ConversionGetConid.
2064 char *conname = NameStr(conform->conname);
2066 visible = (ConversionGetConid(conname) == conid);
2069 ReleaseSysCache(contup);
2075 * get_ts_parser_oid - find a TS parser by possibly qualified name
2077 * If not found, returns InvalidOid if missing_ok, else throws error
2080 get_ts_parser_oid(List *names, bool missing_ok)
2085 Oid prsoid = InvalidOid;
2088 /* deconstruct the name list */
2089 DeconstructQualifiedName(names, &schemaname, &parser_name);
2093 /* use exact schema given */
2094 namespaceId = LookupExplicitNamespace(schemaname);
2095 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2096 PointerGetDatum(parser_name),
2097 ObjectIdGetDatum(namespaceId));
2101 /* search for it in search path */
2102 recomputeNamespacePath();
2104 foreach(l, activeSearchPath)
2106 namespaceId = lfirst_oid(l);
2108 if (namespaceId == myTempNamespace)
2109 continue; /* do not look in temp namespace */
2111 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2112 PointerGetDatum(parser_name),
2113 ObjectIdGetDatum(namespaceId));
2114 if (OidIsValid(prsoid))
2119 if (!OidIsValid(prsoid) && !missing_ok)
2121 (errcode(ERRCODE_UNDEFINED_OBJECT),
2122 errmsg("text search parser \"%s\" does not exist",
2123 NameListToString(names))));
2130 * Determine whether a parser (identified by OID) is visible in the
2131 * current search path. Visible means "would be found by searching
2132 * for the unqualified parser name".
2135 TSParserIsVisible(Oid prsId)
2138 Form_pg_ts_parser form;
2142 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2143 if (!HeapTupleIsValid(tup))
2144 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2145 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2147 recomputeNamespacePath();
2150 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2151 * the system namespace are surely in the path and so we needn't even do
2152 * list_member_oid() for them.
2154 namespace = form->prsnamespace;
2155 if (namespace != PG_CATALOG_NAMESPACE &&
2156 !list_member_oid(activeSearchPath, namespace))
2161 * If it is in the path, it might still not be visible; it could be
2162 * hidden by another parser of the same name earlier in the path. So
2163 * we must do a slow check for conflicting parsers.
2165 char *name = NameStr(form->prsname);
2169 foreach(l, activeSearchPath)
2171 Oid namespaceId = lfirst_oid(l);
2173 if (namespaceId == myTempNamespace)
2174 continue; /* do not look in temp namespace */
2176 if (namespaceId == namespace)
2178 /* Found it first in path */
2182 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2183 PointerGetDatum(name),
2184 ObjectIdGetDatum(namespaceId)))
2186 /* Found something else first in path */
2192 ReleaseSysCache(tup);
2198 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2200 * If not found, returns InvalidOid if failOK, else throws error
2203 get_ts_dict_oid(List *names, bool missing_ok)
2208 Oid dictoid = InvalidOid;
2211 /* deconstruct the name list */
2212 DeconstructQualifiedName(names, &schemaname, &dict_name);
2216 /* use exact schema given */
2217 namespaceId = LookupExplicitNamespace(schemaname);
2218 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2219 PointerGetDatum(dict_name),
2220 ObjectIdGetDatum(namespaceId));
2224 /* search for it in search path */
2225 recomputeNamespacePath();
2227 foreach(l, activeSearchPath)
2229 namespaceId = lfirst_oid(l);
2231 if (namespaceId == myTempNamespace)
2232 continue; /* do not look in temp namespace */
2234 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2235 PointerGetDatum(dict_name),
2236 ObjectIdGetDatum(namespaceId));
2237 if (OidIsValid(dictoid))
2242 if (!OidIsValid(dictoid) && !missing_ok)
2244 (errcode(ERRCODE_UNDEFINED_OBJECT),
2245 errmsg("text search dictionary \"%s\" does not exist",
2246 NameListToString(names))));
2252 * TSDictionaryIsVisible
2253 * Determine whether a dictionary (identified by OID) is visible in the
2254 * current search path. Visible means "would be found by searching
2255 * for the unqualified dictionary name".
2258 TSDictionaryIsVisible(Oid dictId)
2261 Form_pg_ts_dict form;
2265 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2266 if (!HeapTupleIsValid(tup))
2267 elog(ERROR, "cache lookup failed for text search dictionary %u",
2269 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2271 recomputeNamespacePath();
2274 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2275 * the system namespace are surely in the path and so we needn't even do
2276 * list_member_oid() for them.
2278 namespace = form->dictnamespace;
2279 if (namespace != PG_CATALOG_NAMESPACE &&
2280 !list_member_oid(activeSearchPath, namespace))
2285 * If it is in the path, it might still not be visible; it could be
2286 * hidden by another dictionary of the same name earlier in the path.
2287 * So we must do a slow check for conflicting dictionaries.
2289 char *name = NameStr(form->dictname);
2293 foreach(l, activeSearchPath)
2295 Oid namespaceId = lfirst_oid(l);
2297 if (namespaceId == myTempNamespace)
2298 continue; /* do not look in temp namespace */
2300 if (namespaceId == namespace)
2302 /* Found it first in path */
2306 if (SearchSysCacheExists2(TSDICTNAMENSP,
2307 PointerGetDatum(name),
2308 ObjectIdGetDatum(namespaceId)))
2310 /* Found something else first in path */
2316 ReleaseSysCache(tup);
2322 * get_ts_template_oid - find a TS template by possibly qualified name
2324 * If not found, returns InvalidOid if missing_ok, else throws error
2327 get_ts_template_oid(List *names, bool missing_ok)
2330 char *template_name;
2332 Oid tmploid = InvalidOid;
2335 /* deconstruct the name list */
2336 DeconstructQualifiedName(names, &schemaname, &template_name);
2340 /* use exact schema given */
2341 namespaceId = LookupExplicitNamespace(schemaname);
2342 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2343 PointerGetDatum(template_name),
2344 ObjectIdGetDatum(namespaceId));
2348 /* search for it in search path */
2349 recomputeNamespacePath();
2351 foreach(l, activeSearchPath)
2353 namespaceId = lfirst_oid(l);
2355 if (namespaceId == myTempNamespace)
2356 continue; /* do not look in temp namespace */
2358 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2359 PointerGetDatum(template_name),
2360 ObjectIdGetDatum(namespaceId));
2361 if (OidIsValid(tmploid))
2366 if (!OidIsValid(tmploid) && !missing_ok)
2368 (errcode(ERRCODE_UNDEFINED_OBJECT),
2369 errmsg("text search template \"%s\" does not exist",
2370 NameListToString(names))));
2376 * TSTemplateIsVisible
2377 * Determine whether a template (identified by OID) is visible in the
2378 * current search path. Visible means "would be found by searching
2379 * for the unqualified template name".
2382 TSTemplateIsVisible(Oid tmplId)
2385 Form_pg_ts_template form;
2389 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2390 if (!HeapTupleIsValid(tup))
2391 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2392 form = (Form_pg_ts_template) GETSTRUCT(tup);
2394 recomputeNamespacePath();
2397 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2398 * the system namespace are surely in the path and so we needn't even do
2399 * list_member_oid() for them.
2401 namespace = form->tmplnamespace;
2402 if (namespace != PG_CATALOG_NAMESPACE &&
2403 !list_member_oid(activeSearchPath, namespace))
2408 * If it is in the path, it might still not be visible; it could be
2409 * hidden by another template of the same name earlier in the path. So
2410 * we must do a slow check for conflicting templates.
2412 char *name = NameStr(form->tmplname);
2416 foreach(l, activeSearchPath)
2418 Oid namespaceId = lfirst_oid(l);
2420 if (namespaceId == myTempNamespace)
2421 continue; /* do not look in temp namespace */
2423 if (namespaceId == namespace)
2425 /* Found it first in path */
2429 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2430 PointerGetDatum(name),
2431 ObjectIdGetDatum(namespaceId)))
2433 /* Found something else first in path */
2439 ReleaseSysCache(tup);
2445 * get_ts_config_oid - find a TS config by possibly qualified name
2447 * If not found, returns InvalidOid if missing_ok, else throws error
2450 get_ts_config_oid(List *names, bool missing_ok)
2455 Oid cfgoid = InvalidOid;
2458 /* deconstruct the name list */
2459 DeconstructQualifiedName(names, &schemaname, &config_name);
2463 /* use exact schema given */
2464 namespaceId = LookupExplicitNamespace(schemaname);
2465 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2466 PointerGetDatum(config_name),
2467 ObjectIdGetDatum(namespaceId));
2471 /* search for it in search path */
2472 recomputeNamespacePath();
2474 foreach(l, activeSearchPath)
2476 namespaceId = lfirst_oid(l);
2478 if (namespaceId == myTempNamespace)
2479 continue; /* do not look in temp namespace */
2481 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2482 PointerGetDatum(config_name),
2483 ObjectIdGetDatum(namespaceId));
2484 if (OidIsValid(cfgoid))
2489 if (!OidIsValid(cfgoid) && !missing_ok)
2491 (errcode(ERRCODE_UNDEFINED_OBJECT),
2492 errmsg("text search configuration \"%s\" does not exist",
2493 NameListToString(names))));
2500 * Determine whether a text search configuration (identified by OID)
2501 * is visible in the current search path. Visible means "would be found
2502 * by searching for the unqualified text search configuration name".
2505 TSConfigIsVisible(Oid cfgid)
2508 Form_pg_ts_config form;
2512 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2513 if (!HeapTupleIsValid(tup))
2514 elog(ERROR, "cache lookup failed for text search configuration %u",
2516 form = (Form_pg_ts_config) GETSTRUCT(tup);
2518 recomputeNamespacePath();
2521 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2522 * the system namespace are surely in the path and so we needn't even do
2523 * list_member_oid() for them.
2525 namespace = form->cfgnamespace;
2526 if (namespace != PG_CATALOG_NAMESPACE &&
2527 !list_member_oid(activeSearchPath, namespace))
2532 * If it is in the path, it might still not be visible; it could be
2533 * hidden by another configuration of the same name earlier in the
2534 * path. So we must do a slow check for conflicting configurations.
2536 char *name = NameStr(form->cfgname);
2540 foreach(l, activeSearchPath)
2542 Oid namespaceId = lfirst_oid(l);
2544 if (namespaceId == myTempNamespace)
2545 continue; /* do not look in temp namespace */
2547 if (namespaceId == namespace)
2549 /* Found it first in path */
2553 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2554 PointerGetDatum(name),
2555 ObjectIdGetDatum(namespaceId)))
2557 /* Found something else first in path */
2563 ReleaseSysCache(tup);
2570 * DeconstructQualifiedName
2571 * Given a possibly-qualified name expressed as a list of String nodes,
2572 * extract the schema name and object name.
2574 * *nspname_p is set to NULL if there is no explicit schema name.
2577 DeconstructQualifiedName(List *names,
2582 char *schemaname = NULL;
2583 char *objname = NULL;
2585 switch (list_length(names))
2588 objname = strVal(linitial(names));
2591 schemaname = strVal(linitial(names));
2592 objname = strVal(lsecond(names));
2595 catalogname = strVal(linitial(names));
2596 schemaname = strVal(lsecond(names));
2597 objname = strVal(lthird(names));
2600 * We check the catalog name and then ignore it.
2602 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2604 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2605 errmsg("cross-database references are not implemented: %s",
2606 NameListToString(names))));
2610 (errcode(ERRCODE_SYNTAX_ERROR),
2611 errmsg("improper qualified name (too many dotted names): %s",
2612 NameListToString(names))));
2616 *nspname_p = schemaname;
2617 *objname_p = objname;
2621 * LookupNamespaceNoError
2622 * Look up a schema name.
2624 * Returns the namespace OID, or InvalidOid if not found.
2626 * Note this does NOT perform any permissions check --- callers are
2627 * responsible for being sure that an appropriate check is made.
2628 * In the majority of cases LookupExplicitNamespace is preferable.
2631 LookupNamespaceNoError(const char *nspname)
2633 /* check for pg_temp alias */
2634 if (strcmp(nspname, "pg_temp") == 0)
2636 if (OidIsValid(myTempNamespace))
2637 return myTempNamespace;
2640 * Since this is used only for looking up existing objects, there is
2641 * no point in trying to initialize the temp namespace here; and doing
2642 * so might create problems for some callers. Just report "not found".
2647 return get_namespace_oid(nspname, true);
2651 * LookupExplicitNamespace
2652 * Process an explicitly-specified schema name: look up the schema
2653 * and verify we have USAGE (lookup) rights in it.
2655 * Returns the namespace OID. Raises ereport if any problem.
2658 LookupExplicitNamespace(const char *nspname)
2661 AclResult aclresult;
2663 /* check for pg_temp alias */
2664 if (strcmp(nspname, "pg_temp") == 0)
2666 if (OidIsValid(myTempNamespace))
2667 return myTempNamespace;
2670 * Since this is used only for looking up existing objects, there is
2671 * no point in trying to initialize the temp namespace here; and doing
2672 * so might create problems for some callers. Just fall through and
2673 * give the "does not exist" error.
2677 namespaceId = get_namespace_oid(nspname, false);
2679 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2680 if (aclresult != ACLCHECK_OK)
2681 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2688 * LookupCreationNamespace
2689 * Look up the schema and verify we have CREATE rights on it.
2691 * This is just like LookupExplicitNamespace except for the different
2692 * permission check, and that we are willing to create pg_temp if needed.
2694 * Note: calling this may result in a CommandCounterIncrement operation,
2695 * if we have to create or clean out the temp namespace.
2698 LookupCreationNamespace(const char *nspname)
2701 AclResult aclresult;
2703 /* check for pg_temp alias */
2704 if (strcmp(nspname, "pg_temp") == 0)
2706 /* Initialize temp namespace if first time through */
2707 if (!OidIsValid(myTempNamespace))
2708 InitTempTableNamespace();
2709 return myTempNamespace;
2712 namespaceId = get_namespace_oid(nspname, false);
2714 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2715 if (aclresult != ACLCHECK_OK)
2716 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2723 * Common checks on switching namespaces.
2725 * We complain if (1) the old and new namespaces are the same, (2) either the
2726 * old or new namespaces is a temporary schema (or temporary toast schema), or
2727 * (3) either the old or new namespaces is the TOAST schema.
2730 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2732 if (oldNspOid == nspOid)
2734 (classid == RelationRelationId ?
2735 errcode(ERRCODE_DUPLICATE_TABLE) :
2736 classid == ProcedureRelationId ?
2737 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2738 errcode(ERRCODE_DUPLICATE_OBJECT),
2739 errmsg("%s is already in schema \"%s\"",
2740 getObjectDescriptionOids(classid, objid),
2741 get_namespace_name(nspOid))));
2743 /* disallow renaming into or out of temp schemas */
2744 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2746 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2747 errmsg("cannot move objects into or out of temporary schemas")));
2749 /* same for TOAST schema */
2750 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2752 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2753 errmsg("cannot move objects into or out of TOAST schema")));
2757 * QualifiedNameGetCreationNamespace
2758 * Given a possibly-qualified name for an object (in List-of-Values
2759 * format), determine what namespace the object should be created in.
2760 * Also extract and return the object name (last component of list).
2762 * Note: this does not apply any permissions check. Callers must check
2763 * for CREATE rights on the selected namespace when appropriate.
2765 * Note: calling this may result in a CommandCounterIncrement operation,
2766 * if we have to create or clean out the temp namespace.
2769 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2774 /* deconstruct the name list */
2775 DeconstructQualifiedName(names, &schemaname, objname_p);
2779 /* check for pg_temp alias */
2780 if (strcmp(schemaname, "pg_temp") == 0)
2782 /* Initialize temp namespace if first time through */
2783 if (!OidIsValid(myTempNamespace))
2784 InitTempTableNamespace();
2785 return myTempNamespace;
2787 /* use exact schema given */
2788 namespaceId = get_namespace_oid(schemaname, false);
2789 /* we do not check for USAGE rights here! */
2793 /* use the default creation namespace */
2794 recomputeNamespacePath();
2795 if (activeTempCreationPending)
2797 /* Need to initialize temp namespace */
2798 InitTempTableNamespace();
2799 return myTempNamespace;
2801 namespaceId = activeCreationNamespace;
2802 if (!OidIsValid(namespaceId))
2804 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2805 errmsg("no schema has been selected to create in")));
2812 * get_namespace_oid - given a namespace name, look up the OID
2814 * If missing_ok is false, throw an error if namespace name not found. If
2815 * true, just return InvalidOid.
2818 get_namespace_oid(const char *nspname, bool missing_ok)
2822 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2823 if (!OidIsValid(oid) && !missing_ok)
2825 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2826 errmsg("schema \"%s\" does not exist", nspname)));
2832 * makeRangeVarFromNameList
2833 * Utility routine to convert a qualified-name list into RangeVar form.
2836 makeRangeVarFromNameList(List *names)
2838 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2840 switch (list_length(names))
2843 rel->relname = strVal(linitial(names));
2846 rel->schemaname = strVal(linitial(names));
2847 rel->relname = strVal(lsecond(names));
2850 rel->catalogname = strVal(linitial(names));
2851 rel->schemaname = strVal(lsecond(names));
2852 rel->relname = strVal(lthird(names));
2856 (errcode(ERRCODE_SYNTAX_ERROR),
2857 errmsg("improper relation name (too many dotted names): %s",
2858 NameListToString(names))));
2867 * Utility routine to convert a qualified-name list into a string.
2869 * This is used primarily to form error messages, and so we do not quote
2870 * the list elements, for the sake of legibility.
2872 * In most scenarios the list elements should always be Value strings,
2873 * but we also allow A_Star for the convenience of ColumnRef processing.
2876 NameListToString(List *names)
2878 StringInfoData string;
2881 initStringInfo(&string);
2885 Node *name = (Node *) lfirst(l);
2887 if (l != list_head(names))
2888 appendStringInfoChar(&string, '.');
2890 if (IsA(name, String))
2891 appendStringInfoString(&string, strVal(name));
2892 else if (IsA(name, A_Star))
2893 appendStringInfoString(&string, "*");
2895 elog(ERROR, "unexpected node type in name list: %d",
2896 (int) nodeTag(name));
2903 * NameListToQuotedString
2904 * Utility routine to convert a qualified-name list into a string.
2906 * Same as above except that names will be double-quoted where necessary,
2907 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2910 NameListToQuotedString(List *names)
2912 StringInfoData string;
2915 initStringInfo(&string);
2919 if (l != list_head(names))
2920 appendStringInfoChar(&string, '.');
2921 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2928 * isTempNamespace - is the given namespace my temporary-table namespace?
2931 isTempNamespace(Oid namespaceId)
2933 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2939 * isTempToastNamespace - is the given namespace my temporary-toast-table
2943 isTempToastNamespace(Oid namespaceId)
2945 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2951 * isTempOrToastNamespace - is the given namespace my temporary-table
2952 * namespace or my temporary-toast-table namespace?
2955 isTempOrToastNamespace(Oid namespaceId)
2957 if (OidIsValid(myTempNamespace) &&
2958 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2964 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2965 * (either my own, or another backend's)? Temporary-toast-table namespaces
2966 * are included, too.
2969 isAnyTempNamespace(Oid namespaceId)
2974 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2975 nspname = get_namespace_name(namespaceId);
2977 return false; /* no such namespace? */
2978 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2979 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2985 * isOtherTempNamespace - is the given namespace some other backend's
2986 * temporary-table namespace (including temporary-toast-table namespaces)?
2988 * Note: for most purposes in the C code, this function is obsolete. Use
2989 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2992 isOtherTempNamespace(Oid namespaceId)
2994 /* If it's my own temp namespace, say "false" */
2995 if (isTempOrToastNamespace(namespaceId))
2997 /* Else, if it's any temp namespace, say "true" */
2998 return isAnyTempNamespace(namespaceId);
3002 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3003 * namespace (either my own, or another backend's), return the BackendId
3004 * that owns it. Temporary-toast-table namespaces are included, too.
3005 * If it isn't a temp namespace, return InvalidBackendId.
3008 GetTempNamespaceBackendId(Oid namespaceId)
3013 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3014 nspname = get_namespace_name(namespaceId);
3016 return InvalidBackendId; /* no such namespace? */
3017 if (strncmp(nspname, "pg_temp_", 8) == 0)
3018 result = atoi(nspname + 8);
3019 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3020 result = atoi(nspname + 14);
3022 result = InvalidBackendId;
3028 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3029 * which must already be assigned. (This is only used when creating a toast
3030 * table for a temp table, so we must have already done InitTempTableNamespace)
3033 GetTempToastNamespace(void)
3035 Assert(OidIsValid(myTempToastNamespace));
3036 return myTempToastNamespace;
3041 * GetOverrideSearchPath - fetch current search path definition in form
3042 * used by PushOverrideSearchPath.
3044 * The result structure is allocated in the specified memory context
3045 * (which might or might not be equal to CurrentMemoryContext); but any
3046 * junk created by revalidation calculations will be in CurrentMemoryContext.
3048 OverrideSearchPath *
3049 GetOverrideSearchPath(MemoryContext context)
3051 OverrideSearchPath *result;
3053 MemoryContext oldcxt;
3055 recomputeNamespacePath();
3057 oldcxt = MemoryContextSwitchTo(context);
3059 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3060 schemas = list_copy(activeSearchPath);
3061 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3063 if (linitial_oid(schemas) == myTempNamespace)
3064 result->addTemp = true;
3067 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3068 result->addCatalog = true;
3070 schemas = list_delete_first(schemas);
3072 result->schemas = schemas;
3074 MemoryContextSwitchTo(oldcxt);
3080 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3082 * The result structure is allocated in CurrentMemoryContext.
3084 OverrideSearchPath *
3085 CopyOverrideSearchPath(OverrideSearchPath *path)
3087 OverrideSearchPath *result;
3089 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3090 result->schemas = list_copy(path->schemas);
3091 result->addCatalog = path->addCatalog;
3092 result->addTemp = path->addTemp;
3098 * PushOverrideSearchPath - temporarily override the search path
3100 * We allow nested overrides, hence the push/pop terminology. The GUC
3101 * search_path variable is ignored while an override is active.
3103 * It's possible that newpath->useTemp is set but there is no longer any
3104 * active temp namespace, if the path was saved during a transaction that
3105 * created a temp namespace and was later rolled back. In that case we just
3106 * ignore useTemp. A plausible alternative would be to create a new temp
3107 * namespace, but for existing callers that's not necessary because an empty
3108 * temp namespace wouldn't affect their results anyway.
3110 * It's also worth noting that other schemas listed in newpath might not
3111 * exist anymore either. We don't worry about this because OIDs that match
3112 * no existing namespace will simply not produce any hits during searches.
3115 PushOverrideSearchPath(OverrideSearchPath *newpath)
3117 OverrideStackEntry *entry;
3120 MemoryContext oldcxt;
3123 * Copy the list for safekeeping, and insert implicitly-searched
3124 * namespaces as needed. This code should track recomputeNamespacePath.
3126 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3128 oidlist = list_copy(newpath->schemas);
3131 * Remember the first member of the explicit list.
3134 firstNS = InvalidOid;
3136 firstNS = linitial_oid(oidlist);
3139 * Add any implicitly-searched namespaces to the list. Note these go on
3140 * the front, not the back; also notice that we do not check USAGE
3141 * permissions for these.
3143 if (newpath->addCatalog)
3144 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3146 if (newpath->addTemp && OidIsValid(myTempNamespace))
3147 oidlist = lcons_oid(myTempNamespace, oidlist);
3150 * Build the new stack entry, then insert it at the head of the list.
3152 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3153 entry->searchPath = oidlist;
3154 entry->creationNamespace = firstNS;
3155 entry->nestLevel = GetCurrentTransactionNestLevel();
3157 overrideStack = lcons(entry, overrideStack);
3159 /* And make it active. */
3160 activeSearchPath = entry->searchPath;
3161 activeCreationNamespace = entry->creationNamespace;
3162 activeTempCreationPending = false; /* XXX is this OK? */
3164 MemoryContextSwitchTo(oldcxt);
3168 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3170 * Any push during a (sub)transaction will be popped automatically at abort.
3171 * But it's caller error if a push isn't popped in normal control flow.
3174 PopOverrideSearchPath(void)
3176 OverrideStackEntry *entry;
3178 /* Sanity checks. */
3179 if (overrideStack == NIL)
3180 elog(ERROR, "bogus PopOverrideSearchPath call");
3181 entry = (OverrideStackEntry *) linitial(overrideStack);
3182 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3183 elog(ERROR, "bogus PopOverrideSearchPath call");
3185 /* Pop the stack and free storage. */
3186 overrideStack = list_delete_first(overrideStack);
3187 list_free(entry->searchPath);
3190 /* Activate the next level down. */
3193 entry = (OverrideStackEntry *) linitial(overrideStack);
3194 activeSearchPath = entry->searchPath;
3195 activeCreationNamespace = entry->creationNamespace;
3196 activeTempCreationPending = false; /* XXX is this OK? */
3200 /* If not baseSearchPathValid, this is useless but harmless */
3201 activeSearchPath = baseSearchPath;
3202 activeCreationNamespace = baseCreationNamespace;
3203 activeTempCreationPending = baseTempCreationPending;
3209 * get_collation_oid - find a collation by possibly qualified name
3212 get_collation_oid(List *name, bool missing_ok)
3215 char *collation_name;
3216 int32 dbencoding = GetDatabaseEncoding();
3221 /* deconstruct the name list */
3222 DeconstructQualifiedName(name, &schemaname, &collation_name);
3226 /* use exact schema given */
3227 namespaceId = LookupExplicitNamespace(schemaname);
3229 /* first try for encoding-specific entry, then any-encoding */
3230 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3231 PointerGetDatum(collation_name),
3232 Int32GetDatum(dbencoding),
3233 ObjectIdGetDatum(namespaceId));
3234 if (OidIsValid(colloid))
3236 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3237 PointerGetDatum(collation_name),
3239 ObjectIdGetDatum(namespaceId));
3240 if (OidIsValid(colloid))
3245 /* search for it in search path */
3246 recomputeNamespacePath();
3248 foreach(l, activeSearchPath)
3250 namespaceId = lfirst_oid(l);
3252 if (namespaceId == myTempNamespace)
3253 continue; /* do not look in temp namespace */
3255 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3256 PointerGetDatum(collation_name),
3257 Int32GetDatum(dbencoding),
3258 ObjectIdGetDatum(namespaceId));
3259 if (OidIsValid(colloid))
3261 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3262 PointerGetDatum(collation_name),
3264 ObjectIdGetDatum(namespaceId));
3265 if (OidIsValid(colloid))
3270 /* Not found in path */
3273 (errcode(ERRCODE_UNDEFINED_OBJECT),
3274 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3275 NameListToString(name), GetDatabaseEncodingName())));
3280 * get_conversion_oid - find a conversion by possibly qualified name
3283 get_conversion_oid(List *name, bool missing_ok)
3286 char *conversion_name;
3288 Oid conoid = InvalidOid;
3291 /* deconstruct the name list */
3292 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3296 /* use exact schema given */
3297 namespaceId = LookupExplicitNamespace(schemaname);
3298 conoid = GetSysCacheOid2(CONNAMENSP,
3299 PointerGetDatum(conversion_name),
3300 ObjectIdGetDatum(namespaceId));
3304 /* search for it in search path */
3305 recomputeNamespacePath();
3307 foreach(l, activeSearchPath)
3309 namespaceId = lfirst_oid(l);
3311 if (namespaceId == myTempNamespace)
3312 continue; /* do not look in temp namespace */
3314 conoid = GetSysCacheOid2(CONNAMENSP,
3315 PointerGetDatum(conversion_name),
3316 ObjectIdGetDatum(namespaceId));
3317 if (OidIsValid(conoid))
3322 /* Not found in path */
3323 if (!OidIsValid(conoid) && !missing_ok)
3325 (errcode(ERRCODE_UNDEFINED_OBJECT),
3326 errmsg("conversion \"%s\" does not exist",
3327 NameListToString(name))));
3332 * FindDefaultConversionProc - find default encoding conversion proc
3335 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
3340 recomputeNamespacePath();
3342 foreach(l, activeSearchPath)
3344 Oid namespaceId = lfirst_oid(l);
3346 if (namespaceId == myTempNamespace)
3347 continue; /* do not look in temp namespace */
3349 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3350 if (OidIsValid(proc))
3354 /* Not found in path */
3359 * recomputeNamespacePath - recompute path derived variables if needed.
3362 recomputeNamespacePath(void)
3364 Oid roleid = GetUserId();
3372 MemoryContext oldcxt;
3374 /* Do nothing if an override search spec is active. */
3378 /* Do nothing if path is already valid. */
3379 if (baseSearchPathValid && namespaceUser == roleid)
3382 /* Need a modifiable copy of namespace_search_path string */
3383 rawname = pstrdup(namespace_search_path);
3385 /* Parse string into list of identifiers */
3386 if (!SplitIdentifierString(rawname, ',', &namelist))
3388 /* syntax error in name list */
3389 /* this should not happen if GUC checked check_search_path */
3390 elog(ERROR, "invalid list syntax");
3394 * Convert the list of names to a list of OIDs. If any names are not
3395 * recognizable or we don't have read access, just leave them out of the
3396 * list. (We can't raise an error, since the search_path setting has
3397 * already been accepted.) Don't make duplicate entries, either.
3400 temp_missing = false;
3401 foreach(l, namelist)
3403 char *curname = (char *) lfirst(l);
3406 if (strcmp(curname, "$user") == 0)
3408 /* $user --- substitute namespace matching user name, if any */
3411 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3412 if (HeapTupleIsValid(tuple))
3416 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3417 namespaceId = get_namespace_oid(rname, true);
3418 ReleaseSysCache(tuple);
3419 if (OidIsValid(namespaceId) &&
3420 !list_member_oid(oidlist, namespaceId) &&
3421 pg_namespace_aclcheck(namespaceId, roleid,
3422 ACL_USAGE) == ACLCHECK_OK)
3423 oidlist = lappend_oid(oidlist, namespaceId);
3426 else if (strcmp(curname, "pg_temp") == 0)
3428 /* pg_temp --- substitute temp namespace, if any */
3429 if (OidIsValid(myTempNamespace))
3431 if (!list_member_oid(oidlist, myTempNamespace))
3432 oidlist = lappend_oid(oidlist, myTempNamespace);
3436 /* If it ought to be the creation namespace, set flag */
3438 temp_missing = true;
3443 /* normal namespace reference */
3444 namespaceId = get_namespace_oid(curname, true);
3445 if (OidIsValid(namespaceId) &&
3446 !list_member_oid(oidlist, namespaceId) &&
3447 pg_namespace_aclcheck(namespaceId, roleid,
3448 ACL_USAGE) == ACLCHECK_OK)
3449 oidlist = lappend_oid(oidlist, namespaceId);
3454 * Remember the first member of the explicit list. (Note: this is
3455 * nominally wrong if temp_missing, but we need it anyway to distinguish
3456 * explicit from implicit mention of pg_catalog.)
3459 firstNS = InvalidOid;
3461 firstNS = linitial_oid(oidlist);
3464 * Add any implicitly-searched namespaces to the list. Note these go on
3465 * the front, not the back; also notice that we do not check USAGE
3466 * permissions for these.
3468 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3469 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3471 if (OidIsValid(myTempNamespace) &&
3472 !list_member_oid(oidlist, myTempNamespace))
3473 oidlist = lcons_oid(myTempNamespace, oidlist);
3476 * Now that we've successfully built the new list of namespace OIDs, save
3477 * it in permanent storage.
3479 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3480 newpath = list_copy(oidlist);
3481 MemoryContextSwitchTo(oldcxt);
3483 /* Now safe to assign to state variables. */
3484 list_free(baseSearchPath);
3485 baseSearchPath = newpath;
3486 baseCreationNamespace = firstNS;
3487 baseTempCreationPending = temp_missing;
3489 /* Mark the path valid. */
3490 baseSearchPathValid = true;
3491 namespaceUser = roleid;
3493 /* And make it active. */
3494 activeSearchPath = baseSearchPath;
3495 activeCreationNamespace = baseCreationNamespace;
3496 activeTempCreationPending = baseTempCreationPending;
3500 list_free(namelist);
3505 * InitTempTableNamespace
3506 * Initialize temp table namespace on first use in a particular backend
3509 InitTempTableNamespace(void)
3511 char namespaceName[NAMEDATALEN];
3515 Assert(!OidIsValid(myTempNamespace));
3518 * First, do permission check to see if we are authorized to make temp
3519 * tables. We use a nonstandard error message here since "databasename:
3520 * permission denied" might be a tad cryptic.
3522 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3523 * that's necessary since current user ID could change during the session.
3524 * But there's no need to make the namespace in the first place until a
3525 * temp table creation request is made by someone with appropriate rights.
3527 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3528 ACL_CREATE_TEMP) != ACLCHECK_OK)
3530 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3531 errmsg("permission denied to create temporary tables in database \"%s\"",
3532 get_database_name(MyDatabaseId))));
3535 * Do not allow a Hot Standby slave session to make temp tables. Aside
3536 * from problems with modifying the system catalogs, there is a naming
3537 * conflict: pg_temp_N belongs to the session with BackendId N on the
3538 * master, not to a slave session with the same BackendId. We should not
3539 * be able to get here anyway due to XactReadOnly checks, but let's just
3540 * make real sure. Note that this also backstops various operations that
3541 * allow XactReadOnly transactions to modify temp tables; they'd need
3542 * RecoveryInProgress checks if not for this.
3544 if (RecoveryInProgress())
3546 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3547 errmsg("cannot create temporary tables during recovery")));
3549 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3551 namespaceId = get_namespace_oid(namespaceName, true);
3552 if (!OidIsValid(namespaceId))
3555 * First use of this temp namespace in this database; create it. The
3556 * temp namespaces are always owned by the superuser. We leave their
3557 * permissions at default --- i.e., no access except to superuser ---
3558 * to ensure that unprivileged users can't peek at other backends'
3559 * temp tables. This works because the places that access the temp
3560 * namespace for my own backend skip permissions checks on it.
3562 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3564 /* Advance command counter to make namespace visible */
3565 CommandCounterIncrement();
3570 * If the namespace already exists, clean it out (in case the former
3571 * owner crashed without doing so).
3573 RemoveTempRelations(namespaceId);
3577 * If the corresponding toast-table namespace doesn't exist yet, create
3578 * it. (We assume there is no need to clean it out if it does exist, since
3579 * dropping a parent table should make its toast table go away.)
3581 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3584 toastspaceId = get_namespace_oid(namespaceName, true);
3585 if (!OidIsValid(toastspaceId))
3587 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3589 /* Advance command counter to make namespace visible */
3590 CommandCounterIncrement();
3594 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3595 * so all our work could be undone by transaction rollback. Set flag for
3596 * AtEOXact_Namespace to know what to do.
3598 myTempNamespace = namespaceId;
3599 myTempToastNamespace = toastspaceId;
3601 /* It should not be done already. */
3602 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3603 myTempNamespaceSubID = GetCurrentSubTransactionId();
3605 baseSearchPathValid = false; /* need to rebuild list */
3609 * End-of-transaction cleanup for namespaces.
3612 AtEOXact_Namespace(bool isCommit)
3615 * If we abort the transaction in which a temp namespace was selected,
3616 * we'll have to do any creation or cleanout work over again. So, just
3617 * forget the namespace entirely until next time. On the other hand, if
3618 * we commit then register an exit callback to clean out the temp tables
3619 * at backend shutdown. (We only want to register the callback once per
3620 * session, so this is a good place to do it.)
3622 if (myTempNamespaceSubID != InvalidSubTransactionId)
3625 on_shmem_exit(RemoveTempRelationsCallback, 0);
3628 myTempNamespace = InvalidOid;
3629 myTempToastNamespace = InvalidOid;
3630 baseSearchPathValid = false; /* need to rebuild list */
3632 myTempNamespaceSubID = InvalidSubTransactionId;
3636 * Clean up if someone failed to do PopOverrideSearchPath
3641 elog(WARNING, "leaked override search path");
3642 while (overrideStack)
3644 OverrideStackEntry *entry;
3646 entry = (OverrideStackEntry *) linitial(overrideStack);
3647 overrideStack = list_delete_first(overrideStack);
3648 list_free(entry->searchPath);
3651 /* If not baseSearchPathValid, this is useless but harmless */
3652 activeSearchPath = baseSearchPath;
3653 activeCreationNamespace = baseCreationNamespace;
3654 activeTempCreationPending = baseTempCreationPending;
3659 * AtEOSubXact_Namespace
3661 * At subtransaction commit, propagate the temp-namespace-creation
3662 * flag to the parent subtransaction.
3664 * At subtransaction abort, forget the flag if we set it up.
3667 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3668 SubTransactionId parentSubid)
3670 OverrideStackEntry *entry;
3672 if (myTempNamespaceSubID == mySubid)
3675 myTempNamespaceSubID = parentSubid;
3678 myTempNamespaceSubID = InvalidSubTransactionId;
3679 /* TEMP namespace creation failed, so reset state */
3680 myTempNamespace = InvalidOid;
3681 myTempToastNamespace = InvalidOid;
3682 baseSearchPathValid = false; /* need to rebuild list */
3687 * Clean up if someone failed to do PopOverrideSearchPath
3689 while (overrideStack)
3691 entry = (OverrideStackEntry *) linitial(overrideStack);
3692 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3695 elog(WARNING, "leaked override search path");
3696 overrideStack = list_delete_first(overrideStack);
3697 list_free(entry->searchPath);
3701 /* Activate the next level down. */
3704 entry = (OverrideStackEntry *) linitial(overrideStack);
3705 activeSearchPath = entry->searchPath;
3706 activeCreationNamespace = entry->creationNamespace;
3707 activeTempCreationPending = false; /* XXX is this OK? */
3711 /* If not baseSearchPathValid, this is useless but harmless */
3712 activeSearchPath = baseSearchPath;
3713 activeCreationNamespace = baseCreationNamespace;
3714 activeTempCreationPending = baseTempCreationPending;
3719 * Remove all relations in the specified temp namespace.
3721 * This is called at backend shutdown (if we made any temp relations).
3722 * It is also called when we begin using a pre-existing temp namespace,
3723 * in order to clean out any relations that might have been created by
3724 * a crashed backend.
3727 RemoveTempRelations(Oid tempNamespaceId)
3729 ObjectAddress object;
3732 * We want to get rid of everything in the target namespace, but not the
3733 * namespace itself (deleting it only to recreate it later would be a
3734 * waste of cycles). We do this by finding everything that has a
3735 * dependency on the namespace.
3737 object.classId = NamespaceRelationId;
3738 object.objectId = tempNamespaceId;
3739 object.objectSubId = 0;
3741 deleteWhatDependsOn(&object, false);
3745 * Callback to remove temp relations at backend exit.
3748 RemoveTempRelationsCallback(int code, Datum arg)
3750 if (OidIsValid(myTempNamespace)) /* should always be true */
3752 /* Need to ensure we have a usable transaction. */
3753 AbortOutOfAnyTransaction();
3754 StartTransactionCommand();
3756 RemoveTempRelations(myTempNamespace);
3758 CommitTransactionCommand();
3763 * Remove all temp tables from the temporary namespace.
3766 ResetTempTableNamespace(void)
3768 if (OidIsValid(myTempNamespace))
3769 RemoveTempRelations(myTempNamespace);
3774 * Routines for handling the GUC variable 'search_path'.
3777 /* check_hook: validate new search_path value */
3779 check_search_path(char **newval, void **extra, GucSource source)
3784 /* Need a modifiable copy of string */
3785 rawname = pstrdup(*newval);
3787 /* Parse string into list of identifiers */
3788 if (!SplitIdentifierString(rawname, ',', &namelist))
3790 /* syntax error in name list */
3791 GUC_check_errdetail("List syntax is invalid.");
3793 list_free(namelist);
3798 * We used to try to check that the named schemas exist, but there are
3799 * many valid use-cases for having search_path settings that include
3800 * schemas that don't exist; and often, we are not inside a transaction
3801 * here and so can't consult the system catalogs anyway. So now, the only
3802 * requirement is syntactic validity of the identifier list.
3806 list_free(namelist);
3811 /* assign_hook: do extra actions as needed */
3813 assign_search_path(const char *newval, void *extra)
3816 * We mark the path as needing recomputation, but don't do anything until
3817 * it's needed. This avoids trying to do database access during GUC
3818 * initialization, or outside a transaction.
3820 baseSearchPathValid = false;
3824 * InitializeSearchPath: initialize module during InitPostgres.
3826 * This is called after we are up enough to be able to do catalog lookups.
3829 InitializeSearchPath(void)
3831 if (IsBootstrapProcessingMode())
3834 * In bootstrap mode, the search path must be 'pg_catalog' so that
3835 * tables are created in the proper namespace; ignore the GUC setting.
3837 MemoryContext oldcxt;
3839 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3840 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3841 MemoryContextSwitchTo(oldcxt);
3842 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3843 baseTempCreationPending = false;
3844 baseSearchPathValid = true;
3845 namespaceUser = GetUserId();
3846 activeSearchPath = baseSearchPath;
3847 activeCreationNamespace = baseCreationNamespace;
3848 activeTempCreationPending = baseTempCreationPending;
3853 * In normal mode, arrange for a callback on any syscache invalidation
3854 * of pg_namespace rows.
3856 CacheRegisterSyscacheCallback(NAMESPACEOID,
3859 /* Force search path to be recomputed on next use */
3860 baseSearchPathValid = false;
3866 * Syscache inval callback function
3869 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3871 /* Force search path to be recomputed on next use */
3872 baseSearchPathValid = false;
3876 * Fetch the active search path. The return value is a palloc'ed list
3877 * of OIDs; the caller is responsible for freeing this storage as
3880 * The returned list includes the implicitly-prepended namespaces only if
3881 * includeImplicit is true.
3883 * Note: calling this may result in a CommandCounterIncrement operation,
3884 * if we have to create or clean out the temp namespace.
3887 fetch_search_path(bool includeImplicit)
3891 recomputeNamespacePath();
3894 * If the temp namespace should be first, force it to exist. This is so
3895 * that callers can trust the result to reflect the actual default
3896 * creation namespace. It's a bit bogus to do this here, since
3897 * current_schema() is supposedly a stable function without side-effects,
3898 * but the alternatives seem worse.
3900 if (activeTempCreationPending)
3902 InitTempTableNamespace();
3903 recomputeNamespacePath();
3906 result = list_copy(activeSearchPath);
3907 if (!includeImplicit)
3909 while (result && linitial_oid(result) != activeCreationNamespace)
3910 result = list_delete_first(result);
3917 * Fetch the active search path into a caller-allocated array of OIDs.
3918 * Returns the number of path entries. (If this is more than sarray_len,
3919 * then the data didn't fit and is not all stored.)
3921 * The returned list always includes the implicitly-prepended namespaces,
3922 * but never includes the temp namespace. (This is suitable for existing
3923 * users, which would want to ignore the temp namespace anyway.) This
3924 * definition allows us to not worry about initializing the temp namespace.
3927 fetch_search_path_array(Oid *sarray, int sarray_len)
3932 recomputeNamespacePath();
3934 foreach(l, activeSearchPath)
3936 Oid namespaceId = lfirst_oid(l);
3938 if (namespaceId == myTempNamespace)
3939 continue; /* do not include temp namespace */
3941 if (count < sarray_len)
3942 sarray[count] = namespaceId;
3951 * Export the FooIsVisible functions as SQL-callable functions.
3953 * Note: as of Postgres 8.4, these will silently return NULL if called on
3954 * a nonexistent object OID, rather than failing. This is to avoid race
3955 * condition errors when a query that's scanning a catalog using an MVCC
3956 * snapshot uses one of these functions. The underlying IsVisible functions
3957 * operate on SnapshotNow semantics and so might see the object as already
3958 * gone when it's still visible to the MVCC snapshot. (There is no race
3959 * condition in the current coding because we don't accept sinval messages
3960 * between the SearchSysCacheExists test and the subsequent lookup.)
3964 pg_table_is_visible(PG_FUNCTION_ARGS)
3966 Oid oid = PG_GETARG_OID(0);
3968 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3971 PG_RETURN_BOOL(RelationIsVisible(oid));
3975 pg_type_is_visible(PG_FUNCTION_ARGS)
3977 Oid oid = PG_GETARG_OID(0);
3979 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3982 PG_RETURN_BOOL(TypeIsVisible(oid));
3986 pg_function_is_visible(PG_FUNCTION_ARGS)
3988 Oid oid = PG_GETARG_OID(0);
3990 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3993 PG_RETURN_BOOL(FunctionIsVisible(oid));
3997 pg_operator_is_visible(PG_FUNCTION_ARGS)
3999 Oid oid = PG_GETARG_OID(0);
4001 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4004 PG_RETURN_BOOL(OperatorIsVisible(oid));
4008 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4010 Oid oid = PG_GETARG_OID(0);
4012 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4015 PG_RETURN_BOOL(OpclassIsVisible(oid));
4019 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4021 Oid oid = PG_GETARG_OID(0);
4023 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4026 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4030 pg_collation_is_visible(PG_FUNCTION_ARGS)
4032 Oid oid = PG_GETARG_OID(0);
4034 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4037 PG_RETURN_BOOL(CollationIsVisible(oid));
4041 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4043 Oid oid = PG_GETARG_OID(0);
4045 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4048 PG_RETURN_BOOL(ConversionIsVisible(oid));
4052 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4054 Oid oid = PG_GETARG_OID(0);
4056 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4059 PG_RETURN_BOOL(TSParserIsVisible(oid));
4063 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4065 Oid oid = PG_GETARG_OID(0);
4067 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4070 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4074 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4076 Oid oid = PG_GETARG_OID(0);
4078 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4081 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4085 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4087 Oid oid = PG_GETARG_OID(0);
4089 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4092 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4096 pg_my_temp_schema(PG_FUNCTION_ARGS)
4098 PG_RETURN_OID(myTempNamespace);
4102 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4104 Oid oid = PG_GETARG_OID(0);
4106 PG_RETURN_BOOL(isOtherTempNamespace(oid));