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-2013, 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/htup_details.h"
23 #include "access/xact.h"
24 #include "catalog/dependency.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_collation.h"
27 #include "catalog/pg_conversion.h"
28 #include "catalog/pg_conversion_fn.h"
29 #include "catalog/pg_namespace.h"
30 #include "catalog/pg_opclass.h"
31 #include "catalog/pg_operator.h"
32 #include "catalog/pg_opfamily.h"
33 #include "catalog/pg_proc.h"
34 #include "catalog/pg_ts_config.h"
35 #include "catalog/pg_ts_dict.h"
36 #include "catalog/pg_ts_parser.h"
37 #include "catalog/pg_ts_template.h"
38 #include "catalog/pg_type.h"
39 #include "commands/dbcommands.h"
41 #include "mb/pg_wchar.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "parser/parse_func.h"
45 #include "storage/ipc.h"
46 #include "storage/lmgr.h"
47 #include "storage/sinval.h"
48 #include "utils/acl.h"
49 #include "utils/builtins.h"
50 #include "utils/catcache.h"
51 #include "utils/guc.h"
52 #include "utils/inval.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55 #include "utils/syscache.h"
59 * The namespace search path is a possibly-empty list of namespace OIDs.
60 * In addition to the explicit list, implicitly-searched namespaces
63 * 1. If a TEMP table namespace has been initialized in this session, it
64 * is implicitly searched first. (The only time this doesn't happen is
65 * when we are obeying an override search path spec that says not to use the
66 * temp namespace, or the temp namespace is included in the explicit list.)
68 * 2. The system catalog namespace is always searched. If the system
69 * namespace is present in the explicit path then it will be searched in
70 * the specified order; otherwise it will be searched after TEMP tables and
71 * *before* the explicit list. (It might seem that the system namespace
72 * should be implicitly last, but this behavior appears to be required by
73 * SQL99. Also, this provides a way to search the system namespace first
74 * without thereby making it the default creation target namespace.)
76 * For security reasons, searches using the search path will ignore the temp
77 * namespace when searching for any object type other than relations and
78 * types. (We must allow types since temp tables have rowtypes.)
80 * The default creation target namespace is always the first element of the
81 * explicit list. If the explicit list is empty, there is no default target.
83 * The textual specification of search_path can include "$user" to refer to
84 * the namespace named the same as the current user, if any. (This is just
85 * ignored if there is no such namespace.) Also, it can include "pg_temp"
86 * to refer to the current backend's temp namespace. This is usually also
87 * ignorable if the temp namespace hasn't been set up, but there's a special
88 * case: if "pg_temp" appears first then it should be the default creation
89 * target. We kluge this case a little bit so that the temp namespace isn't
90 * set up until the first attempt to create something in it. (The reason for
91 * klugery is that we can't create the temp namespace outside a transaction,
92 * but initial GUC processing of search_path happens outside a transaction.)
93 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
94 * but is not reflected in activeCreationNamespace because the namespace isn't
97 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
98 * the system namespace is the only one searched or inserted into.
99 * initdb is also careful to set search_path to "pg_catalog" for its
100 * post-bootstrap standalone backend runs. Otherwise the default search
101 * path is determined by GUC. The factory default path contains the PUBLIC
102 * namespace (if it exists), preceded by the user's personal namespace
105 * We support a stack of "override" search path settings for use within
106 * specific sections of backend code. namespace_search_path is ignored
107 * whenever the override stack is nonempty. activeSearchPath is always
108 * the actually active path; it points either to the search list of the
109 * topmost stack entry, or to baseSearchPath which is the list derived
110 * from namespace_search_path.
112 * If baseSearchPathValid is false, then baseSearchPath (and other
113 * derived variables) need to be recomputed from namespace_search_path.
114 * We mark it invalid upon an assignment to namespace_search_path or receipt
115 * of a syscache invalidation event for pg_namespace. The recomputation
116 * is done during the next non-overridden lookup attempt. Note that an
117 * override spec is never subject to recomputation.
119 * Any namespaces mentioned in namespace_search_path that are not readable
120 * by the current user ID are simply left out of baseSearchPath; so
121 * we have to be willing to recompute the path when current userid changes.
122 * namespaceUser is the userid the path has been computed for.
124 * Note: all data pointed to by these List variables is in TopMemoryContext.
127 /* These variables define the actually active state: */
129 static List *activeSearchPath = NIL;
131 /* default place to create stuff; if InvalidOid, no default */
132 static Oid activeCreationNamespace = InvalidOid;
134 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
135 static bool activeTempCreationPending = false;
137 /* These variables are the values last derived from namespace_search_path: */
139 static List *baseSearchPath = NIL;
141 static Oid baseCreationNamespace = InvalidOid;
143 static bool baseTempCreationPending = false;
145 static Oid namespaceUser = InvalidOid;
147 /* The above four values are valid only if baseSearchPathValid */
148 static bool baseSearchPathValid = true;
150 /* Override requests are remembered in a stack of OverrideStackEntry structs */
154 List *searchPath; /* the desired search path */
155 Oid creationNamespace; /* the desired creation namespace */
156 int nestLevel; /* subtransaction nesting level */
157 } OverrideStackEntry;
159 static List *overrideStack = NIL;
162 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
163 * in a particular backend session (this happens when a CREATE TEMP TABLE
164 * command is first executed). Thereafter it's the OID of the temp namespace.
166 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
167 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
169 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
170 * current subtransaction. The flag propagates up the subtransaction tree,
171 * so the main transaction will correctly recognize the flag if all
172 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
173 * we either haven't made the TEMP namespace yet, or have successfully
174 * committed its creation, depending on whether myTempNamespace is valid.
176 static Oid myTempNamespace = InvalidOid;
178 static Oid myTempToastNamespace = InvalidOid;
180 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
183 * This is the user's textual search path specification --- it's the value
184 * of the GUC variable 'search_path'.
186 char *namespace_search_path = NULL;
189 /* Local functions */
190 static void recomputeNamespacePath(void);
191 static void InitTempTableNamespace(void);
192 static void RemoveTempRelations(Oid tempNamespaceId);
193 static void RemoveTempRelationsCallback(int code, Datum arg);
194 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
195 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
198 /* These don't really need to appear in any header file */
199 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
200 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
210 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
211 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
212 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
217 * Given a RangeVar describing an existing relation,
218 * select the proper namespace and look up the relation OID.
220 * If the relation is not found, return InvalidOid if missing_ok = true,
221 * otherwise raise an error.
223 * If nowait = true, throw an error if we'd have to wait for a lock.
225 * Callback allows caller to check permissions or acquire additional locks
226 * prior to grabbing the relation lock.
229 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
230 bool missing_ok, bool nowait,
231 RangeVarGetRelidCallback callback, void *callback_arg)
235 Oid oldRelId = InvalidOid;
239 * We check the catalog name and then ignore it.
241 if (relation->catalogname)
243 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
245 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
246 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
247 relation->catalogname, relation->schemaname,
248 relation->relname)));
252 * DDL operations can change the results of a name lookup. Since all such
253 * operations will generate invalidation messages, we keep track of
254 * whether any such messages show up while we're performing the operation,
255 * and retry until either (1) no more invalidation messages show up or (2)
256 * the answer doesn't change.
258 * But if lockmode = NoLock, then we assume that either the caller is OK
259 * with the answer changing under them, or that they already hold some
260 * appropriate lock, and therefore return the first answer we get without
261 * checking for invalidation messages. Also, if the requested lock is
262 * already held, no LockRelationOid will not AcceptInvalidationMessages,
263 * so we may fail to notice a change. We could protect against that case
264 * by calling AcceptInvalidationMessages() before beginning this loop, but
265 * that would add a significant amount overhead, so for now we don't.
270 * Remember this value, so that, after looking up the relation name
271 * and locking its OID, we can check whether any invalidation messages
272 * have been processed that might require a do-over.
274 inval_count = SharedInvalidMessageCounter;
277 * Some non-default relpersistence value may have been specified. The
278 * parser never generates such a RangeVar in simple DML, but it can
279 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
280 * KEY)". Such a command will generate an added CREATE INDEX
281 * operation, which must be careful to find the temp table, even when
282 * pg_temp is not first in the search path.
284 if (relation->relpersistence == RELPERSISTENCE_TEMP)
286 if (!OidIsValid(myTempNamespace))
287 relId = InvalidOid; /* this probably can't happen? */
290 if (relation->schemaname)
294 namespaceId = LookupExplicitNamespace(relation->schemaname);
295 if (namespaceId != myTempNamespace)
297 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
298 errmsg("temporary tables cannot specify a schema name")));
301 relId = get_relname_relid(relation->relname, myTempNamespace);
304 else if (relation->schemaname)
308 /* use exact schema given */
309 namespaceId = LookupExplicitNamespace(relation->schemaname);
310 relId = get_relname_relid(relation->relname, namespaceId);
314 /* search the namespace path */
315 relId = RelnameGetRelid(relation->relname);
319 * Invoke caller-supplied callback, if any.
321 * This callback is a good place to check permissions: we haven't
322 * taken the table lock yet (and it's really best to check permissions
323 * before locking anything!), but we've gotten far enough to know what
324 * OID we think we should lock. Of course, concurrent DDL might
325 * change things while we're waiting for the lock, but in that case
326 * the callback will be invoked again for the new OID.
329 callback(relation, relId, oldRelId, callback_arg);
332 * If no lock requested, we assume the caller knows what they're
333 * doing. They should have already acquired a heavyweight lock on
334 * this relation earlier in the processing of this same statement, so
335 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
336 * that might pull the rug out from under them.
338 if (lockmode == NoLock)
342 * If, upon retry, we get back the same OID we did last time, then the
343 * invalidation messages we processed did not change the final answer.
346 * If we got a different OID, we've locked the relation that used to
347 * have this name rather than the one that does now. So release the
352 if (relId == oldRelId)
354 if (OidIsValid(oldRelId))
355 UnlockRelationOid(oldRelId, lockmode);
359 * Lock relation. This will also accept any pending invalidation
360 * messages. If we got back InvalidOid, indicating not found, then
361 * there's nothing to lock, but we accept invalidation messages
362 * anyway, to flush any negative catcache entries that may be
365 if (!OidIsValid(relId))
366 AcceptInvalidationMessages();
368 LockRelationOid(relId, lockmode);
369 else if (!ConditionalLockRelationOid(relId, lockmode))
371 if (relation->schemaname)
373 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
374 errmsg("could not obtain lock on relation \"%s.%s\"",
375 relation->schemaname, relation->relname)));
378 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
379 errmsg("could not obtain lock on relation \"%s\"",
380 relation->relname)));
384 * If no invalidation message were processed, we're done!
386 if (inval_count == SharedInvalidMessageCounter)
390 * Something may have changed. Let's repeat the name lookup, to make
391 * sure this name still references the same relation it did
398 if (!OidIsValid(relId) && !missing_ok)
400 if (relation->schemaname)
402 (errcode(ERRCODE_UNDEFINED_TABLE),
403 errmsg("relation \"%s.%s\" does not exist",
404 relation->schemaname, relation->relname)));
407 (errcode(ERRCODE_UNDEFINED_TABLE),
408 errmsg("relation \"%s\" does not exist",
409 relation->relname)));
415 * RangeVarGetCreationNamespace
416 * Given a RangeVar describing a to-be-created relation,
417 * choose which namespace to create it in.
419 * Note: calling this may result in a CommandCounterIncrement operation.
420 * That will happen on the first request for a temp table in any particular
421 * backend run; we will need to either create or clean out the temp schema.
424 RangeVarGetCreationNamespace(const RangeVar *newRelation)
429 * We check the catalog name and then ignore it.
431 if (newRelation->catalogname)
433 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
436 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
437 newRelation->catalogname, newRelation->schemaname,
438 newRelation->relname)));
441 if (newRelation->schemaname)
443 /* check for pg_temp alias */
444 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
446 /* Initialize temp namespace if first time through */
447 if (!OidIsValid(myTempNamespace))
448 InitTempTableNamespace();
449 return myTempNamespace;
451 /* use exact schema given */
452 namespaceId = get_namespace_oid(newRelation->schemaname, false);
453 /* we do not check for USAGE rights here! */
455 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
457 /* Initialize temp namespace if first time through */
458 if (!OidIsValid(myTempNamespace))
459 InitTempTableNamespace();
460 return myTempNamespace;
464 /* use the default creation namespace */
465 recomputeNamespacePath();
466 if (activeTempCreationPending)
468 /* Need to initialize temp namespace */
469 InitTempTableNamespace();
470 return myTempNamespace;
472 namespaceId = activeCreationNamespace;
473 if (!OidIsValid(namespaceId))
475 (errcode(ERRCODE_UNDEFINED_SCHEMA),
476 errmsg("no schema has been selected to create in")));
479 /* Note: callers will check for CREATE rights when appropriate */
485 * RangeVarGetAndCheckCreationNamespace
487 * This function returns the OID of the namespace in which a new relation
488 * with a given name should be created. If the user does not have CREATE
489 * permission on the target namespace, this function will instead signal
492 * If non-NULL, *existing_oid is set to the OID of any existing relation with
493 * the same name which already exists in that namespace, or to InvalidOid if
494 * no such relation exists.
496 * If lockmode != NoLock, the specified lock mode is acquire on the existing
497 * relation, if any, provided that the current user owns the target relation.
498 * However, if lockmode != NoLock and the user does not own the target
499 * relation, we throw an ERROR, as we must not try to lock relations the
500 * user does not have permissions on.
502 * As a side effect, this function acquires AccessShareLock on the target
503 * namespace. Without this, the namespace could be dropped before our
504 * transaction commits, leaving behind relations with relnamespace pointing
505 * to a no-longer-exstant namespace.
507 * As a further side-effect, if the select namespace is a temporary namespace,
508 * we mark the RangeVar as RELPERSISTENCE_TEMP.
511 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
513 Oid *existing_relation_id)
517 Oid oldrelid = InvalidOid;
519 Oid oldnspid = InvalidOid;
523 * We check the catalog name and then ignore it.
525 if (relation->catalogname)
527 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
529 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
530 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
531 relation->catalogname, relation->schemaname,
532 relation->relname)));
536 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
537 * operations by tracking whether any invalidation messages are processed
538 * while we're doing the name lookups and acquiring locks. See comments
539 * in that function for a more detailed explanation of this logic.
545 inval_count = SharedInvalidMessageCounter;
547 /* Look up creation namespace and check for existing relation. */
548 nspid = RangeVarGetCreationNamespace(relation);
549 Assert(OidIsValid(nspid));
550 if (existing_relation_id != NULL)
551 relid = get_relname_relid(relation->relname, nspid);
556 * In bootstrap processing mode, we don't bother with permissions or
557 * locking. Permissions might not be working yet, and locking is
560 if (IsBootstrapProcessingMode())
563 /* Check namespace permissions. */
564 aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
565 if (aclresult != ACLCHECK_OK)
566 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
567 get_namespace_name(nspid));
571 /* If nothing changed, we're done. */
572 if (relid == oldrelid && nspid == oldnspid)
574 /* If creation namespace has changed, give up old lock. */
575 if (nspid != oldnspid)
576 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
578 /* If name points to something different, give up old lock. */
579 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
580 UnlockRelationOid(oldrelid, lockmode);
583 /* Lock namespace. */
584 if (nspid != oldnspid)
585 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
587 /* Lock relation, if required if and we have permission. */
588 if (lockmode != NoLock && OidIsValid(relid))
590 if (!pg_class_ownercheck(relid, GetUserId()))
591 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
593 if (relid != oldrelid)
594 LockRelationOid(relid, lockmode);
597 /* If no invalidation message were processed, we're done! */
598 if (inval_count == SharedInvalidMessageCounter)
601 /* Something may have changed, so recheck our work. */
607 RangeVarAdjustRelationPersistence(relation, nspid);
608 if (existing_relation_id != NULL)
609 *existing_relation_id = relid;
614 * Adjust the relpersistence for an about-to-be-created relation based on the
615 * creation namespace, and throw an error for invalid combinations.
618 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
620 switch (newRelation->relpersistence)
622 case RELPERSISTENCE_TEMP:
623 if (!isTempOrToastNamespace(nspid))
625 if (isAnyTempNamespace(nspid))
627 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
628 errmsg("cannot create relations in temporary schemas of other sessions")));
631 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
632 errmsg("cannot create temporary relation in non-temporary schema")));
635 case RELPERSISTENCE_PERMANENT:
636 if (isTempOrToastNamespace(nspid))
637 newRelation->relpersistence = RELPERSISTENCE_TEMP;
638 else if (isAnyTempNamespace(nspid))
640 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
641 errmsg("cannot create relations in temporary schemas of other sessions")));
644 if (isAnyTempNamespace(nspid))
646 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
647 errmsg("only temporary relations may be created in temporary schemas")));
653 * Try to resolve an unqualified relation name.
654 * Returns OID if relation found in search path, else InvalidOid.
657 RelnameGetRelid(const char *relname)
662 recomputeNamespacePath();
664 foreach(l, activeSearchPath)
666 Oid namespaceId = lfirst_oid(l);
668 relid = get_relname_relid(relname, namespaceId);
669 if (OidIsValid(relid))
673 /* Not found in path */
680 * Determine whether a relation (identified by OID) is visible in the
681 * current search path. Visible means "would be found by searching
682 * for the unqualified relation name".
685 RelationIsVisible(Oid relid)
688 Form_pg_class relform;
692 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
693 if (!HeapTupleIsValid(reltup))
694 elog(ERROR, "cache lookup failed for relation %u", relid);
695 relform = (Form_pg_class) GETSTRUCT(reltup);
697 recomputeNamespacePath();
700 * Quick check: if it ain't in the path at all, it ain't visible. Items in
701 * the system namespace are surely in the path and so we needn't even do
702 * list_member_oid() for them.
704 relnamespace = relform->relnamespace;
705 if (relnamespace != PG_CATALOG_NAMESPACE &&
706 !list_member_oid(activeSearchPath, relnamespace))
711 * If it is in the path, it might still not be visible; it could be
712 * hidden by another relation of the same name earlier in the path. So
713 * we must do a slow check for conflicting relations.
715 char *relname = NameStr(relform->relname);
719 foreach(l, activeSearchPath)
721 Oid namespaceId = lfirst_oid(l);
723 if (namespaceId == relnamespace)
725 /* Found it first in path */
729 if (OidIsValid(get_relname_relid(relname, namespaceId)))
731 /* Found something else first in path */
737 ReleaseSysCache(reltup);
745 * Try to resolve an unqualified datatype name.
746 * Returns OID if type found in search path, else InvalidOid.
748 * This is essentially the same as RelnameGetRelid.
751 TypenameGetTypid(const char *typname)
756 recomputeNamespacePath();
758 foreach(l, activeSearchPath)
760 Oid namespaceId = lfirst_oid(l);
762 typid = GetSysCacheOid2(TYPENAMENSP,
763 PointerGetDatum(typname),
764 ObjectIdGetDatum(namespaceId));
765 if (OidIsValid(typid))
769 /* Not found in path */
775 * Determine whether a type (identified by OID) is visible in the
776 * current search path. Visible means "would be found by searching
777 * for the unqualified type name".
780 TypeIsVisible(Oid typid)
783 Form_pg_type typform;
787 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
788 if (!HeapTupleIsValid(typtup))
789 elog(ERROR, "cache lookup failed for type %u", typid);
790 typform = (Form_pg_type) GETSTRUCT(typtup);
792 recomputeNamespacePath();
795 * Quick check: if it ain't in the path at all, it ain't visible. Items in
796 * the system namespace are surely in the path and so we needn't even do
797 * list_member_oid() for them.
799 typnamespace = typform->typnamespace;
800 if (typnamespace != PG_CATALOG_NAMESPACE &&
801 !list_member_oid(activeSearchPath, typnamespace))
806 * If it is in the path, it might still not be visible; it could be
807 * hidden by another type of the same name earlier in the path. So we
808 * must do a slow check for conflicting types.
810 char *typname = NameStr(typform->typname);
814 foreach(l, activeSearchPath)
816 Oid namespaceId = lfirst_oid(l);
818 if (namespaceId == typnamespace)
820 /* Found it first in path */
824 if (SearchSysCacheExists2(TYPENAMENSP,
825 PointerGetDatum(typname),
826 ObjectIdGetDatum(namespaceId)))
828 /* Found something else first in path */
834 ReleaseSysCache(typtup);
841 * FuncnameGetCandidates
842 * Given a possibly-qualified function name and argument count,
843 * retrieve a list of the possible matches.
845 * If nargs is -1, we return all functions matching the given name,
846 * regardless of argument count. (argnames must be NIL, and expand_variadic
847 * and expand_defaults must be false, in this case.)
849 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
850 * and only functions having all the listed argument names will be returned.
851 * (We assume that length(argnames) <= nargs and all the passed-in names are
852 * distinct.) The returned structs will include an argnumbers array showing
853 * the actual argument index for each logical argument position.
855 * If expand_variadic is true, then variadic functions having the same number
856 * or fewer arguments will be retrieved, with the variadic argument and any
857 * additional argument positions filled with the variadic element type.
858 * nvargs in the returned struct is set to the number of such arguments.
859 * If expand_variadic is false, variadic arguments are not treated specially,
860 * and the returned nvargs will always be zero.
862 * If expand_defaults is true, functions that could match after insertion of
863 * default argument values will also be retrieved. In this case the returned
864 * structs could have nargs > passed-in nargs, and ndargs is set to the number
865 * of additional args (which can be retrieved from the function's
866 * proargdefaults entry).
868 * It is not possible for nvargs and ndargs to both be nonzero in the same
869 * list entry, since default insertion allows matches to functions with more
870 * than nargs arguments while the variadic transformation requires the same
873 * When argnames isn't NIL, the returned args[] type arrays are not ordered
874 * according to the functions' declarations, but rather according to the call:
875 * first any positional arguments, then the named arguments, then defaulted
876 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
877 * array can be used to map this back to the catalog information.
878 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
880 * We search a single namespace if the function name is qualified, else
881 * all namespaces in the search path. In the multiple-namespace case,
882 * we arrange for entries in earlier namespaces to mask identical entries in
885 * When expanding variadics, we arrange for non-variadic functions to mask
886 * variadic ones if the expanded argument list is the same. It is still
887 * possible for there to be conflicts between different variadic functions,
890 * It is guaranteed that the return list will never contain multiple entries
891 * with identical argument lists. When expand_defaults is true, the entries
892 * could have more than nargs positions, but we still guarantee that they are
893 * distinct in the first nargs positions. However, if argnames isn't NIL or
894 * either expand_variadic or expand_defaults is true, there might be multiple
895 * candidate functions that expand to identical argument lists. Rather than
896 * throw error here, we report such situations by returning a single entry
897 * with oid = 0 that represents a set of such conflicting candidates.
898 * The caller might end up discarding such an entry anyway, but if it selects
899 * such an entry it should react as though the call were ambiguous.
902 FuncnameGetCandidates(List *names, int nargs, List *argnames,
903 bool expand_variadic, bool expand_defaults)
905 FuncCandidateList resultList = NULL;
906 bool any_special = false;
913 /* check for caller error */
914 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
916 /* deconstruct the name list */
917 DeconstructQualifiedName(names, &schemaname, &funcname);
921 /* use exact schema given */
922 namespaceId = LookupExplicitNamespace(schemaname);
926 /* flag to indicate we need namespace search */
927 namespaceId = InvalidOid;
928 recomputeNamespacePath();
931 /* Search syscache by name only */
932 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
934 for (i = 0; i < catlist->n_members; i++)
936 HeapTuple proctup = &catlist->members[i]->tuple;
937 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
938 int pronargs = procform->pronargs;
944 int *argnumbers = NULL;
945 FuncCandidateList newResult;
947 if (OidIsValid(namespaceId))
949 /* Consider only procs in specified namespace */
950 if (procform->pronamespace != namespaceId)
956 * Consider only procs that are in the search path and are not in
957 * the temp namespace.
961 foreach(nsp, activeSearchPath)
963 if (procform->pronamespace == lfirst_oid(nsp) &&
964 procform->pronamespace != myTempNamespace)
969 continue; /* proc is not in search path */
975 * Call uses named or mixed notation
977 * Named or mixed notation can match a variadic function only if
978 * expand_variadic is off; otherwise there is no way to match the
979 * presumed-nameless parameters expanded from the variadic array.
981 if (OidIsValid(procform->provariadic) && expand_variadic)
983 va_elem_type = InvalidOid;
987 * Check argument count.
989 Assert(nargs >= 0); /* -1 not supported with argnames */
991 if (pronargs > nargs && expand_defaults)
993 /* Ignore if not enough default expressions */
994 if (nargs + procform->pronargdefaults < pronargs)
999 use_defaults = false;
1001 /* Ignore if it doesn't match requested argument count */
1002 if (pronargs != nargs && !use_defaults)
1005 /* Check for argument name match, generate positional mapping */
1006 if (!MatchNamedCall(proctup, nargs, argnames,
1010 /* Named argument matching is always "special" */
1016 * Call uses positional notation
1018 * Check if function is variadic, and get variadic element type if
1019 * so. If expand_variadic is false, we should just ignore
1022 if (pronargs <= nargs && expand_variadic)
1024 va_elem_type = procform->provariadic;
1025 variadic = OidIsValid(va_elem_type);
1026 any_special |= variadic;
1030 va_elem_type = InvalidOid;
1035 * Check if function can match by using parameter defaults.
1037 if (pronargs > nargs && expand_defaults)
1039 /* Ignore if not enough default expressions */
1040 if (nargs + procform->pronargdefaults < pronargs)
1042 use_defaults = true;
1046 use_defaults = false;
1048 /* Ignore if it doesn't match requested argument count */
1049 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1054 * We must compute the effective argument list so that we can easily
1055 * compare it to earlier results. We waste a palloc cycle if it gets
1056 * masked by an earlier result, but really that's a pretty infrequent
1057 * case so it's not worth worrying about.
1059 effective_nargs = Max(pronargs, nargs);
1060 newResult = (FuncCandidateList)
1061 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
1062 + effective_nargs * sizeof(Oid));
1063 newResult->pathpos = pathpos;
1064 newResult->oid = HeapTupleGetOid(proctup);
1065 newResult->nargs = effective_nargs;
1066 newResult->argnumbers = argnumbers;
1069 /* Re-order the argument types into call's logical order */
1070 Oid *proargtypes = procform->proargtypes.values;
1073 for (i = 0; i < pronargs; i++)
1074 newResult->args[i] = proargtypes[argnumbers[i]];
1078 /* Simple positional case, just copy proargtypes as-is */
1079 memcpy(newResult->args, procform->proargtypes.values,
1080 pronargs * sizeof(Oid));
1086 newResult->nvargs = effective_nargs - pronargs + 1;
1087 /* Expand variadic argument into N copies of element type */
1088 for (i = pronargs - 1; i < effective_nargs; i++)
1089 newResult->args[i] = va_elem_type;
1092 newResult->nvargs = 0;
1093 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1096 * Does it have the same arguments as something we already accepted?
1097 * If so, decide what to do to avoid returning duplicate argument
1098 * lists. We can skip this check for the single-namespace case if no
1099 * special (named, variadic or defaults) match has been made, since
1100 * then the unique index on pg_proc guarantees all the matches have
1101 * different argument lists.
1103 if (resultList != NULL &&
1104 (any_special || !OidIsValid(namespaceId)))
1107 * If we have an ordered list from SearchSysCacheList (the normal
1108 * case), then any conflicting proc must immediately adjoin this
1109 * one in the list, so we only need to look at the newest result
1110 * item. If we have an unordered list, we have to scan the whole
1111 * result list. Also, if either the current candidate or any
1112 * previous candidate is a special match, we can't assume that
1113 * conflicts are adjacent.
1115 * We ignore defaulted arguments in deciding what is a match.
1117 FuncCandidateList prevResult;
1119 if (catlist->ordered && !any_special)
1121 /* ndargs must be 0 if !any_special */
1122 if (effective_nargs == resultList->nargs &&
1123 memcmp(newResult->args,
1125 effective_nargs * sizeof(Oid)) == 0)
1126 prevResult = resultList;
1132 int cmp_nargs = newResult->nargs - newResult->ndargs;
1134 for (prevResult = resultList;
1136 prevResult = prevResult->next)
1138 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1139 memcmp(newResult->args,
1141 cmp_nargs * sizeof(Oid)) == 0)
1149 * We have a match with a previous result. Decide which one
1150 * to keep, or mark it ambiguous if we can't decide. The
1151 * logic here is preference > 0 means prefer the old result,
1152 * preference < 0 means prefer the new, preference = 0 means
1157 if (pathpos != prevResult->pathpos)
1160 * Prefer the one that's earlier in the search path.
1162 preference = pathpos - prevResult->pathpos;
1164 else if (variadic && prevResult->nvargs == 0)
1167 * With variadic functions we could have, for example,
1168 * both foo(numeric) and foo(variadic numeric[]) in the
1169 * same namespace; if so we prefer the non-variadic match
1170 * on efficiency grounds.
1174 else if (!variadic && prevResult->nvargs > 0)
1181 * We can't decide. This can happen with, for example,
1182 * both foo(numeric, variadic numeric[]) and
1183 * foo(variadic numeric[]) in the same namespace, or
1184 * both foo(int) and foo (int, int default something)
1185 * in the same namespace, or both foo(a int, b text)
1186 * and foo(b text, a int) in the same namespace.
1194 /* keep previous result */
1198 else if (preference < 0)
1200 /* remove previous result from the list */
1201 if (prevResult == resultList)
1202 resultList = prevResult->next;
1205 FuncCandidateList prevPrevResult;
1207 for (prevPrevResult = resultList;
1209 prevPrevResult = prevPrevResult->next)
1211 if (prevResult == prevPrevResult->next)
1213 prevPrevResult->next = prevResult->next;
1217 Assert(prevPrevResult); /* assert we found it */
1220 /* fall through to add newResult to list */
1224 /* mark old result as ambiguous, discard new */
1225 prevResult->oid = InvalidOid;
1233 * Okay to add it to result list
1235 newResult->next = resultList;
1236 resultList = newResult;
1239 ReleaseSysCacheList(catlist);
1246 * Given a pg_proc heap tuple and a call's list of argument names,
1247 * check whether the function could match the call.
1249 * The call could match if all supplied argument names are accepted by
1250 * the function, in positions after the last positional argument, and there
1251 * are defaults for all unsupplied arguments.
1253 * The number of positional arguments is nargs - list_length(argnames).
1254 * Note caller has already done basic checks on argument count.
1256 * On match, return true and fill *argnumbers with a palloc'd array showing
1257 * the mapping from call argument positions to actual function argument
1258 * numbers. Defaulted arguments are included in this map, at positions
1259 * after the last supplied argument.
1262 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1265 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1266 int pronargs = procform->pronargs;
1267 int numposargs = nargs - list_length(argnames);
1272 bool arggiven[FUNC_MAX_ARGS];
1274 int ap; /* call args position */
1275 int pp; /* proargs position */
1278 Assert(argnames != NIL);
1279 Assert(numposargs >= 0);
1280 Assert(nargs <= pronargs);
1282 /* Ignore this function if its proargnames is null */
1283 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1288 /* OK, let's extract the argument names and types */
1289 pronallargs = get_func_arg_info(proctup,
1290 &p_argtypes, &p_argnames, &p_argmodes);
1291 Assert(p_argnames != NULL);
1293 /* initialize state for matching */
1294 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1295 memset(arggiven, false, pronargs * sizeof(bool));
1297 /* there are numposargs positional args before the named args */
1298 for (ap = 0; ap < numposargs; ap++)
1300 (*argnumbers)[ap] = ap;
1301 arggiven[ap] = true;
1304 /* now examine the named args */
1305 foreach(lc, argnames)
1307 char *argname = (char *) lfirst(lc);
1313 for (i = 0; i < pronallargs; i++)
1315 /* consider only input parameters */
1317 (p_argmodes[i] != FUNC_PARAM_IN &&
1318 p_argmodes[i] != FUNC_PARAM_INOUT &&
1319 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1321 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1323 /* fail if argname matches a positional argument */
1326 arggiven[pp] = true;
1327 (*argnumbers)[ap] = pp;
1331 /* increase pp only for input parameters */
1334 /* if name isn't in proargnames, fail */
1340 Assert(ap == nargs); /* processed all actual parameters */
1342 /* Check for default arguments */
1343 if (nargs < pronargs)
1345 int first_arg_with_default = pronargs - procform->pronargdefaults;
1347 for (pp = numposargs; pp < pronargs; pp++)
1351 /* fail if arg not given and no default available */
1352 if (pp < first_arg_with_default)
1354 (*argnumbers)[ap++] = pp;
1358 Assert(ap == pronargs); /* processed all function parameters */
1365 * Determine whether a function (identified by OID) is visible in the
1366 * current search path. Visible means "would be found by searching
1367 * for the unqualified function name with exact argument matches".
1370 FunctionIsVisible(Oid funcid)
1373 Form_pg_proc procform;
1377 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1378 if (!HeapTupleIsValid(proctup))
1379 elog(ERROR, "cache lookup failed for function %u", funcid);
1380 procform = (Form_pg_proc) GETSTRUCT(proctup);
1382 recomputeNamespacePath();
1385 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1386 * the system namespace are surely in the path and so we needn't even do
1387 * list_member_oid() for them.
1389 pronamespace = procform->pronamespace;
1390 if (pronamespace != PG_CATALOG_NAMESPACE &&
1391 !list_member_oid(activeSearchPath, pronamespace))
1396 * If it is in the path, it might still not be visible; it could be
1397 * hidden by another proc of the same name and arguments earlier in
1398 * the path. So we must do a slow check to see if this is the same
1399 * proc that would be found by FuncnameGetCandidates.
1401 char *proname = NameStr(procform->proname);
1402 int nargs = procform->pronargs;
1403 FuncCandidateList clist;
1407 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1408 nargs, NIL, false, false);
1410 for (; clist; clist = clist->next)
1412 if (memcmp(clist->args, procform->proargtypes.values,
1413 nargs * sizeof(Oid)) == 0)
1415 /* Found the expected entry; is it the right proc? */
1416 visible = (clist->oid == funcid);
1422 ReleaseSysCache(proctup);
1430 * Given a possibly-qualified operator name and exact input datatypes,
1431 * look up the operator. Returns InvalidOid if not found.
1433 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1436 * If the operator name is not schema-qualified, it is sought in the current
1437 * namespace search path.
1440 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1447 /* deconstruct the name list */
1448 DeconstructQualifiedName(names, &schemaname, &opername);
1452 /* search only in exact schema given */
1456 namespaceId = LookupExplicitNamespace(schemaname);
1457 opertup = SearchSysCache4(OPERNAMENSP,
1458 CStringGetDatum(opername),
1459 ObjectIdGetDatum(oprleft),
1460 ObjectIdGetDatum(oprright),
1461 ObjectIdGetDatum(namespaceId));
1462 if (HeapTupleIsValid(opertup))
1464 Oid result = HeapTupleGetOid(opertup);
1466 ReleaseSysCache(opertup);
1472 /* Search syscache by name and argument types */
1473 catlist = SearchSysCacheList3(OPERNAMENSP,
1474 CStringGetDatum(opername),
1475 ObjectIdGetDatum(oprleft),
1476 ObjectIdGetDatum(oprright));
1478 if (catlist->n_members == 0)
1480 /* no hope, fall out early */
1481 ReleaseSysCacheList(catlist);
1486 * We have to find the list member that is first in the search path, if
1487 * there's more than one. This doubly-nested loop looks ugly, but in
1488 * practice there should usually be few catlist members.
1490 recomputeNamespacePath();
1492 foreach(l, activeSearchPath)
1494 Oid namespaceId = lfirst_oid(l);
1497 if (namespaceId == myTempNamespace)
1498 continue; /* do not look in temp namespace */
1500 for (i = 0; i < catlist->n_members; i++)
1502 HeapTuple opertup = &catlist->members[i]->tuple;
1503 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1505 if (operform->oprnamespace == namespaceId)
1507 Oid result = HeapTupleGetOid(opertup);
1509 ReleaseSysCacheList(catlist);
1515 ReleaseSysCacheList(catlist);
1520 * OpernameGetCandidates
1521 * Given a possibly-qualified operator name and operator kind,
1522 * retrieve a list of the possible matches.
1524 * If oprkind is '\0', we return all operators matching the given name,
1525 * regardless of arguments.
1527 * We search a single namespace if the operator name is qualified, else
1528 * all namespaces in the search path. The return list will never contain
1529 * multiple entries with identical argument lists --- in the multiple-
1530 * namespace case, we arrange for entries in earlier namespaces to mask
1531 * identical entries in later namespaces.
1533 * The returned items always have two args[] entries --- one or the other
1534 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1537 OpernameGetCandidates(List *names, char oprkind)
1539 FuncCandidateList resultList = NULL;
1540 char *resultSpace = NULL;
1548 /* deconstruct the name list */
1549 DeconstructQualifiedName(names, &schemaname, &opername);
1553 /* use exact schema given */
1554 namespaceId = LookupExplicitNamespace(schemaname);
1558 /* flag to indicate we need namespace search */
1559 namespaceId = InvalidOid;
1560 recomputeNamespacePath();
1563 /* Search syscache by name only */
1564 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1567 * In typical scenarios, most if not all of the operators found by the
1568 * catcache search will end up getting returned; and there can be quite a
1569 * few, for common operator names such as '=' or '+'. To reduce the time
1570 * spent in palloc, we allocate the result space as an array large enough
1571 * to hold all the operators. The original coding of this routine did a
1572 * separate palloc for each operator, but profiling revealed that the
1573 * pallocs used an unreasonably large fraction of parsing time.
1575 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1577 if (catlist->n_members > 0)
1578 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1580 for (i = 0; i < catlist->n_members; i++)
1582 HeapTuple opertup = &catlist->members[i]->tuple;
1583 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1585 FuncCandidateList newResult;
1587 /* Ignore operators of wrong kind, if specific kind requested */
1588 if (oprkind && operform->oprkind != oprkind)
1591 if (OidIsValid(namespaceId))
1593 /* Consider only opers in specified namespace */
1594 if (operform->oprnamespace != namespaceId)
1596 /* No need to check args, they must all be different */
1601 * Consider only opers that are in the search path and are not in
1602 * the temp namespace.
1606 foreach(nsp, activeSearchPath)
1608 if (operform->oprnamespace == lfirst_oid(nsp) &&
1609 operform->oprnamespace != myTempNamespace)
1614 continue; /* oper is not in search path */
1617 * Okay, it's in the search path, but does it have the same
1618 * arguments as something we already accepted? If so, keep only
1619 * the one that appears earlier in the search path.
1621 * If we have an ordered list from SearchSysCacheList (the normal
1622 * case), then any conflicting oper must immediately adjoin this
1623 * one in the list, so we only need to look at the newest result
1624 * item. If we have an unordered list, we have to scan the whole
1629 FuncCandidateList prevResult;
1631 if (catlist->ordered)
1633 if (operform->oprleft == resultList->args[0] &&
1634 operform->oprright == resultList->args[1])
1635 prevResult = resultList;
1641 for (prevResult = resultList;
1643 prevResult = prevResult->next)
1645 if (operform->oprleft == prevResult->args[0] &&
1646 operform->oprright == prevResult->args[1])
1652 /* We have a match with a previous result */
1653 Assert(pathpos != prevResult->pathpos);
1654 if (pathpos > prevResult->pathpos)
1655 continue; /* keep previous result */
1656 /* replace previous result */
1657 prevResult->pathpos = pathpos;
1658 prevResult->oid = HeapTupleGetOid(opertup);
1659 continue; /* args are same, of course */
1665 * Okay to add it to result list
1667 newResult = (FuncCandidateList) (resultSpace + nextResult);
1668 nextResult += SPACE_PER_OP;
1670 newResult->pathpos = pathpos;
1671 newResult->oid = HeapTupleGetOid(opertup);
1672 newResult->nargs = 2;
1673 newResult->nvargs = 0;
1674 newResult->ndargs = 0;
1675 newResult->argnumbers = NULL;
1676 newResult->args[0] = operform->oprleft;
1677 newResult->args[1] = operform->oprright;
1678 newResult->next = resultList;
1679 resultList = newResult;
1682 ReleaseSysCacheList(catlist);
1689 * Determine whether an operator (identified by OID) is visible in the
1690 * current search path. Visible means "would be found by searching
1691 * for the unqualified operator name with exact argument matches".
1694 OperatorIsVisible(Oid oprid)
1697 Form_pg_operator oprform;
1701 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1702 if (!HeapTupleIsValid(oprtup))
1703 elog(ERROR, "cache lookup failed for operator %u", oprid);
1704 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1706 recomputeNamespacePath();
1709 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1710 * the system namespace are surely in the path and so we needn't even do
1711 * list_member_oid() for them.
1713 oprnamespace = oprform->oprnamespace;
1714 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1715 !list_member_oid(activeSearchPath, oprnamespace))
1720 * If it is in the path, it might still not be visible; it could be
1721 * hidden by another operator of the same name and arguments earlier
1722 * in the path. So we must do a slow check to see if this is the same
1723 * operator that would be found by OpernameGetOprId.
1725 char *oprname = NameStr(oprform->oprname);
1727 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1728 oprform->oprleft, oprform->oprright)
1732 ReleaseSysCache(oprtup);
1739 * OpclassnameGetOpcid
1740 * Try to resolve an unqualified index opclass name.
1741 * Returns OID if opclass found in search path, else InvalidOid.
1743 * This is essentially the same as TypenameGetTypid, but we have to have
1744 * an extra argument for the index AM OID.
1747 OpclassnameGetOpcid(Oid amid, const char *opcname)
1752 recomputeNamespacePath();
1754 foreach(l, activeSearchPath)
1756 Oid namespaceId = lfirst_oid(l);
1758 if (namespaceId == myTempNamespace)
1759 continue; /* do not look in temp namespace */
1761 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1762 ObjectIdGetDatum(amid),
1763 PointerGetDatum(opcname),
1764 ObjectIdGetDatum(namespaceId));
1765 if (OidIsValid(opcid))
1769 /* Not found in path */
1775 * Determine whether an opclass (identified by OID) is visible in the
1776 * current search path. Visible means "would be found by searching
1777 * for the unqualified opclass name".
1780 OpclassIsVisible(Oid opcid)
1783 Form_pg_opclass opcform;
1787 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1788 if (!HeapTupleIsValid(opctup))
1789 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1790 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1792 recomputeNamespacePath();
1795 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1796 * the system namespace are surely in the path and so we needn't even do
1797 * list_member_oid() for them.
1799 opcnamespace = opcform->opcnamespace;
1800 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1801 !list_member_oid(activeSearchPath, opcnamespace))
1806 * If it is in the path, it might still not be visible; it could be
1807 * hidden by another opclass of the same name earlier in the path. So
1808 * we must do a slow check to see if this opclass would be found by
1809 * OpclassnameGetOpcid.
1811 char *opcname = NameStr(opcform->opcname);
1813 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1816 ReleaseSysCache(opctup);
1822 * OpfamilynameGetOpfid
1823 * Try to resolve an unqualified index opfamily name.
1824 * Returns OID if opfamily found in search path, else InvalidOid.
1826 * This is essentially the same as TypenameGetTypid, but we have to have
1827 * an extra argument for the index AM OID.
1830 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1835 recomputeNamespacePath();
1837 foreach(l, activeSearchPath)
1839 Oid namespaceId = lfirst_oid(l);
1841 if (namespaceId == myTempNamespace)
1842 continue; /* do not look in temp namespace */
1844 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1845 ObjectIdGetDatum(amid),
1846 PointerGetDatum(opfname),
1847 ObjectIdGetDatum(namespaceId));
1848 if (OidIsValid(opfid))
1852 /* Not found in path */
1858 * Determine whether an opfamily (identified by OID) is visible in the
1859 * current search path. Visible means "would be found by searching
1860 * for the unqualified opfamily name".
1863 OpfamilyIsVisible(Oid opfid)
1866 Form_pg_opfamily opfform;
1870 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1871 if (!HeapTupleIsValid(opftup))
1872 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1873 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1875 recomputeNamespacePath();
1878 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1879 * the system namespace are surely in the path and so we needn't even do
1880 * list_member_oid() for them.
1882 opfnamespace = opfform->opfnamespace;
1883 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1884 !list_member_oid(activeSearchPath, opfnamespace))
1889 * If it is in the path, it might still not be visible; it could be
1890 * hidden by another opfamily of the same name earlier in the path. So
1891 * we must do a slow check to see if this opfamily would be found by
1892 * OpfamilynameGetOpfid.
1894 char *opfname = NameStr(opfform->opfname);
1896 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1899 ReleaseSysCache(opftup);
1905 * CollationGetCollid
1906 * Try to resolve an unqualified collation name.
1907 * Returns OID if collation found in search path, else InvalidOid.
1910 CollationGetCollid(const char *collname)
1912 int32 dbencoding = GetDatabaseEncoding();
1915 recomputeNamespacePath();
1917 foreach(l, activeSearchPath)
1919 Oid namespaceId = lfirst_oid(l);
1922 if (namespaceId == myTempNamespace)
1923 continue; /* do not look in temp namespace */
1925 /* Check for database-encoding-specific entry */
1926 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1927 PointerGetDatum(collname),
1928 Int32GetDatum(dbencoding),
1929 ObjectIdGetDatum(namespaceId));
1930 if (OidIsValid(collid))
1933 /* Check for any-encoding entry */
1934 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1935 PointerGetDatum(collname),
1937 ObjectIdGetDatum(namespaceId));
1938 if (OidIsValid(collid))
1942 /* Not found in path */
1947 * CollationIsVisible
1948 * Determine whether a collation (identified by OID) is visible in the
1949 * current search path. Visible means "would be found by searching
1950 * for the unqualified collation name".
1953 CollationIsVisible(Oid collid)
1956 Form_pg_collation collform;
1960 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1961 if (!HeapTupleIsValid(colltup))
1962 elog(ERROR, "cache lookup failed for collation %u", collid);
1963 collform = (Form_pg_collation) GETSTRUCT(colltup);
1965 recomputeNamespacePath();
1968 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1969 * the system namespace are surely in the path and so we needn't even do
1970 * list_member_oid() for them.
1972 collnamespace = collform->collnamespace;
1973 if (collnamespace != PG_CATALOG_NAMESPACE &&
1974 !list_member_oid(activeSearchPath, collnamespace))
1979 * If it is in the path, it might still not be visible; it could be
1980 * hidden by another conversion of the same name earlier in the path.
1981 * So we must do a slow check to see if this conversion would be found
1982 * by CollationGetCollid.
1984 char *collname = NameStr(collform->collname);
1986 visible = (CollationGetCollid(collname) == collid);
1989 ReleaseSysCache(colltup);
1996 * ConversionGetConid
1997 * Try to resolve an unqualified conversion name.
1998 * Returns OID if conversion found in search path, else InvalidOid.
2000 * This is essentially the same as RelnameGetRelid.
2003 ConversionGetConid(const char *conname)
2008 recomputeNamespacePath();
2010 foreach(l, activeSearchPath)
2012 Oid namespaceId = lfirst_oid(l);
2014 if (namespaceId == myTempNamespace)
2015 continue; /* do not look in temp namespace */
2017 conid = GetSysCacheOid2(CONNAMENSP,
2018 PointerGetDatum(conname),
2019 ObjectIdGetDatum(namespaceId));
2020 if (OidIsValid(conid))
2024 /* Not found in path */
2029 * ConversionIsVisible
2030 * Determine whether a conversion (identified by OID) is visible in the
2031 * current search path. Visible means "would be found by searching
2032 * for the unqualified conversion name".
2035 ConversionIsVisible(Oid conid)
2038 Form_pg_conversion conform;
2042 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2043 if (!HeapTupleIsValid(contup))
2044 elog(ERROR, "cache lookup failed for conversion %u", conid);
2045 conform = (Form_pg_conversion) GETSTRUCT(contup);
2047 recomputeNamespacePath();
2050 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2051 * the system namespace are surely in the path and so we needn't even do
2052 * list_member_oid() for them.
2054 connamespace = conform->connamespace;
2055 if (connamespace != PG_CATALOG_NAMESPACE &&
2056 !list_member_oid(activeSearchPath, connamespace))
2061 * If it is in the path, it might still not be visible; it could be
2062 * hidden by another conversion of the same name earlier in the path.
2063 * So we must do a slow check to see if this conversion would be found
2064 * by ConversionGetConid.
2066 char *conname = NameStr(conform->conname);
2068 visible = (ConversionGetConid(conname) == conid);
2071 ReleaseSysCache(contup);
2077 * get_ts_parser_oid - find a TS parser by possibly qualified name
2079 * If not found, returns InvalidOid if missing_ok, else throws error
2082 get_ts_parser_oid(List *names, bool missing_ok)
2087 Oid prsoid = InvalidOid;
2090 /* deconstruct the name list */
2091 DeconstructQualifiedName(names, &schemaname, &parser_name);
2095 /* use exact schema given */
2096 namespaceId = LookupExplicitNamespace(schemaname);
2097 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2098 PointerGetDatum(parser_name),
2099 ObjectIdGetDatum(namespaceId));
2103 /* search for it in search path */
2104 recomputeNamespacePath();
2106 foreach(l, activeSearchPath)
2108 namespaceId = lfirst_oid(l);
2110 if (namespaceId == myTempNamespace)
2111 continue; /* do not look in temp namespace */
2113 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2114 PointerGetDatum(parser_name),
2115 ObjectIdGetDatum(namespaceId));
2116 if (OidIsValid(prsoid))
2121 if (!OidIsValid(prsoid) && !missing_ok)
2123 (errcode(ERRCODE_UNDEFINED_OBJECT),
2124 errmsg("text search parser \"%s\" does not exist",
2125 NameListToString(names))));
2132 * Determine whether a parser (identified by OID) is visible in the
2133 * current search path. Visible means "would be found by searching
2134 * for the unqualified parser name".
2137 TSParserIsVisible(Oid prsId)
2140 Form_pg_ts_parser form;
2144 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2145 if (!HeapTupleIsValid(tup))
2146 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2147 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2149 recomputeNamespacePath();
2152 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2153 * the system namespace are surely in the path and so we needn't even do
2154 * list_member_oid() for them.
2156 namespace = form->prsnamespace;
2157 if (namespace != PG_CATALOG_NAMESPACE &&
2158 !list_member_oid(activeSearchPath, namespace))
2163 * If it is in the path, it might still not be visible; it could be
2164 * hidden by another parser of the same name earlier in the path. So
2165 * we must do a slow check for conflicting parsers.
2167 char *name = NameStr(form->prsname);
2171 foreach(l, activeSearchPath)
2173 Oid namespaceId = lfirst_oid(l);
2175 if (namespaceId == myTempNamespace)
2176 continue; /* do not look in temp namespace */
2178 if (namespaceId == namespace)
2180 /* Found it first in path */
2184 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2185 PointerGetDatum(name),
2186 ObjectIdGetDatum(namespaceId)))
2188 /* Found something else first in path */
2194 ReleaseSysCache(tup);
2200 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2202 * If not found, returns InvalidOid if failOK, else throws error
2205 get_ts_dict_oid(List *names, bool missing_ok)
2210 Oid dictoid = InvalidOid;
2213 /* deconstruct the name list */
2214 DeconstructQualifiedName(names, &schemaname, &dict_name);
2218 /* use exact schema given */
2219 namespaceId = LookupExplicitNamespace(schemaname);
2220 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2221 PointerGetDatum(dict_name),
2222 ObjectIdGetDatum(namespaceId));
2226 /* search for it in search path */
2227 recomputeNamespacePath();
2229 foreach(l, activeSearchPath)
2231 namespaceId = lfirst_oid(l);
2233 if (namespaceId == myTempNamespace)
2234 continue; /* do not look in temp namespace */
2236 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2237 PointerGetDatum(dict_name),
2238 ObjectIdGetDatum(namespaceId));
2239 if (OidIsValid(dictoid))
2244 if (!OidIsValid(dictoid) && !missing_ok)
2246 (errcode(ERRCODE_UNDEFINED_OBJECT),
2247 errmsg("text search dictionary \"%s\" does not exist",
2248 NameListToString(names))));
2254 * TSDictionaryIsVisible
2255 * Determine whether a dictionary (identified by OID) is visible in the
2256 * current search path. Visible means "would be found by searching
2257 * for the unqualified dictionary name".
2260 TSDictionaryIsVisible(Oid dictId)
2263 Form_pg_ts_dict form;
2267 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2268 if (!HeapTupleIsValid(tup))
2269 elog(ERROR, "cache lookup failed for text search dictionary %u",
2271 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2273 recomputeNamespacePath();
2276 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2277 * the system namespace are surely in the path and so we needn't even do
2278 * list_member_oid() for them.
2280 namespace = form->dictnamespace;
2281 if (namespace != PG_CATALOG_NAMESPACE &&
2282 !list_member_oid(activeSearchPath, namespace))
2287 * If it is in the path, it might still not be visible; it could be
2288 * hidden by another dictionary of the same name earlier in the path.
2289 * So we must do a slow check for conflicting dictionaries.
2291 char *name = NameStr(form->dictname);
2295 foreach(l, activeSearchPath)
2297 Oid namespaceId = lfirst_oid(l);
2299 if (namespaceId == myTempNamespace)
2300 continue; /* do not look in temp namespace */
2302 if (namespaceId == namespace)
2304 /* Found it first in path */
2308 if (SearchSysCacheExists2(TSDICTNAMENSP,
2309 PointerGetDatum(name),
2310 ObjectIdGetDatum(namespaceId)))
2312 /* Found something else first in path */
2318 ReleaseSysCache(tup);
2324 * get_ts_template_oid - find a TS template by possibly qualified name
2326 * If not found, returns InvalidOid if missing_ok, else throws error
2329 get_ts_template_oid(List *names, bool missing_ok)
2332 char *template_name;
2334 Oid tmploid = InvalidOid;
2337 /* deconstruct the name list */
2338 DeconstructQualifiedName(names, &schemaname, &template_name);
2342 /* use exact schema given */
2343 namespaceId = LookupExplicitNamespace(schemaname);
2344 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2345 PointerGetDatum(template_name),
2346 ObjectIdGetDatum(namespaceId));
2350 /* search for it in search path */
2351 recomputeNamespacePath();
2353 foreach(l, activeSearchPath)
2355 namespaceId = lfirst_oid(l);
2357 if (namespaceId == myTempNamespace)
2358 continue; /* do not look in temp namespace */
2360 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2361 PointerGetDatum(template_name),
2362 ObjectIdGetDatum(namespaceId));
2363 if (OidIsValid(tmploid))
2368 if (!OidIsValid(tmploid) && !missing_ok)
2370 (errcode(ERRCODE_UNDEFINED_OBJECT),
2371 errmsg("text search template \"%s\" does not exist",
2372 NameListToString(names))));
2378 * TSTemplateIsVisible
2379 * Determine whether a template (identified by OID) is visible in the
2380 * current search path. Visible means "would be found by searching
2381 * for the unqualified template name".
2384 TSTemplateIsVisible(Oid tmplId)
2387 Form_pg_ts_template form;
2391 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2392 if (!HeapTupleIsValid(tup))
2393 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2394 form = (Form_pg_ts_template) GETSTRUCT(tup);
2396 recomputeNamespacePath();
2399 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2400 * the system namespace are surely in the path and so we needn't even do
2401 * list_member_oid() for them.
2403 namespace = form->tmplnamespace;
2404 if (namespace != PG_CATALOG_NAMESPACE &&
2405 !list_member_oid(activeSearchPath, namespace))
2410 * If it is in the path, it might still not be visible; it could be
2411 * hidden by another template of the same name earlier in the path. So
2412 * we must do a slow check for conflicting templates.
2414 char *name = NameStr(form->tmplname);
2418 foreach(l, activeSearchPath)
2420 Oid namespaceId = lfirst_oid(l);
2422 if (namespaceId == myTempNamespace)
2423 continue; /* do not look in temp namespace */
2425 if (namespaceId == namespace)
2427 /* Found it first in path */
2431 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2432 PointerGetDatum(name),
2433 ObjectIdGetDatum(namespaceId)))
2435 /* Found something else first in path */
2441 ReleaseSysCache(tup);
2447 * get_ts_config_oid - find a TS config by possibly qualified name
2449 * If not found, returns InvalidOid if missing_ok, else throws error
2452 get_ts_config_oid(List *names, bool missing_ok)
2457 Oid cfgoid = InvalidOid;
2460 /* deconstruct the name list */
2461 DeconstructQualifiedName(names, &schemaname, &config_name);
2465 /* use exact schema given */
2466 namespaceId = LookupExplicitNamespace(schemaname);
2467 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2468 PointerGetDatum(config_name),
2469 ObjectIdGetDatum(namespaceId));
2473 /* search for it in search path */
2474 recomputeNamespacePath();
2476 foreach(l, activeSearchPath)
2478 namespaceId = lfirst_oid(l);
2480 if (namespaceId == myTempNamespace)
2481 continue; /* do not look in temp namespace */
2483 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2484 PointerGetDatum(config_name),
2485 ObjectIdGetDatum(namespaceId));
2486 if (OidIsValid(cfgoid))
2491 if (!OidIsValid(cfgoid) && !missing_ok)
2493 (errcode(ERRCODE_UNDEFINED_OBJECT),
2494 errmsg("text search configuration \"%s\" does not exist",
2495 NameListToString(names))));
2502 * Determine whether a text search configuration (identified by OID)
2503 * is visible in the current search path. Visible means "would be found
2504 * by searching for the unqualified text search configuration name".
2507 TSConfigIsVisible(Oid cfgid)
2510 Form_pg_ts_config form;
2514 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2515 if (!HeapTupleIsValid(tup))
2516 elog(ERROR, "cache lookup failed for text search configuration %u",
2518 form = (Form_pg_ts_config) GETSTRUCT(tup);
2520 recomputeNamespacePath();
2523 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2524 * the system namespace are surely in the path and so we needn't even do
2525 * list_member_oid() for them.
2527 namespace = form->cfgnamespace;
2528 if (namespace != PG_CATALOG_NAMESPACE &&
2529 !list_member_oid(activeSearchPath, namespace))
2534 * If it is in the path, it might still not be visible; it could be
2535 * hidden by another configuration of the same name earlier in the
2536 * path. So we must do a slow check for conflicting configurations.
2538 char *name = NameStr(form->cfgname);
2542 foreach(l, activeSearchPath)
2544 Oid namespaceId = lfirst_oid(l);
2546 if (namespaceId == myTempNamespace)
2547 continue; /* do not look in temp namespace */
2549 if (namespaceId == namespace)
2551 /* Found it first in path */
2555 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2556 PointerGetDatum(name),
2557 ObjectIdGetDatum(namespaceId)))
2559 /* Found something else first in path */
2565 ReleaseSysCache(tup);
2572 * DeconstructQualifiedName
2573 * Given a possibly-qualified name expressed as a list of String nodes,
2574 * extract the schema name and object name.
2576 * *nspname_p is set to NULL if there is no explicit schema name.
2579 DeconstructQualifiedName(List *names,
2584 char *schemaname = NULL;
2585 char *objname = NULL;
2587 switch (list_length(names))
2590 objname = strVal(linitial(names));
2593 schemaname = strVal(linitial(names));
2594 objname = strVal(lsecond(names));
2597 catalogname = strVal(linitial(names));
2598 schemaname = strVal(lsecond(names));
2599 objname = strVal(lthird(names));
2602 * We check the catalog name and then ignore it.
2604 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2606 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2607 errmsg("cross-database references are not implemented: %s",
2608 NameListToString(names))));
2612 (errcode(ERRCODE_SYNTAX_ERROR),
2613 errmsg("improper qualified name (too many dotted names): %s",
2614 NameListToString(names))));
2618 *nspname_p = schemaname;
2619 *objname_p = objname;
2623 * LookupNamespaceNoError
2624 * Look up a schema name.
2626 * Returns the namespace OID, or InvalidOid if not found.
2628 * Note this does NOT perform any permissions check --- callers are
2629 * responsible for being sure that an appropriate check is made.
2630 * In the majority of cases LookupExplicitNamespace is preferable.
2633 LookupNamespaceNoError(const char *nspname)
2635 /* check for pg_temp alias */
2636 if (strcmp(nspname, "pg_temp") == 0)
2638 if (OidIsValid(myTempNamespace))
2639 return myTempNamespace;
2642 * Since this is used only for looking up existing objects, there is
2643 * no point in trying to initialize the temp namespace here; and doing
2644 * so might create problems for some callers. Just report "not found".
2649 return get_namespace_oid(nspname, true);
2653 * LookupExplicitNamespace
2654 * Process an explicitly-specified schema name: look up the schema
2655 * and verify we have USAGE (lookup) rights in it.
2657 * Returns the namespace OID. Raises ereport if any problem.
2660 LookupExplicitNamespace(const char *nspname)
2663 AclResult aclresult;
2665 /* check for pg_temp alias */
2666 if (strcmp(nspname, "pg_temp") == 0)
2668 if (OidIsValid(myTempNamespace))
2669 return myTempNamespace;
2672 * Since this is used only for looking up existing objects, there is
2673 * no point in trying to initialize the temp namespace here; and doing
2674 * so might create problems for some callers. Just fall through and
2675 * give the "does not exist" error.
2679 namespaceId = get_namespace_oid(nspname, false);
2681 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2682 if (aclresult != ACLCHECK_OK)
2683 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2690 * LookupCreationNamespace
2691 * Look up the schema and verify we have CREATE rights on it.
2693 * This is just like LookupExplicitNamespace except for the different
2694 * permission check, and that we are willing to create pg_temp if needed.
2696 * Note: calling this may result in a CommandCounterIncrement operation,
2697 * if we have to create or clean out the temp namespace.
2700 LookupCreationNamespace(const char *nspname)
2703 AclResult aclresult;
2705 /* check for pg_temp alias */
2706 if (strcmp(nspname, "pg_temp") == 0)
2708 /* Initialize temp namespace if first time through */
2709 if (!OidIsValid(myTempNamespace))
2710 InitTempTableNamespace();
2711 return myTempNamespace;
2714 namespaceId = get_namespace_oid(nspname, false);
2716 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2717 if (aclresult != ACLCHECK_OK)
2718 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2725 * Common checks on switching namespaces.
2727 * We complain if (1) the old and new namespaces are the same, (2) either the
2728 * old or new namespaces is a temporary schema (or temporary toast schema), or
2729 * (3) either the old or new namespaces is the TOAST schema.
2732 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2734 if (oldNspOid == nspOid)
2736 (classid == RelationRelationId ?
2737 errcode(ERRCODE_DUPLICATE_TABLE) :
2738 classid == ProcedureRelationId ?
2739 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2740 errcode(ERRCODE_DUPLICATE_OBJECT),
2741 errmsg("%s is already in schema \"%s\"",
2742 getObjectDescriptionOids(classid, objid),
2743 get_namespace_name(nspOid))));
2745 /* disallow renaming into or out of temp schemas */
2746 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2748 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2749 errmsg("cannot move objects into or out of temporary schemas")));
2751 /* same for TOAST schema */
2752 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2754 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2755 errmsg("cannot move objects into or out of TOAST schema")));
2759 * QualifiedNameGetCreationNamespace
2760 * Given a possibly-qualified name for an object (in List-of-Values
2761 * format), determine what namespace the object should be created in.
2762 * Also extract and return the object name (last component of list).
2764 * Note: this does not apply any permissions check. Callers must check
2765 * for CREATE rights on the selected namespace when appropriate.
2767 * Note: calling this may result in a CommandCounterIncrement operation,
2768 * if we have to create or clean out the temp namespace.
2771 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2776 /* deconstruct the name list */
2777 DeconstructQualifiedName(names, &schemaname, objname_p);
2781 /* check for pg_temp alias */
2782 if (strcmp(schemaname, "pg_temp") == 0)
2784 /* Initialize temp namespace if first time through */
2785 if (!OidIsValid(myTempNamespace))
2786 InitTempTableNamespace();
2787 return myTempNamespace;
2789 /* use exact schema given */
2790 namespaceId = get_namespace_oid(schemaname, false);
2791 /* we do not check for USAGE rights here! */
2795 /* use the default creation namespace */
2796 recomputeNamespacePath();
2797 if (activeTempCreationPending)
2799 /* Need to initialize temp namespace */
2800 InitTempTableNamespace();
2801 return myTempNamespace;
2803 namespaceId = activeCreationNamespace;
2804 if (!OidIsValid(namespaceId))
2806 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2807 errmsg("no schema has been selected to create in")));
2814 * get_namespace_oid - given a namespace name, look up the OID
2816 * If missing_ok is false, throw an error if namespace name not found. If
2817 * true, just return InvalidOid.
2820 get_namespace_oid(const char *nspname, bool missing_ok)
2824 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2825 if (!OidIsValid(oid) && !missing_ok)
2827 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2828 errmsg("schema \"%s\" does not exist", nspname)));
2834 * makeRangeVarFromNameList
2835 * Utility routine to convert a qualified-name list into RangeVar form.
2838 makeRangeVarFromNameList(List *names)
2840 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2842 switch (list_length(names))
2845 rel->relname = strVal(linitial(names));
2848 rel->schemaname = strVal(linitial(names));
2849 rel->relname = strVal(lsecond(names));
2852 rel->catalogname = strVal(linitial(names));
2853 rel->schemaname = strVal(lsecond(names));
2854 rel->relname = strVal(lthird(names));
2858 (errcode(ERRCODE_SYNTAX_ERROR),
2859 errmsg("improper relation name (too many dotted names): %s",
2860 NameListToString(names))));
2869 * Utility routine to convert a qualified-name list into a string.
2871 * This is used primarily to form error messages, and so we do not quote
2872 * the list elements, for the sake of legibility.
2874 * In most scenarios the list elements should always be Value strings,
2875 * but we also allow A_Star for the convenience of ColumnRef processing.
2878 NameListToString(List *names)
2880 StringInfoData string;
2883 initStringInfo(&string);
2887 Node *name = (Node *) lfirst(l);
2889 if (l != list_head(names))
2890 appendStringInfoChar(&string, '.');
2892 if (IsA(name, String))
2893 appendStringInfoString(&string, strVal(name));
2894 else if (IsA(name, A_Star))
2895 appendStringInfoString(&string, "*");
2897 elog(ERROR, "unexpected node type in name list: %d",
2898 (int) nodeTag(name));
2905 * NameListToQuotedString
2906 * Utility routine to convert a qualified-name list into a string.
2908 * Same as above except that names will be double-quoted where necessary,
2909 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2912 NameListToQuotedString(List *names)
2914 StringInfoData string;
2917 initStringInfo(&string);
2921 if (l != list_head(names))
2922 appendStringInfoChar(&string, '.');
2923 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2930 * isTempNamespace - is the given namespace my temporary-table namespace?
2933 isTempNamespace(Oid namespaceId)
2935 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2941 * isTempToastNamespace - is the given namespace my temporary-toast-table
2945 isTempToastNamespace(Oid namespaceId)
2947 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2953 * isTempOrToastNamespace - is the given namespace my temporary-table
2954 * namespace or my temporary-toast-table namespace?
2957 isTempOrToastNamespace(Oid namespaceId)
2959 if (OidIsValid(myTempNamespace) &&
2960 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2966 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2967 * (either my own, or another backend's)? Temporary-toast-table namespaces
2968 * are included, too.
2971 isAnyTempNamespace(Oid namespaceId)
2976 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2977 nspname = get_namespace_name(namespaceId);
2979 return false; /* no such namespace? */
2980 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2981 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2987 * isOtherTempNamespace - is the given namespace some other backend's
2988 * temporary-table namespace (including temporary-toast-table namespaces)?
2990 * Note: for most purposes in the C code, this function is obsolete. Use
2991 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2994 isOtherTempNamespace(Oid namespaceId)
2996 /* If it's my own temp namespace, say "false" */
2997 if (isTempOrToastNamespace(namespaceId))
2999 /* Else, if it's any temp namespace, say "true" */
3000 return isAnyTempNamespace(namespaceId);
3004 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3005 * namespace (either my own, or another backend's), return the BackendId
3006 * that owns it. Temporary-toast-table namespaces are included, too.
3007 * If it isn't a temp namespace, return InvalidBackendId.
3010 GetTempNamespaceBackendId(Oid namespaceId)
3015 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3016 nspname = get_namespace_name(namespaceId);
3018 return InvalidBackendId; /* no such namespace? */
3019 if (strncmp(nspname, "pg_temp_", 8) == 0)
3020 result = atoi(nspname + 8);
3021 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3022 result = atoi(nspname + 14);
3024 result = InvalidBackendId;
3030 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3031 * which must already be assigned. (This is only used when creating a toast
3032 * table for a temp table, so we must have already done InitTempTableNamespace)
3035 GetTempToastNamespace(void)
3037 Assert(OidIsValid(myTempToastNamespace));
3038 return myTempToastNamespace;
3043 * GetOverrideSearchPath - fetch current search path definition in form
3044 * used by PushOverrideSearchPath.
3046 * The result structure is allocated in the specified memory context
3047 * (which might or might not be equal to CurrentMemoryContext); but any
3048 * junk created by revalidation calculations will be in CurrentMemoryContext.
3050 OverrideSearchPath *
3051 GetOverrideSearchPath(MemoryContext context)
3053 OverrideSearchPath *result;
3055 MemoryContext oldcxt;
3057 recomputeNamespacePath();
3059 oldcxt = MemoryContextSwitchTo(context);
3061 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3062 schemas = list_copy(activeSearchPath);
3063 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3065 if (linitial_oid(schemas) == myTempNamespace)
3066 result->addTemp = true;
3069 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3070 result->addCatalog = true;
3072 schemas = list_delete_first(schemas);
3074 result->schemas = schemas;
3076 MemoryContextSwitchTo(oldcxt);
3082 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3084 * The result structure is allocated in CurrentMemoryContext.
3086 OverrideSearchPath *
3087 CopyOverrideSearchPath(OverrideSearchPath *path)
3089 OverrideSearchPath *result;
3091 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3092 result->schemas = list_copy(path->schemas);
3093 result->addCatalog = path->addCatalog;
3094 result->addTemp = path->addTemp;
3100 * PushOverrideSearchPath - temporarily override the search path
3102 * We allow nested overrides, hence the push/pop terminology. The GUC
3103 * search_path variable is ignored while an override is active.
3105 * It's possible that newpath->useTemp is set but there is no longer any
3106 * active temp namespace, if the path was saved during a transaction that
3107 * created a temp namespace and was later rolled back. In that case we just
3108 * ignore useTemp. A plausible alternative would be to create a new temp
3109 * namespace, but for existing callers that's not necessary because an empty
3110 * temp namespace wouldn't affect their results anyway.
3112 * It's also worth noting that other schemas listed in newpath might not
3113 * exist anymore either. We don't worry about this because OIDs that match
3114 * no existing namespace will simply not produce any hits during searches.
3117 PushOverrideSearchPath(OverrideSearchPath *newpath)
3119 OverrideStackEntry *entry;
3122 MemoryContext oldcxt;
3125 * Copy the list for safekeeping, and insert implicitly-searched
3126 * namespaces as needed. This code should track recomputeNamespacePath.
3128 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3130 oidlist = list_copy(newpath->schemas);
3133 * Remember the first member of the explicit list.
3136 firstNS = InvalidOid;
3138 firstNS = linitial_oid(oidlist);
3141 * Add any implicitly-searched namespaces to the list. Note these go on
3142 * the front, not the back; also notice that we do not check USAGE
3143 * permissions for these.
3145 if (newpath->addCatalog)
3146 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3148 if (newpath->addTemp && OidIsValid(myTempNamespace))
3149 oidlist = lcons_oid(myTempNamespace, oidlist);
3152 * Build the new stack entry, then insert it at the head of the list.
3154 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3155 entry->searchPath = oidlist;
3156 entry->creationNamespace = firstNS;
3157 entry->nestLevel = GetCurrentTransactionNestLevel();
3159 overrideStack = lcons(entry, overrideStack);
3161 /* And make it active. */
3162 activeSearchPath = entry->searchPath;
3163 activeCreationNamespace = entry->creationNamespace;
3164 activeTempCreationPending = false; /* XXX is this OK? */
3166 MemoryContextSwitchTo(oldcxt);
3170 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3172 * Any push during a (sub)transaction will be popped automatically at abort.
3173 * But it's caller error if a push isn't popped in normal control flow.
3176 PopOverrideSearchPath(void)
3178 OverrideStackEntry *entry;
3180 /* Sanity checks. */
3181 if (overrideStack == NIL)
3182 elog(ERROR, "bogus PopOverrideSearchPath call");
3183 entry = (OverrideStackEntry *) linitial(overrideStack);
3184 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3185 elog(ERROR, "bogus PopOverrideSearchPath call");
3187 /* Pop the stack and free storage. */
3188 overrideStack = list_delete_first(overrideStack);
3189 list_free(entry->searchPath);
3192 /* Activate the next level down. */
3195 entry = (OverrideStackEntry *) linitial(overrideStack);
3196 activeSearchPath = entry->searchPath;
3197 activeCreationNamespace = entry->creationNamespace;
3198 activeTempCreationPending = false; /* XXX is this OK? */
3202 /* If not baseSearchPathValid, this is useless but harmless */
3203 activeSearchPath = baseSearchPath;
3204 activeCreationNamespace = baseCreationNamespace;
3205 activeTempCreationPending = baseTempCreationPending;
3211 * get_collation_oid - find a collation by possibly qualified name
3214 get_collation_oid(List *name, bool missing_ok)
3217 char *collation_name;
3218 int32 dbencoding = GetDatabaseEncoding();
3223 /* deconstruct the name list */
3224 DeconstructQualifiedName(name, &schemaname, &collation_name);
3228 /* use exact schema given */
3229 namespaceId = LookupExplicitNamespace(schemaname);
3231 /* first try for encoding-specific entry, then any-encoding */
3232 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3233 PointerGetDatum(collation_name),
3234 Int32GetDatum(dbencoding),
3235 ObjectIdGetDatum(namespaceId));
3236 if (OidIsValid(colloid))
3238 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3239 PointerGetDatum(collation_name),
3241 ObjectIdGetDatum(namespaceId));
3242 if (OidIsValid(colloid))
3247 /* search for it in search path */
3248 recomputeNamespacePath();
3250 foreach(l, activeSearchPath)
3252 namespaceId = lfirst_oid(l);
3254 if (namespaceId == myTempNamespace)
3255 continue; /* do not look in temp namespace */
3257 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3258 PointerGetDatum(collation_name),
3259 Int32GetDatum(dbencoding),
3260 ObjectIdGetDatum(namespaceId));
3261 if (OidIsValid(colloid))
3263 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3264 PointerGetDatum(collation_name),
3266 ObjectIdGetDatum(namespaceId));
3267 if (OidIsValid(colloid))
3272 /* Not found in path */
3275 (errcode(ERRCODE_UNDEFINED_OBJECT),
3276 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3277 NameListToString(name), GetDatabaseEncodingName())));
3282 * get_conversion_oid - find a conversion by possibly qualified name
3285 get_conversion_oid(List *name, bool missing_ok)
3288 char *conversion_name;
3290 Oid conoid = InvalidOid;
3293 /* deconstruct the name list */
3294 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3298 /* use exact schema given */
3299 namespaceId = LookupExplicitNamespace(schemaname);
3300 conoid = GetSysCacheOid2(CONNAMENSP,
3301 PointerGetDatum(conversion_name),
3302 ObjectIdGetDatum(namespaceId));
3306 /* search for it in search path */
3307 recomputeNamespacePath();
3309 foreach(l, activeSearchPath)
3311 namespaceId = lfirst_oid(l);
3313 if (namespaceId == myTempNamespace)
3314 continue; /* do not look in temp namespace */
3316 conoid = GetSysCacheOid2(CONNAMENSP,
3317 PointerGetDatum(conversion_name),
3318 ObjectIdGetDatum(namespaceId));
3319 if (OidIsValid(conoid))
3324 /* Not found in path */
3325 if (!OidIsValid(conoid) && !missing_ok)
3327 (errcode(ERRCODE_UNDEFINED_OBJECT),
3328 errmsg("conversion \"%s\" does not exist",
3329 NameListToString(name))));
3334 * FindDefaultConversionProc - find default encoding conversion proc
3337 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3342 recomputeNamespacePath();
3344 foreach(l, activeSearchPath)
3346 Oid namespaceId = lfirst_oid(l);
3348 if (namespaceId == myTempNamespace)
3349 continue; /* do not look in temp namespace */
3351 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3352 if (OidIsValid(proc))
3356 /* Not found in path */
3361 * recomputeNamespacePath - recompute path derived variables if needed.
3364 recomputeNamespacePath(void)
3366 Oid roleid = GetUserId();
3374 MemoryContext oldcxt;
3376 /* Do nothing if an override search spec is active. */
3380 /* Do nothing if path is already valid. */
3381 if (baseSearchPathValid && namespaceUser == roleid)
3384 /* Need a modifiable copy of namespace_search_path string */
3385 rawname = pstrdup(namespace_search_path);
3387 /* Parse string into list of identifiers */
3388 if (!SplitIdentifierString(rawname, ',', &namelist))
3390 /* syntax error in name list */
3391 /* this should not happen if GUC checked check_search_path */
3392 elog(ERROR, "invalid list syntax");
3396 * Convert the list of names to a list of OIDs. If any names are not
3397 * recognizable or we don't have read access, just leave them out of the
3398 * list. (We can't raise an error, since the search_path setting has
3399 * already been accepted.) Don't make duplicate entries, either.
3402 temp_missing = false;
3403 foreach(l, namelist)
3405 char *curname = (char *) lfirst(l);
3408 if (strcmp(curname, "$user") == 0)
3410 /* $user --- substitute namespace matching user name, if any */
3413 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3414 if (HeapTupleIsValid(tuple))
3418 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3419 namespaceId = get_namespace_oid(rname, true);
3420 ReleaseSysCache(tuple);
3421 if (OidIsValid(namespaceId) &&
3422 !list_member_oid(oidlist, namespaceId) &&
3423 pg_namespace_aclcheck(namespaceId, roleid,
3424 ACL_USAGE) == ACLCHECK_OK)
3425 oidlist = lappend_oid(oidlist, namespaceId);
3428 else if (strcmp(curname, "pg_temp") == 0)
3430 /* pg_temp --- substitute temp namespace, if any */
3431 if (OidIsValid(myTempNamespace))
3433 if (!list_member_oid(oidlist, myTempNamespace))
3434 oidlist = lappend_oid(oidlist, myTempNamespace);
3438 /* If it ought to be the creation namespace, set flag */
3440 temp_missing = true;
3445 /* normal namespace reference */
3446 namespaceId = get_namespace_oid(curname, true);
3447 if (OidIsValid(namespaceId) &&
3448 !list_member_oid(oidlist, namespaceId) &&
3449 pg_namespace_aclcheck(namespaceId, roleid,
3450 ACL_USAGE) == ACLCHECK_OK)
3451 oidlist = lappend_oid(oidlist, namespaceId);
3456 * Remember the first member of the explicit list. (Note: this is
3457 * nominally wrong if temp_missing, but we need it anyway to distinguish
3458 * explicit from implicit mention of pg_catalog.)
3461 firstNS = InvalidOid;
3463 firstNS = linitial_oid(oidlist);
3466 * Add any implicitly-searched namespaces to the list. Note these go on
3467 * the front, not the back; also notice that we do not check USAGE
3468 * permissions for these.
3470 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3471 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3473 if (OidIsValid(myTempNamespace) &&
3474 !list_member_oid(oidlist, myTempNamespace))
3475 oidlist = lcons_oid(myTempNamespace, oidlist);
3478 * Now that we've successfully built the new list of namespace OIDs, save
3479 * it in permanent storage.
3481 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3482 newpath = list_copy(oidlist);
3483 MemoryContextSwitchTo(oldcxt);
3485 /* Now safe to assign to state variables. */
3486 list_free(baseSearchPath);
3487 baseSearchPath = newpath;
3488 baseCreationNamespace = firstNS;
3489 baseTempCreationPending = temp_missing;
3491 /* Mark the path valid. */
3492 baseSearchPathValid = true;
3493 namespaceUser = roleid;
3495 /* And make it active. */
3496 activeSearchPath = baseSearchPath;
3497 activeCreationNamespace = baseCreationNamespace;
3498 activeTempCreationPending = baseTempCreationPending;
3502 list_free(namelist);
3507 * InitTempTableNamespace
3508 * Initialize temp table namespace on first use in a particular backend
3511 InitTempTableNamespace(void)
3513 char namespaceName[NAMEDATALEN];
3517 Assert(!OidIsValid(myTempNamespace));
3520 * First, do permission check to see if we are authorized to make temp
3521 * tables. We use a nonstandard error message here since "databasename:
3522 * permission denied" might be a tad cryptic.
3524 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3525 * that's necessary since current user ID could change during the session.
3526 * But there's no need to make the namespace in the first place until a
3527 * temp table creation request is made by someone with appropriate rights.
3529 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3530 ACL_CREATE_TEMP) != ACLCHECK_OK)
3532 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3533 errmsg("permission denied to create temporary tables in database \"%s\"",
3534 get_database_name(MyDatabaseId))));
3537 * Do not allow a Hot Standby slave session to make temp tables. Aside
3538 * from problems with modifying the system catalogs, there is a naming
3539 * conflict: pg_temp_N belongs to the session with BackendId N on the
3540 * master, not to a slave session with the same BackendId. We should not
3541 * be able to get here anyway due to XactReadOnly checks, but let's just
3542 * make real sure. Note that this also backstops various operations that
3543 * allow XactReadOnly transactions to modify temp tables; they'd need
3544 * RecoveryInProgress checks if not for this.
3546 if (RecoveryInProgress())
3548 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3549 errmsg("cannot create temporary tables during recovery")));
3551 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3553 namespaceId = get_namespace_oid(namespaceName, true);
3554 if (!OidIsValid(namespaceId))
3557 * First use of this temp namespace in this database; create it. The
3558 * temp namespaces are always owned by the superuser. We leave their
3559 * permissions at default --- i.e., no access except to superuser ---
3560 * to ensure that unprivileged users can't peek at other backends'
3561 * temp tables. This works because the places that access the temp
3562 * namespace for my own backend skip permissions checks on it.
3564 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3566 /* Advance command counter to make namespace visible */
3567 CommandCounterIncrement();
3572 * If the namespace already exists, clean it out (in case the former
3573 * owner crashed without doing so).
3575 RemoveTempRelations(namespaceId);
3579 * If the corresponding toast-table namespace doesn't exist yet, create
3580 * it. (We assume there is no need to clean it out if it does exist, since
3581 * dropping a parent table should make its toast table go away.)
3583 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3586 toastspaceId = get_namespace_oid(namespaceName, true);
3587 if (!OidIsValid(toastspaceId))
3589 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3591 /* Advance command counter to make namespace visible */
3592 CommandCounterIncrement();
3596 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3597 * so all our work could be undone by transaction rollback. Set flag for
3598 * AtEOXact_Namespace to know what to do.
3600 myTempNamespace = namespaceId;
3601 myTempToastNamespace = toastspaceId;
3603 /* It should not be done already. */
3604 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3605 myTempNamespaceSubID = GetCurrentSubTransactionId();
3607 baseSearchPathValid = false; /* need to rebuild list */
3611 * End-of-transaction cleanup for namespaces.
3614 AtEOXact_Namespace(bool isCommit)
3617 * If we abort the transaction in which a temp namespace was selected,
3618 * we'll have to do any creation or cleanout work over again. So, just
3619 * forget the namespace entirely until next time. On the other hand, if
3620 * we commit then register an exit callback to clean out the temp tables
3621 * at backend shutdown. (We only want to register the callback once per
3622 * session, so this is a good place to do it.)
3624 if (myTempNamespaceSubID != InvalidSubTransactionId)
3627 on_shmem_exit(RemoveTempRelationsCallback, 0);
3630 myTempNamespace = InvalidOid;
3631 myTempToastNamespace = InvalidOid;
3632 baseSearchPathValid = false; /* need to rebuild list */
3634 myTempNamespaceSubID = InvalidSubTransactionId;
3638 * Clean up if someone failed to do PopOverrideSearchPath
3643 elog(WARNING, "leaked override search path");
3644 while (overrideStack)
3646 OverrideStackEntry *entry;
3648 entry = (OverrideStackEntry *) linitial(overrideStack);
3649 overrideStack = list_delete_first(overrideStack);
3650 list_free(entry->searchPath);
3653 /* If not baseSearchPathValid, this is useless but harmless */
3654 activeSearchPath = baseSearchPath;
3655 activeCreationNamespace = baseCreationNamespace;
3656 activeTempCreationPending = baseTempCreationPending;
3661 * AtEOSubXact_Namespace
3663 * At subtransaction commit, propagate the temp-namespace-creation
3664 * flag to the parent subtransaction.
3666 * At subtransaction abort, forget the flag if we set it up.
3669 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3670 SubTransactionId parentSubid)
3672 OverrideStackEntry *entry;
3674 if (myTempNamespaceSubID == mySubid)
3677 myTempNamespaceSubID = parentSubid;
3680 myTempNamespaceSubID = InvalidSubTransactionId;
3681 /* TEMP namespace creation failed, so reset state */
3682 myTempNamespace = InvalidOid;
3683 myTempToastNamespace = InvalidOid;
3684 baseSearchPathValid = false; /* need to rebuild list */
3689 * Clean up if someone failed to do PopOverrideSearchPath
3691 while (overrideStack)
3693 entry = (OverrideStackEntry *) linitial(overrideStack);
3694 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3697 elog(WARNING, "leaked override search path");
3698 overrideStack = list_delete_first(overrideStack);
3699 list_free(entry->searchPath);
3703 /* Activate the next level down. */
3706 entry = (OverrideStackEntry *) linitial(overrideStack);
3707 activeSearchPath = entry->searchPath;
3708 activeCreationNamespace = entry->creationNamespace;
3709 activeTempCreationPending = false; /* XXX is this OK? */
3713 /* If not baseSearchPathValid, this is useless but harmless */
3714 activeSearchPath = baseSearchPath;
3715 activeCreationNamespace = baseCreationNamespace;
3716 activeTempCreationPending = baseTempCreationPending;
3721 * Remove all relations in the specified temp namespace.
3723 * This is called at backend shutdown (if we made any temp relations).
3724 * It is also called when we begin using a pre-existing temp namespace,
3725 * in order to clean out any relations that might have been created by
3726 * a crashed backend.
3729 RemoveTempRelations(Oid tempNamespaceId)
3731 ObjectAddress object;
3734 * We want to get rid of everything in the target namespace, but not the
3735 * namespace itself (deleting it only to recreate it later would be a
3736 * waste of cycles). We do this by finding everything that has a
3737 * dependency on the namespace.
3739 object.classId = NamespaceRelationId;
3740 object.objectId = tempNamespaceId;
3741 object.objectSubId = 0;
3743 deleteWhatDependsOn(&object, false);
3747 * Callback to remove temp relations at backend exit.
3750 RemoveTempRelationsCallback(int code, Datum arg)
3752 if (OidIsValid(myTempNamespace)) /* should always be true */
3754 /* Need to ensure we have a usable transaction. */
3755 AbortOutOfAnyTransaction();
3756 StartTransactionCommand();
3758 RemoveTempRelations(myTempNamespace);
3760 CommitTransactionCommand();
3765 * Remove all temp tables from the temporary namespace.
3768 ResetTempTableNamespace(void)
3770 if (OidIsValid(myTempNamespace))
3771 RemoveTempRelations(myTempNamespace);
3776 * Routines for handling the GUC variable 'search_path'.
3779 /* check_hook: validate new search_path value */
3781 check_search_path(char **newval, void **extra, GucSource source)
3786 /* Need a modifiable copy of string */
3787 rawname = pstrdup(*newval);
3789 /* Parse string into list of identifiers */
3790 if (!SplitIdentifierString(rawname, ',', &namelist))
3792 /* syntax error in name list */
3793 GUC_check_errdetail("List syntax is invalid.");
3795 list_free(namelist);
3800 * We used to try to check that the named schemas exist, but there are
3801 * many valid use-cases for having search_path settings that include
3802 * schemas that don't exist; and often, we are not inside a transaction
3803 * here and so can't consult the system catalogs anyway. So now, the only
3804 * requirement is syntactic validity of the identifier list.
3808 list_free(namelist);
3813 /* assign_hook: do extra actions as needed */
3815 assign_search_path(const char *newval, void *extra)
3818 * We mark the path as needing recomputation, but don't do anything until
3819 * it's needed. This avoids trying to do database access during GUC
3820 * initialization, or outside a transaction.
3822 baseSearchPathValid = false;
3826 * InitializeSearchPath: initialize module during InitPostgres.
3828 * This is called after we are up enough to be able to do catalog lookups.
3831 InitializeSearchPath(void)
3833 if (IsBootstrapProcessingMode())
3836 * In bootstrap mode, the search path must be 'pg_catalog' so that
3837 * tables are created in the proper namespace; ignore the GUC setting.
3839 MemoryContext oldcxt;
3841 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3842 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3843 MemoryContextSwitchTo(oldcxt);
3844 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3845 baseTempCreationPending = false;
3846 baseSearchPathValid = true;
3847 namespaceUser = GetUserId();
3848 activeSearchPath = baseSearchPath;
3849 activeCreationNamespace = baseCreationNamespace;
3850 activeTempCreationPending = baseTempCreationPending;
3855 * In normal mode, arrange for a callback on any syscache invalidation
3856 * of pg_namespace rows.
3858 CacheRegisterSyscacheCallback(NAMESPACEOID,
3861 /* Force search path to be recomputed on next use */
3862 baseSearchPathValid = false;
3868 * Syscache inval callback function
3871 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3873 /* Force search path to be recomputed on next use */
3874 baseSearchPathValid = false;
3878 * Fetch the active search path. The return value is a palloc'ed list
3879 * of OIDs; the caller is responsible for freeing this storage as
3882 * The returned list includes the implicitly-prepended namespaces only if
3883 * includeImplicit is true.
3885 * Note: calling this may result in a CommandCounterIncrement operation,
3886 * if we have to create or clean out the temp namespace.
3889 fetch_search_path(bool includeImplicit)
3893 recomputeNamespacePath();
3896 * If the temp namespace should be first, force it to exist. This is so
3897 * that callers can trust the result to reflect the actual default
3898 * creation namespace. It's a bit bogus to do this here, since
3899 * current_schema() is supposedly a stable function without side-effects,
3900 * but the alternatives seem worse.
3902 if (activeTempCreationPending)
3904 InitTempTableNamespace();
3905 recomputeNamespacePath();
3908 result = list_copy(activeSearchPath);
3909 if (!includeImplicit)
3911 while (result && linitial_oid(result) != activeCreationNamespace)
3912 result = list_delete_first(result);
3919 * Fetch the active search path into a caller-allocated array of OIDs.
3920 * Returns the number of path entries. (If this is more than sarray_len,
3921 * then the data didn't fit and is not all stored.)
3923 * The returned list always includes the implicitly-prepended namespaces,
3924 * but never includes the temp namespace. (This is suitable for existing
3925 * users, which would want to ignore the temp namespace anyway.) This
3926 * definition allows us to not worry about initializing the temp namespace.
3929 fetch_search_path_array(Oid *sarray, int sarray_len)
3934 recomputeNamespacePath();
3936 foreach(l, activeSearchPath)
3938 Oid namespaceId = lfirst_oid(l);
3940 if (namespaceId == myTempNamespace)
3941 continue; /* do not include temp namespace */
3943 if (count < sarray_len)
3944 sarray[count] = namespaceId;
3953 * Export the FooIsVisible functions as SQL-callable functions.
3955 * Note: as of Postgres 8.4, these will silently return NULL if called on
3956 * a nonexistent object OID, rather than failing. This is to avoid race
3957 * condition errors when a query that's scanning a catalog using an MVCC
3958 * snapshot uses one of these functions. The underlying IsVisible functions
3959 * operate on SnapshotNow semantics and so might see the object as already
3960 * gone when it's still visible to the MVCC snapshot. (There is no race
3961 * condition in the current coding because we don't accept sinval messages
3962 * between the SearchSysCacheExists test and the subsequent lookup.)
3966 pg_table_is_visible(PG_FUNCTION_ARGS)
3968 Oid oid = PG_GETARG_OID(0);
3970 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3973 PG_RETURN_BOOL(RelationIsVisible(oid));
3977 pg_type_is_visible(PG_FUNCTION_ARGS)
3979 Oid oid = PG_GETARG_OID(0);
3981 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3984 PG_RETURN_BOOL(TypeIsVisible(oid));
3988 pg_function_is_visible(PG_FUNCTION_ARGS)
3990 Oid oid = PG_GETARG_OID(0);
3992 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3995 PG_RETURN_BOOL(FunctionIsVisible(oid));
3999 pg_operator_is_visible(PG_FUNCTION_ARGS)
4001 Oid oid = PG_GETARG_OID(0);
4003 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4006 PG_RETURN_BOOL(OperatorIsVisible(oid));
4010 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4012 Oid oid = PG_GETARG_OID(0);
4014 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4017 PG_RETURN_BOOL(OpclassIsVisible(oid));
4021 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4023 Oid oid = PG_GETARG_OID(0);
4025 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4028 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4032 pg_collation_is_visible(PG_FUNCTION_ARGS)
4034 Oid oid = PG_GETARG_OID(0);
4036 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4039 PG_RETURN_BOOL(CollationIsVisible(oid));
4043 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4045 Oid oid = PG_GETARG_OID(0);
4047 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4050 PG_RETURN_BOOL(ConversionIsVisible(oid));
4054 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4056 Oid oid = PG_GETARG_OID(0);
4058 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4061 PG_RETURN_BOOL(TSParserIsVisible(oid));
4065 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4067 Oid oid = PG_GETARG_OID(0);
4069 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4072 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4076 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4078 Oid oid = PG_GETARG_OID(0);
4080 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4083 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4087 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4089 Oid oid = PG_GETARG_OID(0);
4091 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4094 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4098 pg_my_temp_schema(PG_FUNCTION_ARGS)
4100 PG_RETURN_OID(myTempNamespace);
4104 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4106 Oid oid = PG_GETARG_OID(0);
4108 PG_RETURN_BOOL(isOtherTempNamespace(oid));