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.79 2005/10/15 02:49:14 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 case),
962 * then any conflicting opclass must immediately adjoin this one in
963 * the list, so we only need to look at the newest result item. If we
964 * have an unordered list, we have to scan the whole result list.
968 OpclassCandidateList prevResult;
970 if (catlist->ordered)
972 if (strcmp(NameStr(opcform->opcname),
973 resultList->opcname_tmp) == 0)
974 prevResult = resultList;
980 for (prevResult = resultList;
982 prevResult = prevResult->next)
984 if (strcmp(NameStr(opcform->opcname),
985 prevResult->opcname_tmp) == 0)
991 /* We have a match with a previous result */
992 Assert(pathpos != prevResult->pathpos);
993 if (pathpos > prevResult->pathpos)
994 continue; /* keep previous result */
995 /* replace previous result */
996 prevResult->opcname_tmp = NameStr(opcform->opcname);
997 prevResult->pathpos = pathpos;
998 prevResult->oid = HeapTupleGetOid(opctup);
999 prevResult->opcintype = opcform->opcintype;
1000 prevResult->opcdefault = opcform->opcdefault;
1001 prevResult->opckeytype = opcform->opckeytype;
1007 * Okay to add it to result list
1009 newResult = (OpclassCandidateList)
1010 palloc(sizeof(struct _OpclassCandidateList));
1011 newResult->opcname_tmp = NameStr(opcform->opcname);
1012 newResult->pathpos = pathpos;
1013 newResult->oid = HeapTupleGetOid(opctup);
1014 newResult->opcintype = opcform->opcintype;
1015 newResult->opcdefault = opcform->opcdefault;
1016 newResult->opckeytype = opcform->opckeytype;
1017 newResult->next = resultList;
1018 resultList = newResult;
1021 ReleaseSysCacheList(catlist);
1027 * OpclassnameGetOpcid
1028 * Try to resolve an unqualified index opclass name.
1029 * Returns OID if opclass found in search path, else InvalidOid.
1031 * This is essentially the same as TypenameGetTypid, but we have to have
1032 * an extra argument for the index AM OID.
1035 OpclassnameGetOpcid(Oid amid, const char *opcname)
1040 recomputeNamespacePath();
1042 foreach(l, namespaceSearchPath)
1044 Oid namespaceId = lfirst_oid(l);
1046 opcid = GetSysCacheOid(CLAAMNAMENSP,
1047 ObjectIdGetDatum(amid),
1048 PointerGetDatum(opcname),
1049 ObjectIdGetDatum(namespaceId),
1051 if (OidIsValid(opcid))
1055 /* Not found in path */
1061 * Determine whether an opclass (identified by OID) is visible in the
1062 * current search path. Visible means "would be found by searching
1063 * for the unqualified opclass name".
1066 OpclassIsVisible(Oid opcid)
1069 Form_pg_opclass opcform;
1073 opctup = SearchSysCache(CLAOID,
1074 ObjectIdGetDatum(opcid),
1076 if (!HeapTupleIsValid(opctup))
1077 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1078 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1080 recomputeNamespacePath();
1083 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1084 * the system namespace are surely in the path and so we needn't even do
1085 * list_member_oid() for them.
1087 opcnamespace = opcform->opcnamespace;
1088 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1089 !list_member_oid(namespaceSearchPath, opcnamespace))
1094 * If it is in the path, it might still not be visible; it could be
1095 * hidden by another opclass of the same name earlier in the path. So
1096 * we must do a slow check to see if this opclass would be found by
1097 * OpclassnameGetOpcid.
1099 char *opcname = NameStr(opcform->opcname);
1101 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1104 ReleaseSysCache(opctup);
1110 * ConversionGetConid
1111 * Try to resolve an unqualified conversion name.
1112 * Returns OID if conversion found in search path, else InvalidOid.
1114 * This is essentially the same as RelnameGetRelid.
1117 ConversionGetConid(const char *conname)
1122 recomputeNamespacePath();
1124 foreach(l, namespaceSearchPath)
1126 Oid namespaceId = lfirst_oid(l);
1128 conid = GetSysCacheOid(CONNAMENSP,
1129 PointerGetDatum(conname),
1130 ObjectIdGetDatum(namespaceId),
1132 if (OidIsValid(conid))
1136 /* Not found in path */
1141 * ConversionIsVisible
1142 * Determine whether a conversion (identified by OID) is visible in the
1143 * current search path. Visible means "would be found by searching
1144 * for the unqualified conversion name".
1147 ConversionIsVisible(Oid conid)
1150 Form_pg_conversion conform;
1154 contup = SearchSysCache(CONOID,
1155 ObjectIdGetDatum(conid),
1157 if (!HeapTupleIsValid(contup))
1158 elog(ERROR, "cache lookup failed for conversion %u", conid);
1159 conform = (Form_pg_conversion) GETSTRUCT(contup);
1161 recomputeNamespacePath();
1164 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1165 * the system namespace are surely in the path and so we needn't even do
1166 * list_member_oid() for them.
1168 connamespace = conform->connamespace;
1169 if (connamespace != PG_CATALOG_NAMESPACE &&
1170 !list_member_oid(namespaceSearchPath, connamespace))
1175 * If it is in the path, it might still not be visible; it could be
1176 * hidden by another conversion of the same name earlier in the path.
1177 * So we must do a slow check to see if this conversion would be found
1178 * by ConversionGetConid.
1180 char *conname = NameStr(conform->conname);
1182 visible = (ConversionGetConid(conname) == conid);
1185 ReleaseSysCache(contup);
1191 * DeconstructQualifiedName
1192 * Given a possibly-qualified name expressed as a list of String nodes,
1193 * extract the schema name and object name.
1195 * *nspname_p is set to NULL if there is no explicit schema name.
1198 DeconstructQualifiedName(List *names,
1203 char *schemaname = NULL;
1204 char *objname = NULL;
1206 switch (list_length(names))
1209 objname = strVal(linitial(names));
1212 schemaname = strVal(linitial(names));
1213 objname = strVal(lsecond(names));
1216 catalogname = strVal(linitial(names));
1217 schemaname = strVal(lsecond(names));
1218 objname = strVal(lthird(names));
1221 * We check the catalog name and then ignore it.
1223 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
1225 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1226 errmsg("cross-database references are not implemented: %s",
1227 NameListToString(names))));
1231 (errcode(ERRCODE_SYNTAX_ERROR),
1232 errmsg("improper qualified name (too many dotted names): %s",
1233 NameListToString(names))));
1237 *nspname_p = schemaname;
1238 *objname_p = objname;
1242 * LookupExplicitNamespace
1243 * Process an explicitly-specified schema name: look up the schema
1244 * and verify we have USAGE (lookup) rights in it.
1246 * Returns the namespace OID. Raises ereport if any problem.
1249 LookupExplicitNamespace(const char *nspname)
1252 AclResult aclresult;
1254 namespaceId = GetSysCacheOid(NAMESPACENAME,
1255 CStringGetDatum(nspname),
1257 if (!OidIsValid(namespaceId))
1259 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1260 errmsg("schema \"%s\" does not exist", nspname)));
1262 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1263 if (aclresult != ACLCHECK_OK)
1264 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1271 * LookupCreationNamespace
1272 * Look up the schema and verify we have CREATE rights on it.
1274 * This is just like LookupExplicitNamespace except for the permission check.
1277 LookupCreationNamespace(const char *nspname)
1280 AclResult aclresult;
1282 namespaceId = GetSysCacheOid(NAMESPACENAME,
1283 CStringGetDatum(nspname),
1285 if (!OidIsValid(namespaceId))
1287 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1288 errmsg("schema \"%s\" does not exist", nspname)));
1290 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
1291 if (aclresult != ACLCHECK_OK)
1292 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1299 * QualifiedNameGetCreationNamespace
1300 * Given a possibly-qualified name for an object (in List-of-Values
1301 * format), determine what namespace the object should be created in.
1302 * Also extract and return the object name (last component of list).
1304 * Note: this does not apply any permissions check. Callers must check
1305 * for CREATE rights on the selected namespace when appropriate.
1307 * This is *not* used for tables. Hence, the TEMP table namespace is
1308 * never selected as the creation target.
1311 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1317 /* deconstruct the name list */
1318 DeconstructQualifiedName(names, &schemaname, &objname);
1322 /* use exact schema given */
1323 namespaceId = GetSysCacheOid(NAMESPACENAME,
1324 CStringGetDatum(schemaname),
1326 if (!OidIsValid(namespaceId))
1328 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1329 errmsg("schema \"%s\" does not exist", schemaname)));
1330 /* we do not check for USAGE rights here! */
1334 /* use the default creation namespace */
1335 recomputeNamespacePath();
1336 namespaceId = defaultCreationNamespace;
1337 if (!OidIsValid(namespaceId))
1339 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1340 errmsg("no schema has been selected to create in")));
1343 *objname_p = objname;
1348 * makeRangeVarFromNameList
1349 * Utility routine to convert a qualified-name list into RangeVar form.
1352 makeRangeVarFromNameList(List *names)
1354 RangeVar *rel = makeRangeVar(NULL, NULL);
1356 switch (list_length(names))
1359 rel->relname = strVal(linitial(names));
1362 rel->schemaname = strVal(linitial(names));
1363 rel->relname = strVal(lsecond(names));
1366 rel->catalogname = strVal(linitial(names));
1367 rel->schemaname = strVal(lsecond(names));
1368 rel->relname = strVal(lthird(names));
1372 (errcode(ERRCODE_SYNTAX_ERROR),
1373 errmsg("improper relation name (too many dotted names): %s",
1374 NameListToString(names))));
1383 * Utility routine to convert a qualified-name list into a string.
1385 * This is used primarily to form error messages, and so we do not quote
1386 * the list elements, for the sake of legibility.
1389 NameListToString(List *names)
1391 StringInfoData string;
1394 initStringInfo(&string);
1398 if (l != list_head(names))
1399 appendStringInfoChar(&string, '.');
1400 appendStringInfoString(&string, strVal(lfirst(l)));
1407 * NameListToQuotedString
1408 * Utility routine to convert a qualified-name list into a string.
1410 * Same as above except that names will be double-quoted where necessary,
1411 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1414 NameListToQuotedString(List *names)
1416 StringInfoData string;
1419 initStringInfo(&string);
1423 if (l != list_head(names))
1424 appendStringInfoChar(&string, '.');
1425 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1432 * isTempNamespace - is the given namespace my temporary-table namespace?
1435 isTempNamespace(Oid namespaceId)
1437 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1443 * isAnyTempNamespace - is the given namespace a temporary-table namespace
1444 * (either my own, or another backend's)?
1447 isAnyTempNamespace(Oid namespaceId)
1452 /* If the namespace name starts with "pg_temp_", say "true" */
1453 nspname = get_namespace_name(namespaceId);
1455 return false; /* no such namespace? */
1456 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1462 * isOtherTempNamespace - is the given namespace some other backend's
1463 * temporary-table namespace?
1466 isOtherTempNamespace(Oid namespaceId)
1468 /* If it's my own temp namespace, say "false" */
1469 if (isTempNamespace(namespaceId))
1471 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1472 return isAnyTempNamespace(namespaceId);
1476 * PushSpecialNamespace - push a "special" namespace onto the front of the
1479 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1480 * Although the API is defined to allow a stack of pushed namespaces, we
1481 * presently only support one at a time.
1483 * The pushed namespace will be removed from the search path at end of
1484 * transaction, whether commit or abort.
1487 PushSpecialNamespace(Oid namespaceId)
1489 Assert(!OidIsValid(mySpecialNamespace));
1490 mySpecialNamespace = namespaceId;
1491 namespaceSearchPathValid = false;
1495 * PopSpecialNamespace - remove previously pushed special namespace.
1498 PopSpecialNamespace(Oid namespaceId)
1500 Assert(mySpecialNamespace == namespaceId);
1501 mySpecialNamespace = InvalidOid;
1502 namespaceSearchPathValid = false;
1506 * FindConversionByName - find a conversion by possibly qualified name
1509 FindConversionByName(List *name)
1512 char *conversion_name;
1517 /* deconstruct the name list */
1518 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1522 /* use exact schema given */
1523 namespaceId = LookupExplicitNamespace(schemaname);
1524 return FindConversion(conversion_name, namespaceId);
1528 /* search for it in search path */
1529 recomputeNamespacePath();
1531 foreach(l, namespaceSearchPath)
1533 namespaceId = lfirst_oid(l);
1534 conoid = FindConversion(conversion_name, namespaceId);
1535 if (OidIsValid(conoid))
1540 /* Not found in path */
1545 * FindDefaultConversionProc - find default encoding conversion proc
1548 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1553 recomputeNamespacePath();
1555 foreach(l, namespaceSearchPath)
1557 Oid namespaceId = lfirst_oid(l);
1559 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1560 if (OidIsValid(proc))
1564 /* Not found in path */
1569 * recomputeNamespacePath - recompute path derived variables if needed.
1572 recomputeNamespacePath(void)
1574 Oid roleid = GetUserId();
1581 MemoryContext oldcxt;
1584 * Do nothing if path is already valid.
1586 if (namespaceSearchPathValid && namespaceUser == roleid)
1589 /* Need a modifiable copy of namespace_search_path string */
1590 rawname = pstrdup(namespace_search_path);
1592 /* Parse string into list of identifiers */
1593 if (!SplitIdentifierString(rawname, ',', &namelist))
1595 /* syntax error in name list */
1596 /* this should not happen if GUC checked check_search_path */
1597 elog(ERROR, "invalid list syntax");
1601 * Convert the list of names to a list of OIDs. If any names are not
1602 * recognizable or we don't have read access, just leave them out of the
1603 * list. (We can't raise an error, since the search_path setting has
1604 * already been accepted.) Don't make duplicate entries, either.
1607 foreach(l, namelist)
1609 char *curname = (char *) lfirst(l);
1612 if (strcmp(curname, "$user") == 0)
1614 /* $user --- substitute namespace matching user name, if any */
1617 tuple = SearchSysCache(AUTHOID,
1618 ObjectIdGetDatum(roleid),
1620 if (HeapTupleIsValid(tuple))
1624 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
1625 namespaceId = GetSysCacheOid(NAMESPACENAME,
1626 CStringGetDatum(rname),
1628 ReleaseSysCache(tuple);
1629 if (OidIsValid(namespaceId) &&
1630 !list_member_oid(oidlist, namespaceId) &&
1631 pg_namespace_aclcheck(namespaceId, roleid,
1632 ACL_USAGE) == ACLCHECK_OK)
1633 oidlist = lappend_oid(oidlist, namespaceId);
1638 /* normal namespace reference */
1639 namespaceId = GetSysCacheOid(NAMESPACENAME,
1640 CStringGetDatum(curname),
1642 if (OidIsValid(namespaceId) &&
1643 !list_member_oid(oidlist, namespaceId) &&
1644 pg_namespace_aclcheck(namespaceId, roleid,
1645 ACL_USAGE) == ACLCHECK_OK)
1646 oidlist = lappend_oid(oidlist, namespaceId);
1651 * Remember the first member of the explicit list.
1654 firstNS = InvalidOid;
1656 firstNS = linitial_oid(oidlist);
1659 * Add any implicitly-searched namespaces to the list. Note these go on
1660 * the front, not the back; also notice that we do not check USAGE
1661 * permissions for these.
1663 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
1664 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
1666 if (OidIsValid(myTempNamespace) &&
1667 !list_member_oid(oidlist, myTempNamespace))
1668 oidlist = lcons_oid(myTempNamespace, oidlist);
1670 if (OidIsValid(mySpecialNamespace) &&
1671 !list_member_oid(oidlist, mySpecialNamespace))
1672 oidlist = lcons_oid(mySpecialNamespace, oidlist);
1675 * Now that we've successfully built the new list of namespace OIDs, save
1676 * it in permanent storage.
1678 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1679 newpath = list_copy(oidlist);
1680 MemoryContextSwitchTo(oldcxt);
1682 /* Now safe to assign to state variable. */
1683 list_free(namespaceSearchPath);
1684 namespaceSearchPath = newpath;
1687 * Update info derived from search path.
1689 firstExplicitNamespace = firstNS;
1690 if (OidIsValid(mySpecialNamespace))
1691 defaultCreationNamespace = mySpecialNamespace;
1693 defaultCreationNamespace = firstNS;
1695 /* Mark the path valid. */
1696 namespaceSearchPathValid = true;
1697 namespaceUser = roleid;
1701 list_free(namelist);
1706 * InitTempTableNamespace
1707 * Initialize temp table namespace on first use in a particular backend
1710 InitTempTableNamespace(void)
1712 char namespaceName[NAMEDATALEN];
1716 * First, do permission check to see if we are authorized to make temp
1717 * tables. We use a nonstandard error message here since "databasename:
1718 * permission denied" might be a tad cryptic.
1720 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
1721 * that's necessary since current user ID could change during the session.
1722 * But there's no need to make the namespace in the first place until a
1723 * temp table creation request is made by someone with appropriate rights.
1725 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
1726 ACL_CREATE_TEMP) != ACLCHECK_OK)
1728 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1729 errmsg("permission denied to create temporary tables in database \"%s\"",
1730 get_database_name(MyDatabaseId))));
1732 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1734 namespaceId = GetSysCacheOid(NAMESPACENAME,
1735 CStringGetDatum(namespaceName),
1737 if (!OidIsValid(namespaceId))
1740 * First use of this temp namespace in this database; create it. The
1741 * temp namespaces are always owned by the superuser. We leave their
1742 * permissions at default --- i.e., no access except to superuser ---
1743 * to ensure that unprivileged users can't peek at other backends'
1744 * temp tables. This works because the places that access the temp
1745 * namespace for my own backend skip permissions checks on it.
1747 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
1748 /* Advance command counter to make namespace visible */
1749 CommandCounterIncrement();
1754 * If the namespace already exists, clean it out (in case the former
1755 * owner crashed without doing so).
1757 RemoveTempRelations(namespaceId);
1761 * Okay, we've prepared the temp namespace ... but it's not committed yet,
1762 * so all our work could be undone by transaction rollback. Set flag for
1763 * AtEOXact_Namespace to know what to do.
1765 myTempNamespace = namespaceId;
1767 /* It should not be done already. */
1768 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
1769 myTempNamespaceSubID = GetCurrentSubTransactionId();
1771 namespaceSearchPathValid = false; /* need to rebuild list */
1775 * End-of-transaction cleanup for namespaces.
1778 AtEOXact_Namespace(bool isCommit)
1781 * If we abort the transaction in which a temp namespace was selected,
1782 * we'll have to do any creation or cleanout work over again. So, just
1783 * forget the namespace entirely until next time. On the other hand, if
1784 * we commit then register an exit callback to clean out the temp tables
1785 * at backend shutdown. (We only want to register the callback once per
1786 * session, so this is a good place to do it.)
1788 if (myTempNamespaceSubID != InvalidSubTransactionId)
1791 on_shmem_exit(RemoveTempRelationsCallback, 0);
1794 myTempNamespace = InvalidOid;
1795 namespaceSearchPathValid = false; /* need to rebuild list */
1797 myTempNamespaceSubID = InvalidSubTransactionId;
1801 * Clean up if someone failed to do PopSpecialNamespace
1803 if (OidIsValid(mySpecialNamespace))
1805 mySpecialNamespace = InvalidOid;
1806 namespaceSearchPathValid = false; /* need to rebuild list */
1811 * AtEOSubXact_Namespace
1813 * At subtransaction commit, propagate the temp-namespace-creation
1814 * flag to the parent subtransaction.
1816 * At subtransaction abort, forget the flag if we set it up.
1819 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
1820 SubTransactionId parentSubid)
1822 if (myTempNamespaceSubID == mySubid)
1825 myTempNamespaceSubID = parentSubid;
1828 myTempNamespaceSubID = InvalidSubTransactionId;
1829 /* TEMP namespace creation failed, so reset state */
1830 myTempNamespace = InvalidOid;
1831 namespaceSearchPathValid = false; /* need to rebuild list */
1837 * Remove all relations in the specified temp namespace.
1839 * This is called at backend shutdown (if we made any temp relations).
1840 * It is also called when we begin using a pre-existing temp namespace,
1841 * in order to clean out any relations that might have been created by
1842 * a crashed backend.
1845 RemoveTempRelations(Oid tempNamespaceId)
1847 ObjectAddress object;
1850 * We want to get rid of everything in the target namespace, but not the
1851 * namespace itself (deleting it only to recreate it later would be a
1852 * waste of cycles). We do this by finding everything that has a
1853 * dependency on the namespace.
1855 object.classId = NamespaceRelationId;
1856 object.objectId = tempNamespaceId;
1857 object.objectSubId = 0;
1859 deleteWhatDependsOn(&object, false);
1863 * Callback to remove temp relations at backend exit.
1866 RemoveTempRelationsCallback(int code, Datum arg)
1868 if (OidIsValid(myTempNamespace)) /* should always be true */
1870 /* Need to ensure we have a usable transaction. */
1871 AbortOutOfAnyTransaction();
1872 StartTransactionCommand();
1874 RemoveTempRelations(myTempNamespace);
1876 CommitTransactionCommand();
1882 * Routines for handling the GUC variable 'search_path'.
1885 /* assign_hook: validate new search_path, do extra actions as needed */
1887 assign_search_path(const char *newval, bool doit, GucSource source)
1893 /* Need a modifiable copy of string */
1894 rawname = pstrdup(newval);
1896 /* Parse string into list of identifiers */
1897 if (!SplitIdentifierString(rawname, ',', &namelist))
1899 /* syntax error in name list */
1901 list_free(namelist);
1906 * If we aren't inside a transaction, we cannot do database access so
1907 * cannot verify the individual names. Must accept the list on faith.
1909 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
1912 * Verify that all the names are either valid namespace names or
1913 * "$user". We do not require $user to correspond to a valid
1914 * namespace. We do not check for USAGE rights, either; should we?
1916 * When source == PGC_S_TEST, we are checking the argument of an ALTER
1917 * DATABASE SET or ALTER USER SET command. It could be that the
1918 * intended use of the search path is for some other database, so we
1919 * should not error out if it mentions schemas not present in the
1920 * current database. We reduce the message to NOTICE instead.
1922 foreach(l, namelist)
1924 char *curname = (char *) lfirst(l);
1926 if (strcmp(curname, "$user") == 0)
1928 if (!SearchSysCacheExists(NAMESPACENAME,
1929 CStringGetDatum(curname),
1931 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
1932 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1933 errmsg("schema \"%s\" does not exist", curname)));
1938 list_free(namelist);
1941 * We mark the path as needing recomputation, but don't do anything until
1942 * it's needed. This avoids trying to do database access during GUC
1946 namespaceSearchPathValid = false;
1952 * InitializeSearchPath: initialize module during InitPostgres.
1954 * This is called after we are up enough to be able to do catalog lookups.
1957 InitializeSearchPath(void)
1959 if (IsBootstrapProcessingMode())
1962 * In bootstrap mode, the search path must be 'pg_catalog' so that
1963 * tables are created in the proper namespace; ignore the GUC setting.
1965 MemoryContext oldcxt;
1967 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1968 namespaceSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
1969 MemoryContextSwitchTo(oldcxt);
1970 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1971 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1972 namespaceSearchPathValid = true;
1973 namespaceUser = GetUserId();
1978 * In normal mode, arrange for a callback on any syscache invalidation
1979 * of pg_namespace rows.
1981 CacheRegisterSyscacheCallback(NAMESPACEOID,
1984 /* Force search path to be recomputed on next use */
1985 namespaceSearchPathValid = false;
1991 * Syscache inval callback function
1994 NamespaceCallback(Datum arg, Oid relid)
1996 /* Force search path to be recomputed on next use */
1997 namespaceSearchPathValid = false;
2001 * Fetch the active search path. The return value is a palloc'ed list
2002 * of OIDs; the caller is responsible for freeing this storage as
2005 * The returned list includes the implicitly-prepended namespaces only if
2006 * includeImplicit is true.
2009 fetch_search_path(bool includeImplicit)
2013 recomputeNamespacePath();
2015 result = list_copy(namespaceSearchPath);
2016 if (!includeImplicit)
2018 while (result && linitial_oid(result) != firstExplicitNamespace)
2019 result = list_delete_first(result);
2026 * Export the FooIsVisible functions as SQL-callable functions.
2030 pg_table_is_visible(PG_FUNCTION_ARGS)
2032 Oid oid = PG_GETARG_OID(0);
2034 PG_RETURN_BOOL(RelationIsVisible(oid));
2038 pg_type_is_visible(PG_FUNCTION_ARGS)
2040 Oid oid = PG_GETARG_OID(0);
2042 PG_RETURN_BOOL(TypeIsVisible(oid));
2046 pg_function_is_visible(PG_FUNCTION_ARGS)
2048 Oid oid = PG_GETARG_OID(0);
2050 PG_RETURN_BOOL(FunctionIsVisible(oid));
2054 pg_operator_is_visible(PG_FUNCTION_ARGS)
2056 Oid oid = PG_GETARG_OID(0);
2058 PG_RETURN_BOOL(OperatorIsVisible(oid));
2062 pg_opclass_is_visible(PG_FUNCTION_ARGS)
2064 Oid oid = PG_GETARG_OID(0);
2066 PG_RETURN_BOOL(OpclassIsVisible(oid));
2070 pg_conversion_is_visible(PG_FUNCTION_ARGS)
2072 Oid oid = PG_GETARG_OID(0);
2074 PG_RETURN_BOOL(ConversionIsVisible(oid));