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-2005, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
16 * $PostgreSQL: pgsql/src/backend/catalog/namespace.c,v 1.80 2005/11/22 18:17:08 momjian Exp $
18 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/dependency.h"
24 #include "catalog/namespace.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_conversion.h"
27 #include "catalog/pg_namespace.h"
28 #include "catalog/pg_opclass.h"
29 #include "catalog/pg_operator.h"
30 #include "catalog/pg_proc.h"
31 #include "catalog/pg_type.h"
32 #include "commands/dbcommands.h"
33 #include "lib/stringinfo.h"
34 #include "miscadmin.h"
35 #include "nodes/makefuncs.h"
36 #include "storage/backendid.h"
37 #include "storage/ipc.h"
38 #include "utils/acl.h"
39 #include "utils/builtins.h"
40 #include "utils/catcache.h"
41 #include "utils/guc.h"
42 #include "utils/inval.h"
43 #include "utils/lsyscache.h"
44 #include "utils/memutils.h"
45 #include "utils/syscache.h"
49 * The namespace search path is a possibly-empty list of namespace OIDs.
50 * In addition to the explicit list, several implicitly-searched namespaces
53 * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
54 * always searched first. (This is a hack for CREATE SCHEMA.)
56 * 2. If a TEMP table namespace has been initialized in this session, it
57 * is always searched just after any special namespace.
59 * 3. The system catalog namespace is always searched. If the system
60 * namespace is present in the explicit path then it will be searched in
61 * the specified order; otherwise it will be searched after TEMP tables and
62 * *before* the explicit list. (It might seem that the system namespace
63 * should be implicitly last, but this behavior appears to be required by
64 * SQL99. Also, this provides a way to search the system namespace first
65 * without thereby making it the default creation target namespace.)
67 * The default creation target namespace is normally equal to the first
68 * element of the explicit list, but is the "special" namespace when one
69 * has been set. If the explicit list is empty and there is no special
70 * namespace, there is no default target.
72 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
73 * the system namespace is the only one searched or inserted into.
74 * The initdb script is also careful to set search_path to 'pg_catalog' for
75 * its post-bootstrap standalone backend runs. Otherwise the default search
76 * path is determined by GUC. The factory default path contains the PUBLIC
77 * namespace (if it exists), preceded by the user's personal namespace
80 * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
81 * derived variables) need to be recomputed from namespace_search_path.
82 * We mark it invalid upon an assignment to namespace_search_path or receipt
83 * of a syscache invalidation event for pg_namespace. The recomputation
84 * is done during the next lookup attempt.
86 * Any namespaces mentioned in namespace_search_path that are not readable
87 * by the current user ID are simply left out of namespaceSearchPath; so
88 * we have to be willing to recompute the path when current userid changes.
89 * namespaceUser is the userid the path has been computed for.
92 static List *namespaceSearchPath = NIL;
94 static Oid namespaceUser = InvalidOid;
96 /* default place to create stuff; if InvalidOid, no default */
97 static Oid defaultCreationNamespace = InvalidOid;
99 /* first explicit member of list; usually same as defaultCreationNamespace */
100 static Oid firstExplicitNamespace = InvalidOid;
102 /* The above four values are valid only if namespaceSearchPathValid */
103 static bool namespaceSearchPathValid = true;
106 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
107 * in a particular backend session (this happens when a CREATE TEMP TABLE
108 * command is first executed). Thereafter it's the OID of the temp namespace.
110 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
111 * current subtransaction. The flag propagates up the subtransaction tree,
112 * so the main transaction will correctly recognize the flag if all
113 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
114 * we either haven't made the TEMP namespace yet, or have successfully
115 * committed its creation, depending on whether myTempNamespace is valid.
117 static Oid myTempNamespace = InvalidOid;
119 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
122 * "Special" namespace for CREATE SCHEMA. If set, it's the first search
123 * path element, and also the default creation namespace.
125 static Oid mySpecialNamespace = InvalidOid;
128 * This is the text equivalent of the search path --- it's the value
129 * of the GUC variable 'search_path'.
131 char *namespace_search_path = NULL;
134 /* Local functions */
135 static void recomputeNamespacePath(void);
136 static void InitTempTableNamespace(void);
137 static void RemoveTempRelations(Oid tempNamespaceId);
138 static void RemoveTempRelationsCallback(int code, Datum arg);
139 static void NamespaceCallback(Datum arg, Oid relid);
141 /* These don't really need to appear in any header file */
142 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
143 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
144 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
145 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
146 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
147 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
152 * Given a RangeVar describing an existing relation,
153 * select the proper namespace and look up the relation OID.
155 * If the relation is not found, return InvalidOid if failOK = true,
156 * otherwise raise an error.
159 RangeVarGetRelid(const RangeVar *relation, bool failOK)
165 * We check the catalog name and then ignore it.
167 if (relation->catalogname)
169 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
171 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
172 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
173 relation->catalogname, relation->schemaname,
174 relation->relname)));
177 if (relation->schemaname)
179 /* use exact schema given */
180 namespaceId = LookupExplicitNamespace(relation->schemaname);
181 relId = get_relname_relid(relation->relname, namespaceId);
185 /* search the namespace path */
186 relId = RelnameGetRelid(relation->relname);
189 if (!OidIsValid(relId) && !failOK)
191 if (relation->schemaname)
193 (errcode(ERRCODE_UNDEFINED_TABLE),
194 errmsg("relation \"%s.%s\" does not exist",
195 relation->schemaname, relation->relname)));
198 (errcode(ERRCODE_UNDEFINED_TABLE),
199 errmsg("relation \"%s\" does not exist",
200 relation->relname)));
206 * RangeVarGetCreationNamespace
207 * Given a RangeVar describing a to-be-created relation,
208 * choose which namespace to create it in.
210 * Note: calling this may result in a CommandCounterIncrement operation.
211 * That will happen on the first request for a temp table in any particular
212 * backend run; we will need to either create or clean out the temp schema.
215 RangeVarGetCreationNamespace(const RangeVar *newRelation)
220 * We check the catalog name and then ignore it.
222 if (newRelation->catalogname)
224 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
226 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
227 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
228 newRelation->catalogname, newRelation->schemaname,
229 newRelation->relname)));
232 if (newRelation->istemp)
234 /* TEMP tables are created in our backend-local temp namespace */
235 if (newRelation->schemaname)
237 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
238 errmsg("temporary tables may not specify a schema name")));
239 /* Initialize temp namespace if first time through */
240 if (!OidIsValid(myTempNamespace))
241 InitTempTableNamespace();
242 return myTempNamespace;
245 if (newRelation->schemaname)
247 /* use exact schema given */
248 namespaceId = GetSysCacheOid(NAMESPACENAME,
249 CStringGetDatum(newRelation->schemaname),
251 if (!OidIsValid(namespaceId))
253 (errcode(ERRCODE_UNDEFINED_SCHEMA),
254 errmsg("schema \"%s\" does not exist",
255 newRelation->schemaname)));
256 /* we do not check for USAGE rights here! */
260 /* use the default creation namespace */
261 recomputeNamespacePath();
262 namespaceId = defaultCreationNamespace;
263 if (!OidIsValid(namespaceId))
265 (errcode(ERRCODE_UNDEFINED_SCHEMA),
266 errmsg("no schema has been selected to create in")));
269 /* Note: callers will check for CREATE rights when appropriate */
276 * Try to resolve an unqualified relation name.
277 * Returns OID if relation found in search path, else InvalidOid.
280 RelnameGetRelid(const char *relname)
285 recomputeNamespacePath();
287 foreach(l, namespaceSearchPath)
289 Oid namespaceId = lfirst_oid(l);
291 relid = get_relname_relid(relname, namespaceId);
292 if (OidIsValid(relid))
296 /* Not found in path */
303 * Determine whether a relation (identified by OID) is visible in the
304 * current search path. Visible means "would be found by searching
305 * for the unqualified relation name".
308 RelationIsVisible(Oid relid)
311 Form_pg_class relform;
315 reltup = SearchSysCache(RELOID,
316 ObjectIdGetDatum(relid),
318 if (!HeapTupleIsValid(reltup))
319 elog(ERROR, "cache lookup failed for relation %u", relid);
320 relform = (Form_pg_class) GETSTRUCT(reltup);
322 recomputeNamespacePath();
325 * Quick check: if it ain't in the path at all, it ain't visible. Items in
326 * the system namespace are surely in the path and so we needn't even do
327 * list_member_oid() for them.
329 relnamespace = relform->relnamespace;
330 if (relnamespace != PG_CATALOG_NAMESPACE &&
331 !list_member_oid(namespaceSearchPath, relnamespace))
336 * If it is in the path, it might still not be visible; it could be
337 * hidden by another relation of the same name earlier in the path. So
338 * we must do a slow check for conflicting relations.
340 char *relname = NameStr(relform->relname);
344 foreach(l, namespaceSearchPath)
346 Oid namespaceId = lfirst_oid(l);
348 if (namespaceId == relnamespace)
350 /* Found it first in path */
354 if (OidIsValid(get_relname_relid(relname, namespaceId)))
356 /* Found something else first in path */
362 ReleaseSysCache(reltup);
370 * Try to resolve an unqualified datatype name.
371 * Returns OID if type found in search path, else InvalidOid.
373 * This is essentially the same as RelnameGetRelid.
376 TypenameGetTypid(const char *typname)
381 recomputeNamespacePath();
383 foreach(l, namespaceSearchPath)
385 Oid namespaceId = lfirst_oid(l);
387 typid = GetSysCacheOid(TYPENAMENSP,
388 PointerGetDatum(typname),
389 ObjectIdGetDatum(namespaceId),
391 if (OidIsValid(typid))
395 /* Not found in path */
401 * Determine whether a type (identified by OID) is visible in the
402 * current search path. Visible means "would be found by searching
403 * for the unqualified type name".
406 TypeIsVisible(Oid typid)
409 Form_pg_type typform;
413 typtup = SearchSysCache(TYPEOID,
414 ObjectIdGetDatum(typid),
416 if (!HeapTupleIsValid(typtup))
417 elog(ERROR, "cache lookup failed for type %u", typid);
418 typform = (Form_pg_type) GETSTRUCT(typtup);
420 recomputeNamespacePath();
423 * Quick check: if it ain't in the path at all, it ain't visible. Items in
424 * the system namespace are surely in the path and so we needn't even do
425 * list_member_oid() for them.
427 typnamespace = typform->typnamespace;
428 if (typnamespace != PG_CATALOG_NAMESPACE &&
429 !list_member_oid(namespaceSearchPath, typnamespace))
434 * If it is in the path, it might still not be visible; it could be
435 * hidden by another type of the same name earlier in the path. So we
436 * must do a slow check for conflicting types.
438 char *typname = NameStr(typform->typname);
442 foreach(l, namespaceSearchPath)
444 Oid namespaceId = lfirst_oid(l);
446 if (namespaceId == typnamespace)
448 /* Found it first in path */
452 if (SearchSysCacheExists(TYPENAMENSP,
453 PointerGetDatum(typname),
454 ObjectIdGetDatum(namespaceId),
457 /* Found something else first in path */
463 ReleaseSysCache(typtup);
470 * FuncnameGetCandidates
471 * Given a possibly-qualified function name and argument count,
472 * retrieve a list of the possible matches.
474 * If nargs is -1, we return all functions matching the given name,
475 * regardless of argument count.
477 * We search a single namespace if the function name is qualified, else
478 * all namespaces in the search path. The return list will never contain
479 * multiple entries with identical argument lists --- in the multiple-
480 * namespace case, we arrange for entries in earlier namespaces to mask
481 * identical entries in later namespaces.
484 FuncnameGetCandidates(List *names, int nargs)
486 FuncCandidateList resultList = NULL;
493 /* deconstruct the name list */
494 DeconstructQualifiedName(names, &schemaname, &funcname);
498 /* use exact schema given */
499 namespaceId = LookupExplicitNamespace(schemaname);
503 /* flag to indicate we need namespace search */
504 namespaceId = InvalidOid;
505 recomputeNamespacePath();
508 /* Search syscache by name only */
509 catlist = SearchSysCacheList(PROCNAMEARGSNSP, 1,
510 CStringGetDatum(funcname),
513 for (i = 0; i < catlist->n_members; i++)
515 HeapTuple proctup = &catlist->members[i]->tuple;
516 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
517 int pronargs = procform->pronargs;
519 FuncCandidateList newResult;
521 /* Ignore if it doesn't match requested argument count */
522 if (nargs >= 0 && pronargs != nargs)
525 if (OidIsValid(namespaceId))
527 /* Consider only procs in specified namespace */
528 if (procform->pronamespace != namespaceId)
530 /* No need to check args, they must all be different */
534 /* Consider only procs that are in the search path */
537 foreach(nsp, namespaceSearchPath)
539 if (procform->pronamespace == lfirst_oid(nsp))
544 continue; /* proc is not in search path */
547 * Okay, it's in the search path, but does it have the same
548 * arguments as something we already accepted? If so, keep only
549 * the one that appears earlier in the search path.
551 * If we have an ordered list from SearchSysCacheList (the normal
552 * case), then any conflicting proc must immediately adjoin this
553 * one in the list, so we only need to look at the newest result
554 * item. If we have an unordered list, we have to scan the whole
559 FuncCandidateList prevResult;
561 if (catlist->ordered)
563 if (pronargs == resultList->nargs &&
564 memcmp(procform->proargtypes.values,
566 pronargs * sizeof(Oid)) == 0)
567 prevResult = resultList;
573 for (prevResult = resultList;
575 prevResult = prevResult->next)
577 if (pronargs == prevResult->nargs &&
578 memcmp(procform->proargtypes.values,
580 pronargs * sizeof(Oid)) == 0)
586 /* We have a match with a previous result */
587 Assert(pathpos != prevResult->pathpos);
588 if (pathpos > prevResult->pathpos)
589 continue; /* keep previous result */
590 /* replace previous result */
591 prevResult->pathpos = pathpos;
592 prevResult->oid = HeapTupleGetOid(proctup);
593 continue; /* args are same, of course */
599 * Okay to add it to result list
601 newResult = (FuncCandidateList)
602 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
603 + pronargs * sizeof(Oid));
604 newResult->pathpos = pathpos;
605 newResult->oid = HeapTupleGetOid(proctup);
606 newResult->nargs = pronargs;
607 memcpy(newResult->args, procform->proargtypes.values,
608 pronargs * sizeof(Oid));
610 newResult->next = resultList;
611 resultList = newResult;
614 ReleaseSysCacheList(catlist);
621 * Determine whether a function (identified by OID) is visible in the
622 * current search path. Visible means "would be found by searching
623 * for the unqualified function name with exact argument matches".
626 FunctionIsVisible(Oid funcid)
629 Form_pg_proc procform;
633 proctup = SearchSysCache(PROCOID,
634 ObjectIdGetDatum(funcid),
636 if (!HeapTupleIsValid(proctup))
637 elog(ERROR, "cache lookup failed for function %u", funcid);
638 procform = (Form_pg_proc) GETSTRUCT(proctup);
640 recomputeNamespacePath();
643 * Quick check: if it ain't in the path at all, it ain't visible. Items in
644 * the system namespace are surely in the path and so we needn't even do
645 * list_member_oid() for them.
647 pronamespace = procform->pronamespace;
648 if (pronamespace != PG_CATALOG_NAMESPACE &&
649 !list_member_oid(namespaceSearchPath, pronamespace))
654 * If it is in the path, it might still not be visible; it could be
655 * hidden by another proc of the same name and arguments earlier in
656 * the path. So we must do a slow check to see if this is the same
657 * proc that would be found by FuncnameGetCandidates.
659 char *proname = NameStr(procform->proname);
660 int nargs = procform->pronargs;
661 FuncCandidateList clist;
665 clist = FuncnameGetCandidates(list_make1(makeString(proname)), nargs);
667 for (; clist; clist = clist->next)
669 if (memcmp(clist->args, procform->proargtypes.values,
670 nargs * sizeof(Oid)) == 0)
672 /* Found the expected entry; is it the right proc? */
673 visible = (clist->oid == funcid);
679 ReleaseSysCache(proctup);
686 * OpernameGetCandidates
687 * Given a possibly-qualified operator name and operator kind,
688 * retrieve a list of the possible matches.
690 * If oprkind is '\0', we return all operators matching the given name,
691 * regardless of arguments.
693 * We search a single namespace if the operator name is qualified, else
694 * all namespaces in the search path. The return list will never contain
695 * multiple entries with identical argument lists --- in the multiple-
696 * namespace case, we arrange for entries in earlier namespaces to mask
697 * identical entries in later namespaces.
699 * The returned items always have two args[] entries --- one or the other
700 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
703 OpernameGetCandidates(List *names, char oprkind)
705 FuncCandidateList resultList = NULL;
706 char *resultSpace = NULL;
714 /* deconstruct the name list */
715 DeconstructQualifiedName(names, &schemaname, &opername);
719 /* use exact schema given */
720 namespaceId = LookupExplicitNamespace(schemaname);
724 /* flag to indicate we need namespace search */
725 namespaceId = InvalidOid;
726 recomputeNamespacePath();
729 /* Search syscache by name only */
730 catlist = SearchSysCacheList(OPERNAMENSP, 1,
731 CStringGetDatum(opername),
735 * In typical scenarios, most if not all of the operators found by the
736 * catcache search will end up getting returned; and there can be quite a
737 * few, for common operator names such as '=' or '+'. To reduce the time
738 * spent in palloc, we allocate the result space as an array large enough
739 * to hold all the operators. The original coding of this routine did a
740 * separate palloc for each operator, but profiling revealed that the
741 * pallocs used an unreasonably large fraction of parsing time.
743 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
745 if (catlist->n_members > 0)
746 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
748 for (i = 0; i < catlist->n_members; i++)
750 HeapTuple opertup = &catlist->members[i]->tuple;
751 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
753 FuncCandidateList newResult;
755 /* Ignore operators of wrong kind, if specific kind requested */
756 if (oprkind && operform->oprkind != oprkind)
759 if (OidIsValid(namespaceId))
761 /* Consider only opers in specified namespace */
762 if (operform->oprnamespace != namespaceId)
764 /* No need to check args, they must all be different */
768 /* Consider only opers that are in the search path */
771 foreach(nsp, namespaceSearchPath)
773 if (operform->oprnamespace == lfirst_oid(nsp))
778 continue; /* oper is not in search path */
781 * Okay, it's in the search path, but does it have the same
782 * arguments as something we already accepted? If so, keep only
783 * the one that appears earlier in the search path.
785 * If we have an ordered list from SearchSysCacheList (the normal
786 * case), then any conflicting oper must immediately adjoin this
787 * one in the list, so we only need to look at the newest result
788 * item. If we have an unordered list, we have to scan the whole
793 FuncCandidateList prevResult;
795 if (catlist->ordered)
797 if (operform->oprleft == resultList->args[0] &&
798 operform->oprright == resultList->args[1])
799 prevResult = resultList;
805 for (prevResult = resultList;
807 prevResult = prevResult->next)
809 if (operform->oprleft == prevResult->args[0] &&
810 operform->oprright == prevResult->args[1])
816 /* We have a match with a previous result */
817 Assert(pathpos != prevResult->pathpos);
818 if (pathpos > prevResult->pathpos)
819 continue; /* keep previous result */
820 /* replace previous result */
821 prevResult->pathpos = pathpos;
822 prevResult->oid = HeapTupleGetOid(opertup);
823 continue; /* args are same, of course */
829 * Okay to add it to result list
831 newResult = (FuncCandidateList) (resultSpace + nextResult);
832 nextResult += SPACE_PER_OP;
834 newResult->pathpos = pathpos;
835 newResult->oid = HeapTupleGetOid(opertup);
836 newResult->nargs = 2;
837 newResult->args[0] = operform->oprleft;
838 newResult->args[1] = operform->oprright;
839 newResult->next = resultList;
840 resultList = newResult;
843 ReleaseSysCacheList(catlist);
850 * Determine whether an operator (identified by OID) is visible in the
851 * current search path. Visible means "would be found by searching
852 * for the unqualified operator name with exact argument matches".
855 OperatorIsVisible(Oid oprid)
858 Form_pg_operator oprform;
862 oprtup = SearchSysCache(OPEROID,
863 ObjectIdGetDatum(oprid),
865 if (!HeapTupleIsValid(oprtup))
866 elog(ERROR, "cache lookup failed for operator %u", oprid);
867 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
869 recomputeNamespacePath();
872 * Quick check: if it ain't in the path at all, it ain't visible. Items in
873 * the system namespace are surely in the path and so we needn't even do
874 * list_member_oid() for them.
876 oprnamespace = oprform->oprnamespace;
877 if (oprnamespace != PG_CATALOG_NAMESPACE &&
878 !list_member_oid(namespaceSearchPath, oprnamespace))
883 * If it is in the path, it might still not be visible; it could be
884 * hidden by another operator of the same name and arguments earlier
885 * in the path. So we must do a slow check to see if this is the same
886 * operator that would be found by OpernameGetCandidates.
888 char *oprname = NameStr(oprform->oprname);
889 FuncCandidateList clist;
893 clist = OpernameGetCandidates(list_make1(makeString(oprname)),
896 for (; clist; clist = clist->next)
898 if (clist->args[0] == oprform->oprleft &&
899 clist->args[1] == oprform->oprright)
901 /* Found the expected entry; is it the right op? */
902 visible = (clist->oid == oprid);
908 ReleaseSysCache(oprtup);
915 * OpclassGetCandidates
916 * Given an index access method OID, retrieve a list of all the
917 * opclasses for that AM that are visible in the search path.
919 * NOTE: the opcname_tmp field in the returned structs should not be used
920 * by callers, because it points at syscache entries that we release at
921 * the end of this routine. If any callers needed the name information,
922 * we could pstrdup() the names ... but at present it'd be wasteful.
925 OpclassGetCandidates(Oid amid)
927 OpclassCandidateList resultList = NULL;
931 /* Search syscache by AM OID only */
932 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
933 ObjectIdGetDatum(amid),
936 recomputeNamespacePath();
938 for (i = 0; i < catlist->n_members; i++)
940 HeapTuple opctup = &catlist->members[i]->tuple;
941 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
943 OpclassCandidateList newResult;
946 /* Consider only opclasses that are in the search path */
947 foreach(nsp, namespaceSearchPath)
949 if (opcform->opcnamespace == lfirst_oid(nsp))
954 continue; /* opclass is not in search path */
957 * Okay, it's in the search path, but does it have the same name as
958 * something we already accepted? If so, keep only the one that
959 * appears earlier in the search path.
961 * If we have an ordered list from SearchSysCacheList (the normal
962 * case), then any conflicting opclass must immediately adjoin this
963 * one in the list, so we only need to look at the newest result item.
964 * If we have an unordered list, we have to scan the whole result
969 OpclassCandidateList prevResult;
971 if (catlist->ordered)
973 if (strcmp(NameStr(opcform->opcname),
974 resultList->opcname_tmp) == 0)
975 prevResult = resultList;
981 for (prevResult = resultList;
983 prevResult = prevResult->next)
985 if (strcmp(NameStr(opcform->opcname),
986 prevResult->opcname_tmp) == 0)
992 /* We have a match with a previous result */
993 Assert(pathpos != prevResult->pathpos);
994 if (pathpos > prevResult->pathpos)
995 continue; /* keep previous result */
996 /* replace previous result */
997 prevResult->opcname_tmp = NameStr(opcform->opcname);
998 prevResult->pathpos = pathpos;
999 prevResult->oid = HeapTupleGetOid(opctup);
1000 prevResult->opcintype = opcform->opcintype;
1001 prevResult->opcdefault = opcform->opcdefault;
1002 prevResult->opckeytype = opcform->opckeytype;
1008 * Okay to add it to result list
1010 newResult = (OpclassCandidateList)
1011 palloc(sizeof(struct _OpclassCandidateList));
1012 newResult->opcname_tmp = NameStr(opcform->opcname);
1013 newResult->pathpos = pathpos;
1014 newResult->oid = HeapTupleGetOid(opctup);
1015 newResult->opcintype = opcform->opcintype;
1016 newResult->opcdefault = opcform->opcdefault;
1017 newResult->opckeytype = opcform->opckeytype;
1018 newResult->next = resultList;
1019 resultList = newResult;
1022 ReleaseSysCacheList(catlist);
1028 * OpclassnameGetOpcid
1029 * Try to resolve an unqualified index opclass name.
1030 * Returns OID if opclass found in search path, else InvalidOid.
1032 * This is essentially the same as TypenameGetTypid, but we have to have
1033 * an extra argument for the index AM OID.
1036 OpclassnameGetOpcid(Oid amid, const char *opcname)
1041 recomputeNamespacePath();
1043 foreach(l, namespaceSearchPath)
1045 Oid namespaceId = lfirst_oid(l);
1047 opcid = GetSysCacheOid(CLAAMNAMENSP,
1048 ObjectIdGetDatum(amid),
1049 PointerGetDatum(opcname),
1050 ObjectIdGetDatum(namespaceId),
1052 if (OidIsValid(opcid))
1056 /* Not found in path */
1062 * Determine whether an opclass (identified by OID) is visible in the
1063 * current search path. Visible means "would be found by searching
1064 * for the unqualified opclass name".
1067 OpclassIsVisible(Oid opcid)
1070 Form_pg_opclass opcform;
1074 opctup = SearchSysCache(CLAOID,
1075 ObjectIdGetDatum(opcid),
1077 if (!HeapTupleIsValid(opctup))
1078 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1079 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1081 recomputeNamespacePath();
1084 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1085 * the system namespace are surely in the path and so we needn't even do
1086 * list_member_oid() for them.
1088 opcnamespace = opcform->opcnamespace;
1089 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1090 !list_member_oid(namespaceSearchPath, opcnamespace))
1095 * If it is in the path, it might still not be visible; it could be
1096 * hidden by another opclass of the same name earlier in the path. So
1097 * we must do a slow check to see if this opclass would be found by
1098 * OpclassnameGetOpcid.
1100 char *opcname = NameStr(opcform->opcname);
1102 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1105 ReleaseSysCache(opctup);
1111 * ConversionGetConid
1112 * Try to resolve an unqualified conversion name.
1113 * Returns OID if conversion found in search path, else InvalidOid.
1115 * This is essentially the same as RelnameGetRelid.
1118 ConversionGetConid(const char *conname)
1123 recomputeNamespacePath();
1125 foreach(l, namespaceSearchPath)
1127 Oid namespaceId = lfirst_oid(l);
1129 conid = GetSysCacheOid(CONNAMENSP,
1130 PointerGetDatum(conname),
1131 ObjectIdGetDatum(namespaceId),
1133 if (OidIsValid(conid))
1137 /* Not found in path */
1142 * ConversionIsVisible
1143 * Determine whether a conversion (identified by OID) is visible in the
1144 * current search path. Visible means "would be found by searching
1145 * for the unqualified conversion name".
1148 ConversionIsVisible(Oid conid)
1151 Form_pg_conversion conform;
1155 contup = SearchSysCache(CONOID,
1156 ObjectIdGetDatum(conid),
1158 if (!HeapTupleIsValid(contup))
1159 elog(ERROR, "cache lookup failed for conversion %u", conid);
1160 conform = (Form_pg_conversion) GETSTRUCT(contup);
1162 recomputeNamespacePath();
1165 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1166 * the system namespace are surely in the path and so we needn't even do
1167 * list_member_oid() for them.
1169 connamespace = conform->connamespace;
1170 if (connamespace != PG_CATALOG_NAMESPACE &&
1171 !list_member_oid(namespaceSearchPath, connamespace))
1176 * If it is in the path, it might still not be visible; it could be
1177 * hidden by another conversion of the same name earlier in the path.
1178 * So we must do a slow check to see if this conversion would be found
1179 * by ConversionGetConid.
1181 char *conname = NameStr(conform->conname);
1183 visible = (ConversionGetConid(conname) == conid);
1186 ReleaseSysCache(contup);
1192 * DeconstructQualifiedName
1193 * Given a possibly-qualified name expressed as a list of String nodes,
1194 * extract the schema name and object name.
1196 * *nspname_p is set to NULL if there is no explicit schema name.
1199 DeconstructQualifiedName(List *names,
1204 char *schemaname = NULL;
1205 char *objname = NULL;
1207 switch (list_length(names))
1210 objname = strVal(linitial(names));
1213 schemaname = strVal(linitial(names));
1214 objname = strVal(lsecond(names));
1217 catalogname = strVal(linitial(names));
1218 schemaname = strVal(lsecond(names));
1219 objname = strVal(lthird(names));
1222 * We check the catalog name and then ignore it.
1224 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
1226 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1227 errmsg("cross-database references are not implemented: %s",
1228 NameListToString(names))));
1232 (errcode(ERRCODE_SYNTAX_ERROR),
1233 errmsg("improper qualified name (too many dotted names): %s",
1234 NameListToString(names))));
1238 *nspname_p = schemaname;
1239 *objname_p = objname;
1243 * LookupExplicitNamespace
1244 * Process an explicitly-specified schema name: look up the schema
1245 * and verify we have USAGE (lookup) rights in it.
1247 * Returns the namespace OID. Raises ereport if any problem.
1250 LookupExplicitNamespace(const char *nspname)
1253 AclResult aclresult;
1255 namespaceId = GetSysCacheOid(NAMESPACENAME,
1256 CStringGetDatum(nspname),
1258 if (!OidIsValid(namespaceId))
1260 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1261 errmsg("schema \"%s\" does not exist", nspname)));
1263 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1264 if (aclresult != ACLCHECK_OK)
1265 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1272 * LookupCreationNamespace
1273 * Look up the schema and verify we have CREATE rights on it.
1275 * This is just like LookupExplicitNamespace except for the permission check.
1278 LookupCreationNamespace(const char *nspname)
1281 AclResult aclresult;
1283 namespaceId = GetSysCacheOid(NAMESPACENAME,
1284 CStringGetDatum(nspname),
1286 if (!OidIsValid(namespaceId))
1288 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1289 errmsg("schema \"%s\" does not exist", nspname)));
1291 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
1292 if (aclresult != ACLCHECK_OK)
1293 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1300 * QualifiedNameGetCreationNamespace
1301 * Given a possibly-qualified name for an object (in List-of-Values
1302 * format), determine what namespace the object should be created in.
1303 * Also extract and return the object name (last component of list).
1305 * Note: this does not apply any permissions check. Callers must check
1306 * for CREATE rights on the selected namespace when appropriate.
1308 * This is *not* used for tables. Hence, the TEMP table namespace is
1309 * never selected as the creation target.
1312 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1318 /* deconstruct the name list */
1319 DeconstructQualifiedName(names, &schemaname, &objname);
1323 /* use exact schema given */
1324 namespaceId = GetSysCacheOid(NAMESPACENAME,
1325 CStringGetDatum(schemaname),
1327 if (!OidIsValid(namespaceId))
1329 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1330 errmsg("schema \"%s\" does not exist", schemaname)));
1331 /* we do not check for USAGE rights here! */
1335 /* use the default creation namespace */
1336 recomputeNamespacePath();
1337 namespaceId = defaultCreationNamespace;
1338 if (!OidIsValid(namespaceId))
1340 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1341 errmsg("no schema has been selected to create in")));
1344 *objname_p = objname;
1349 * makeRangeVarFromNameList
1350 * Utility routine to convert a qualified-name list into RangeVar form.
1353 makeRangeVarFromNameList(List *names)
1355 RangeVar *rel = makeRangeVar(NULL, NULL);
1357 switch (list_length(names))
1360 rel->relname = strVal(linitial(names));
1363 rel->schemaname = strVal(linitial(names));
1364 rel->relname = strVal(lsecond(names));
1367 rel->catalogname = strVal(linitial(names));
1368 rel->schemaname = strVal(lsecond(names));
1369 rel->relname = strVal(lthird(names));
1373 (errcode(ERRCODE_SYNTAX_ERROR),
1374 errmsg("improper relation name (too many dotted names): %s",
1375 NameListToString(names))));
1384 * Utility routine to convert a qualified-name list into a string.
1386 * This is used primarily to form error messages, and so we do not quote
1387 * the list elements, for the sake of legibility.
1390 NameListToString(List *names)
1392 StringInfoData string;
1395 initStringInfo(&string);
1399 if (l != list_head(names))
1400 appendStringInfoChar(&string, '.');
1401 appendStringInfoString(&string, strVal(lfirst(l)));
1408 * NameListToQuotedString
1409 * Utility routine to convert a qualified-name list into a string.
1411 * Same as above except that names will be double-quoted where necessary,
1412 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1415 NameListToQuotedString(List *names)
1417 StringInfoData string;
1420 initStringInfo(&string);
1424 if (l != list_head(names))
1425 appendStringInfoChar(&string, '.');
1426 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1433 * isTempNamespace - is the given namespace my temporary-table namespace?
1436 isTempNamespace(Oid namespaceId)
1438 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1444 * isAnyTempNamespace - is the given namespace a temporary-table namespace
1445 * (either my own, or another backend's)?
1448 isAnyTempNamespace(Oid namespaceId)
1453 /* If the namespace name starts with "pg_temp_", say "true" */
1454 nspname = get_namespace_name(namespaceId);
1456 return false; /* no such namespace? */
1457 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1463 * isOtherTempNamespace - is the given namespace some other backend's
1464 * temporary-table namespace?
1467 isOtherTempNamespace(Oid namespaceId)
1469 /* If it's my own temp namespace, say "false" */
1470 if (isTempNamespace(namespaceId))
1472 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1473 return isAnyTempNamespace(namespaceId);
1477 * PushSpecialNamespace - push a "special" namespace onto the front of the
1480 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1481 * Although the API is defined to allow a stack of pushed namespaces, we
1482 * presently only support one at a time.
1484 * The pushed namespace will be removed from the search path at end of
1485 * transaction, whether commit or abort.
1488 PushSpecialNamespace(Oid namespaceId)
1490 Assert(!OidIsValid(mySpecialNamespace));
1491 mySpecialNamespace = namespaceId;
1492 namespaceSearchPathValid = false;
1496 * PopSpecialNamespace - remove previously pushed special namespace.
1499 PopSpecialNamespace(Oid namespaceId)
1501 Assert(mySpecialNamespace == namespaceId);
1502 mySpecialNamespace = InvalidOid;
1503 namespaceSearchPathValid = false;
1507 * FindConversionByName - find a conversion by possibly qualified name
1510 FindConversionByName(List *name)
1513 char *conversion_name;
1518 /* deconstruct the name list */
1519 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1523 /* use exact schema given */
1524 namespaceId = LookupExplicitNamespace(schemaname);
1525 return FindConversion(conversion_name, namespaceId);
1529 /* search for it in search path */
1530 recomputeNamespacePath();
1532 foreach(l, namespaceSearchPath)
1534 namespaceId = lfirst_oid(l);
1535 conoid = FindConversion(conversion_name, namespaceId);
1536 if (OidIsValid(conoid))
1541 /* Not found in path */
1546 * FindDefaultConversionProc - find default encoding conversion proc
1549 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1554 recomputeNamespacePath();
1556 foreach(l, namespaceSearchPath)
1558 Oid namespaceId = lfirst_oid(l);
1560 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1561 if (OidIsValid(proc))
1565 /* Not found in path */
1570 * recomputeNamespacePath - recompute path derived variables if needed.
1573 recomputeNamespacePath(void)
1575 Oid roleid = GetUserId();
1582 MemoryContext oldcxt;
1585 * Do nothing if path is already valid.
1587 if (namespaceSearchPathValid && namespaceUser == roleid)
1590 /* Need a modifiable copy of namespace_search_path string */
1591 rawname = pstrdup(namespace_search_path);
1593 /* Parse string into list of identifiers */
1594 if (!SplitIdentifierString(rawname, ',', &namelist))
1596 /* syntax error in name list */
1597 /* this should not happen if GUC checked check_search_path */
1598 elog(ERROR, "invalid list syntax");
1602 * Convert the list of names to a list of OIDs. If any names are not
1603 * recognizable or we don't have read access, just leave them out of the
1604 * list. (We can't raise an error, since the search_path setting has
1605 * already been accepted.) Don't make duplicate entries, either.
1608 foreach(l, namelist)
1610 char *curname = (char *) lfirst(l);
1613 if (strcmp(curname, "$user") == 0)
1615 /* $user --- substitute namespace matching user name, if any */
1618 tuple = SearchSysCache(AUTHOID,
1619 ObjectIdGetDatum(roleid),
1621 if (HeapTupleIsValid(tuple))
1625 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
1626 namespaceId = GetSysCacheOid(NAMESPACENAME,
1627 CStringGetDatum(rname),
1629 ReleaseSysCache(tuple);
1630 if (OidIsValid(namespaceId) &&
1631 !list_member_oid(oidlist, namespaceId) &&
1632 pg_namespace_aclcheck(namespaceId, roleid,
1633 ACL_USAGE) == ACLCHECK_OK)
1634 oidlist = lappend_oid(oidlist, namespaceId);
1639 /* normal namespace reference */
1640 namespaceId = GetSysCacheOid(NAMESPACENAME,
1641 CStringGetDatum(curname),
1643 if (OidIsValid(namespaceId) &&
1644 !list_member_oid(oidlist, namespaceId) &&
1645 pg_namespace_aclcheck(namespaceId, roleid,
1646 ACL_USAGE) == ACLCHECK_OK)
1647 oidlist = lappend_oid(oidlist, namespaceId);
1652 * Remember the first member of the explicit list.
1655 firstNS = InvalidOid;
1657 firstNS = linitial_oid(oidlist);
1660 * Add any implicitly-searched namespaces to the list. Note these go on
1661 * the front, not the back; also notice that we do not check USAGE
1662 * permissions for these.
1664 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
1665 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
1667 if (OidIsValid(myTempNamespace) &&
1668 !list_member_oid(oidlist, myTempNamespace))
1669 oidlist = lcons_oid(myTempNamespace, oidlist);
1671 if (OidIsValid(mySpecialNamespace) &&
1672 !list_member_oid(oidlist, mySpecialNamespace))
1673 oidlist = lcons_oid(mySpecialNamespace, oidlist);
1676 * Now that we've successfully built the new list of namespace OIDs, save
1677 * it in permanent storage.
1679 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1680 newpath = list_copy(oidlist);
1681 MemoryContextSwitchTo(oldcxt);
1683 /* Now safe to assign to state variable. */
1684 list_free(namespaceSearchPath);
1685 namespaceSearchPath = newpath;
1688 * Update info derived from search path.
1690 firstExplicitNamespace = firstNS;
1691 if (OidIsValid(mySpecialNamespace))
1692 defaultCreationNamespace = mySpecialNamespace;
1694 defaultCreationNamespace = firstNS;
1696 /* Mark the path valid. */
1697 namespaceSearchPathValid = true;
1698 namespaceUser = roleid;
1702 list_free(namelist);
1707 * InitTempTableNamespace
1708 * Initialize temp table namespace on first use in a particular backend
1711 InitTempTableNamespace(void)
1713 char namespaceName[NAMEDATALEN];
1717 * First, do permission check to see if we are authorized to make temp
1718 * tables. We use a nonstandard error message here since "databasename:
1719 * permission denied" might be a tad cryptic.
1721 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
1722 * that's necessary since current user ID could change during the session.
1723 * But there's no need to make the namespace in the first place until a
1724 * temp table creation request is made by someone with appropriate rights.
1726 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
1727 ACL_CREATE_TEMP) != ACLCHECK_OK)
1729 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1730 errmsg("permission denied to create temporary tables in database \"%s\"",
1731 get_database_name(MyDatabaseId))));
1733 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1735 namespaceId = GetSysCacheOid(NAMESPACENAME,
1736 CStringGetDatum(namespaceName),
1738 if (!OidIsValid(namespaceId))
1741 * First use of this temp namespace in this database; create it. The
1742 * temp namespaces are always owned by the superuser. We leave their
1743 * permissions at default --- i.e., no access except to superuser ---
1744 * to ensure that unprivileged users can't peek at other backends'
1745 * temp tables. This works because the places that access the temp
1746 * namespace for my own backend skip permissions checks on it.
1748 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
1749 /* Advance command counter to make namespace visible */
1750 CommandCounterIncrement();
1755 * If the namespace already exists, clean it out (in case the former
1756 * owner crashed without doing so).
1758 RemoveTempRelations(namespaceId);
1762 * Okay, we've prepared the temp namespace ... but it's not committed yet,
1763 * so all our work could be undone by transaction rollback. Set flag for
1764 * AtEOXact_Namespace to know what to do.
1766 myTempNamespace = namespaceId;
1768 /* It should not be done already. */
1769 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
1770 myTempNamespaceSubID = GetCurrentSubTransactionId();
1772 namespaceSearchPathValid = false; /* need to rebuild list */
1776 * End-of-transaction cleanup for namespaces.
1779 AtEOXact_Namespace(bool isCommit)
1782 * If we abort the transaction in which a temp namespace was selected,
1783 * we'll have to do any creation or cleanout work over again. So, just
1784 * forget the namespace entirely until next time. On the other hand, if
1785 * we commit then register an exit callback to clean out the temp tables
1786 * at backend shutdown. (We only want to register the callback once per
1787 * session, so this is a good place to do it.)
1789 if (myTempNamespaceSubID != InvalidSubTransactionId)
1792 on_shmem_exit(RemoveTempRelationsCallback, 0);
1795 myTempNamespace = InvalidOid;
1796 namespaceSearchPathValid = false; /* need to rebuild list */
1798 myTempNamespaceSubID = InvalidSubTransactionId;
1802 * Clean up if someone failed to do PopSpecialNamespace
1804 if (OidIsValid(mySpecialNamespace))
1806 mySpecialNamespace = InvalidOid;
1807 namespaceSearchPathValid = false; /* need to rebuild list */
1812 * AtEOSubXact_Namespace
1814 * At subtransaction commit, propagate the temp-namespace-creation
1815 * flag to the parent subtransaction.
1817 * At subtransaction abort, forget the flag if we set it up.
1820 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
1821 SubTransactionId parentSubid)
1823 if (myTempNamespaceSubID == mySubid)
1826 myTempNamespaceSubID = parentSubid;
1829 myTempNamespaceSubID = InvalidSubTransactionId;
1830 /* TEMP namespace creation failed, so reset state */
1831 myTempNamespace = InvalidOid;
1832 namespaceSearchPathValid = false; /* need to rebuild list */
1838 * Remove all relations in the specified temp namespace.
1840 * This is called at backend shutdown (if we made any temp relations).
1841 * It is also called when we begin using a pre-existing temp namespace,
1842 * in order to clean out any relations that might have been created by
1843 * a crashed backend.
1846 RemoveTempRelations(Oid tempNamespaceId)
1848 ObjectAddress object;
1851 * We want to get rid of everything in the target namespace, but not the
1852 * namespace itself (deleting it only to recreate it later would be a
1853 * waste of cycles). We do this by finding everything that has a
1854 * dependency on the namespace.
1856 object.classId = NamespaceRelationId;
1857 object.objectId = tempNamespaceId;
1858 object.objectSubId = 0;
1860 deleteWhatDependsOn(&object, false);
1864 * Callback to remove temp relations at backend exit.
1867 RemoveTempRelationsCallback(int code, Datum arg)
1869 if (OidIsValid(myTempNamespace)) /* should always be true */
1871 /* Need to ensure we have a usable transaction. */
1872 AbortOutOfAnyTransaction();
1873 StartTransactionCommand();
1875 RemoveTempRelations(myTempNamespace);
1877 CommitTransactionCommand();
1883 * Routines for handling the GUC variable 'search_path'.
1886 /* assign_hook: validate new search_path, do extra actions as needed */
1888 assign_search_path(const char *newval, bool doit, GucSource source)
1894 /* Need a modifiable copy of string */
1895 rawname = pstrdup(newval);
1897 /* Parse string into list of identifiers */
1898 if (!SplitIdentifierString(rawname, ',', &namelist))
1900 /* syntax error in name list */
1902 list_free(namelist);
1907 * If we aren't inside a transaction, we cannot do database access so
1908 * cannot verify the individual names. Must accept the list on faith.
1910 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
1913 * Verify that all the names are either valid namespace names or
1914 * "$user". We do not require $user to correspond to a valid
1915 * namespace. We do not check for USAGE rights, either; should we?
1917 * When source == PGC_S_TEST, we are checking the argument of an ALTER
1918 * DATABASE SET or ALTER USER SET command. It could be that the
1919 * intended use of the search path is for some other database, so we
1920 * should not error out if it mentions schemas not present in the
1921 * current database. We reduce the message to NOTICE instead.
1923 foreach(l, namelist)
1925 char *curname = (char *) lfirst(l);
1927 if (strcmp(curname, "$user") == 0)
1929 if (!SearchSysCacheExists(NAMESPACENAME,
1930 CStringGetDatum(curname),
1932 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
1933 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1934 errmsg("schema \"%s\" does not exist", curname)));
1939 list_free(namelist);
1942 * We mark the path as needing recomputation, but don't do anything until
1943 * it's needed. This avoids trying to do database access during GUC
1947 namespaceSearchPathValid = false;
1953 * InitializeSearchPath: initialize module during InitPostgres.
1955 * This is called after we are up enough to be able to do catalog lookups.
1958 InitializeSearchPath(void)
1960 if (IsBootstrapProcessingMode())
1963 * In bootstrap mode, the search path must be 'pg_catalog' so that
1964 * tables are created in the proper namespace; ignore the GUC setting.
1966 MemoryContext oldcxt;
1968 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1969 namespaceSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
1970 MemoryContextSwitchTo(oldcxt);
1971 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1972 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1973 namespaceSearchPathValid = true;
1974 namespaceUser = GetUserId();
1979 * In normal mode, arrange for a callback on any syscache invalidation
1980 * of pg_namespace rows.
1982 CacheRegisterSyscacheCallback(NAMESPACEOID,
1985 /* Force search path to be recomputed on next use */
1986 namespaceSearchPathValid = false;
1992 * Syscache inval callback function
1995 NamespaceCallback(Datum arg, Oid relid)
1997 /* Force search path to be recomputed on next use */
1998 namespaceSearchPathValid = false;
2002 * Fetch the active search path. The return value is a palloc'ed list
2003 * of OIDs; the caller is responsible for freeing this storage as
2006 * The returned list includes the implicitly-prepended namespaces only if
2007 * includeImplicit is true.
2010 fetch_search_path(bool includeImplicit)
2014 recomputeNamespacePath();
2016 result = list_copy(namespaceSearchPath);
2017 if (!includeImplicit)
2019 while (result && linitial_oid(result) != firstExplicitNamespace)
2020 result = list_delete_first(result);
2027 * Export the FooIsVisible functions as SQL-callable functions.
2031 pg_table_is_visible(PG_FUNCTION_ARGS)
2033 Oid oid = PG_GETARG_OID(0);
2035 PG_RETURN_BOOL(RelationIsVisible(oid));
2039 pg_type_is_visible(PG_FUNCTION_ARGS)
2041 Oid oid = PG_GETARG_OID(0);
2043 PG_RETURN_BOOL(TypeIsVisible(oid));
2047 pg_function_is_visible(PG_FUNCTION_ARGS)
2049 Oid oid = PG_GETARG_OID(0);
2051 PG_RETURN_BOOL(FunctionIsVisible(oid));
2055 pg_operator_is_visible(PG_FUNCTION_ARGS)
2057 Oid oid = PG_GETARG_OID(0);
2059 PG_RETURN_BOOL(OperatorIsVisible(oid));
2063 pg_opclass_is_visible(PG_FUNCTION_ARGS)
2065 Oid oid = PG_GETARG_OID(0);
2067 PG_RETURN_BOOL(OpclassIsVisible(oid));
2071 pg_conversion_is_visible(PG_FUNCTION_ARGS)
2073 Oid oid = PG_GETARG_OID(0);
2075 PG_RETURN_BOOL(ConversionIsVisible(oid));