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.78 2005/10/06 22:43:16 tgl 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.
326 * Items in the system namespace are surely in the path and so we
327 * needn't even do 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
337 * be hidden by another relation of the same name earlier in the
338 * path. So 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.
424 * Items in the system namespace are surely in the path and so we
425 * needn't even do 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
435 * be hidden by another type of the same name earlier in the path.
436 * So we 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
549 * only 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
553 * this one in the list, so we only need to look at the newest
554 * result item. If we have an unordered list, we have to scan
555 * the whole result list.
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.
644 * Items in the system namespace are surely in the path and so we
645 * needn't even do 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
655 * be hidden by another proc of the same name and arguments
656 * earlier in the path. So we must do a slow check to see if this
657 * is the same 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
737 * quite a few, for common operator names such as '=' or '+'. To
738 * reduce the time spent in palloc, we allocate the result space as an
739 * array large enough to hold all the operators. The original coding
740 * of this routine did a separate palloc for each operator, but
741 * profiling revealed that the pallocs used an unreasonably large
742 * fraction of parsing time.
744 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
746 if (catlist->n_members > 0)
747 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
749 for (i = 0; i < catlist->n_members; i++)
751 HeapTuple opertup = &catlist->members[i]->tuple;
752 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
754 FuncCandidateList newResult;
756 /* Ignore operators of wrong kind, if specific kind requested */
757 if (oprkind && operform->oprkind != oprkind)
760 if (OidIsValid(namespaceId))
762 /* Consider only opers in specified namespace */
763 if (operform->oprnamespace != namespaceId)
765 /* No need to check args, they must all be different */
769 /* Consider only opers that are in the search path */
772 foreach(nsp, namespaceSearchPath)
774 if (operform->oprnamespace == lfirst_oid(nsp))
779 continue; /* oper is not in search path */
782 * Okay, it's in the search path, but does it have the same
783 * arguments as something we already accepted? If so, keep
784 * only the one that appears earlier in the search path.
786 * If we have an ordered list from SearchSysCacheList (the normal
787 * case), then any conflicting oper must immediately adjoin
788 * this one in the list, so we only need to look at the newest
789 * result item. If we have an unordered list, we have to scan
790 * the whole result list.
794 FuncCandidateList prevResult;
796 if (catlist->ordered)
798 if (operform->oprleft == resultList->args[0] &&
799 operform->oprright == resultList->args[1])
800 prevResult = resultList;
806 for (prevResult = resultList;
808 prevResult = prevResult->next)
810 if (operform->oprleft == prevResult->args[0] &&
811 operform->oprright == prevResult->args[1])
817 /* We have a match with a previous result */
818 Assert(pathpos != prevResult->pathpos);
819 if (pathpos > prevResult->pathpos)
820 continue; /* keep previous result */
821 /* replace previous result */
822 prevResult->pathpos = pathpos;
823 prevResult->oid = HeapTupleGetOid(opertup);
824 continue; /* args are same, of course */
830 * Okay to add it to result list
832 newResult = (FuncCandidateList) (resultSpace + nextResult);
833 nextResult += SPACE_PER_OP;
835 newResult->pathpos = pathpos;
836 newResult->oid = HeapTupleGetOid(opertup);
837 newResult->nargs = 2;
838 newResult->args[0] = operform->oprleft;
839 newResult->args[1] = operform->oprright;
840 newResult->next = resultList;
841 resultList = newResult;
844 ReleaseSysCacheList(catlist);
851 * Determine whether an operator (identified by OID) is visible in the
852 * current search path. Visible means "would be found by searching
853 * for the unqualified operator name with exact argument matches".
856 OperatorIsVisible(Oid oprid)
859 Form_pg_operator oprform;
863 oprtup = SearchSysCache(OPEROID,
864 ObjectIdGetDatum(oprid),
866 if (!HeapTupleIsValid(oprtup))
867 elog(ERROR, "cache lookup failed for operator %u", oprid);
868 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
870 recomputeNamespacePath();
873 * Quick check: if it ain't in the path at all, it ain't visible.
874 * Items in the system namespace are surely in the path and so we
875 * needn't even do list_member_oid() for them.
877 oprnamespace = oprform->oprnamespace;
878 if (oprnamespace != PG_CATALOG_NAMESPACE &&
879 !list_member_oid(namespaceSearchPath, oprnamespace))
884 * If it is in the path, it might still not be visible; it could
885 * be hidden by another operator of the same name and arguments
886 * earlier in the path. So we must do a slow check to see if this
887 * is the same operator that would be found by
888 * OpernameGetCandidates.
890 char *oprname = NameStr(oprform->oprname);
891 FuncCandidateList clist;
895 clist = OpernameGetCandidates(list_make1(makeString(oprname)),
898 for (; clist; clist = clist->next)
900 if (clist->args[0] == oprform->oprleft &&
901 clist->args[1] == oprform->oprright)
903 /* Found the expected entry; is it the right op? */
904 visible = (clist->oid == oprid);
910 ReleaseSysCache(oprtup);
917 * OpclassGetCandidates
918 * Given an index access method OID, retrieve a list of all the
919 * opclasses for that AM that are visible in the search path.
921 * NOTE: the opcname_tmp field in the returned structs should not be used
922 * by callers, because it points at syscache entries that we release at
923 * the end of this routine. If any callers needed the name information,
924 * we could pstrdup() the names ... but at present it'd be wasteful.
927 OpclassGetCandidates(Oid amid)
929 OpclassCandidateList resultList = NULL;
933 /* Search syscache by AM OID only */
934 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
935 ObjectIdGetDatum(amid),
938 recomputeNamespacePath();
940 for (i = 0; i < catlist->n_members; i++)
942 HeapTuple opctup = &catlist->members[i]->tuple;
943 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
945 OpclassCandidateList newResult;
948 /* Consider only opclasses that are in the search path */
949 foreach(nsp, namespaceSearchPath)
951 if (opcform->opcnamespace == lfirst_oid(nsp))
956 continue; /* opclass is not in search path */
959 * Okay, it's in the search path, but does it have the same name
960 * as something we already accepted? If so, keep only the one
961 * that appears earlier in the search path.
963 * If we have an ordered list from SearchSysCacheList (the normal
964 * case), then any conflicting opclass must immediately adjoin
965 * this one in the list, so we only need to look at the newest
966 * result item. If we have an unordered list, we have to scan the
971 OpclassCandidateList prevResult;
973 if (catlist->ordered)
975 if (strcmp(NameStr(opcform->opcname),
976 resultList->opcname_tmp) == 0)
977 prevResult = resultList;
983 for (prevResult = resultList;
985 prevResult = prevResult->next)
987 if (strcmp(NameStr(opcform->opcname),
988 prevResult->opcname_tmp) == 0)
994 /* We have a match with a previous result */
995 Assert(pathpos != prevResult->pathpos);
996 if (pathpos > prevResult->pathpos)
997 continue; /* keep previous result */
998 /* replace previous result */
999 prevResult->opcname_tmp = NameStr(opcform->opcname);
1000 prevResult->pathpos = pathpos;
1001 prevResult->oid = HeapTupleGetOid(opctup);
1002 prevResult->opcintype = opcform->opcintype;
1003 prevResult->opcdefault = opcform->opcdefault;
1004 prevResult->opckeytype = opcform->opckeytype;
1010 * Okay to add it to result list
1012 newResult = (OpclassCandidateList)
1013 palloc(sizeof(struct _OpclassCandidateList));
1014 newResult->opcname_tmp = NameStr(opcform->opcname);
1015 newResult->pathpos = pathpos;
1016 newResult->oid = HeapTupleGetOid(opctup);
1017 newResult->opcintype = opcform->opcintype;
1018 newResult->opcdefault = opcform->opcdefault;
1019 newResult->opckeytype = opcform->opckeytype;
1020 newResult->next = resultList;
1021 resultList = newResult;
1024 ReleaseSysCacheList(catlist);
1030 * OpclassnameGetOpcid
1031 * Try to resolve an unqualified index opclass name.
1032 * Returns OID if opclass found in search path, else InvalidOid.
1034 * This is essentially the same as TypenameGetTypid, but we have to have
1035 * an extra argument for the index AM OID.
1038 OpclassnameGetOpcid(Oid amid, const char *opcname)
1043 recomputeNamespacePath();
1045 foreach(l, namespaceSearchPath)
1047 Oid namespaceId = lfirst_oid(l);
1049 opcid = GetSysCacheOid(CLAAMNAMENSP,
1050 ObjectIdGetDatum(amid),
1051 PointerGetDatum(opcname),
1052 ObjectIdGetDatum(namespaceId),
1054 if (OidIsValid(opcid))
1058 /* Not found in path */
1064 * Determine whether an opclass (identified by OID) is visible in the
1065 * current search path. Visible means "would be found by searching
1066 * for the unqualified opclass name".
1069 OpclassIsVisible(Oid opcid)
1072 Form_pg_opclass opcform;
1076 opctup = SearchSysCache(CLAOID,
1077 ObjectIdGetDatum(opcid),
1079 if (!HeapTupleIsValid(opctup))
1080 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1081 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1083 recomputeNamespacePath();
1086 * Quick check: if it ain't in the path at all, it ain't visible.
1087 * Items in the system namespace are surely in the path and so we
1088 * needn't even do list_member_oid() for them.
1090 opcnamespace = opcform->opcnamespace;
1091 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1092 !list_member_oid(namespaceSearchPath, opcnamespace))
1097 * If it is in the path, it might still not be visible; it could
1098 * be hidden by another opclass of the same name earlier in the
1099 * path. So we must do a slow check to see if this opclass would
1100 * be found by OpclassnameGetOpcid.
1102 char *opcname = NameStr(opcform->opcname);
1104 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1107 ReleaseSysCache(opctup);
1113 * ConversionGetConid
1114 * Try to resolve an unqualified conversion name.
1115 * Returns OID if conversion found in search path, else InvalidOid.
1117 * This is essentially the same as RelnameGetRelid.
1120 ConversionGetConid(const char *conname)
1125 recomputeNamespacePath();
1127 foreach(l, namespaceSearchPath)
1129 Oid namespaceId = lfirst_oid(l);
1131 conid = GetSysCacheOid(CONNAMENSP,
1132 PointerGetDatum(conname),
1133 ObjectIdGetDatum(namespaceId),
1135 if (OidIsValid(conid))
1139 /* Not found in path */
1144 * ConversionIsVisible
1145 * Determine whether a conversion (identified by OID) is visible in the
1146 * current search path. Visible means "would be found by searching
1147 * for the unqualified conversion name".
1150 ConversionIsVisible(Oid conid)
1153 Form_pg_conversion conform;
1157 contup = SearchSysCache(CONOID,
1158 ObjectIdGetDatum(conid),
1160 if (!HeapTupleIsValid(contup))
1161 elog(ERROR, "cache lookup failed for conversion %u", conid);
1162 conform = (Form_pg_conversion) GETSTRUCT(contup);
1164 recomputeNamespacePath();
1167 * Quick check: if it ain't in the path at all, it ain't visible.
1168 * Items in the system namespace are surely in the path and so we
1169 * needn't even do list_member_oid() for them.
1171 connamespace = conform->connamespace;
1172 if (connamespace != PG_CATALOG_NAMESPACE &&
1173 !list_member_oid(namespaceSearchPath, connamespace))
1178 * If it is in the path, it might still not be visible; it could
1179 * be hidden by another conversion of the same name earlier in the
1180 * path. So we must do a slow check to see if this conversion
1181 * would be found by ConversionGetConid.
1183 char *conname = NameStr(conform->conname);
1185 visible = (ConversionGetConid(conname) == conid);
1188 ReleaseSysCache(contup);
1194 * DeconstructQualifiedName
1195 * Given a possibly-qualified name expressed as a list of String nodes,
1196 * extract the schema name and object name.
1198 * *nspname_p is set to NULL if there is no explicit schema name.
1201 DeconstructQualifiedName(List *names,
1206 char *schemaname = NULL;
1207 char *objname = NULL;
1209 switch (list_length(names))
1212 objname = strVal(linitial(names));
1215 schemaname = strVal(linitial(names));
1216 objname = strVal(lsecond(names));
1219 catalogname = strVal(linitial(names));
1220 schemaname = strVal(lsecond(names));
1221 objname = strVal(lthird(names));
1224 * We check the catalog name and then ignore it.
1226 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
1228 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1229 errmsg("cross-database references are not implemented: %s",
1230 NameListToString(names))));
1234 (errcode(ERRCODE_SYNTAX_ERROR),
1235 errmsg("improper qualified name (too many dotted names): %s",
1236 NameListToString(names))));
1240 *nspname_p = schemaname;
1241 *objname_p = objname;
1245 * LookupExplicitNamespace
1246 * Process an explicitly-specified schema name: look up the schema
1247 * and verify we have USAGE (lookup) rights in it.
1249 * Returns the namespace OID. Raises ereport if any problem.
1252 LookupExplicitNamespace(const char *nspname)
1255 AclResult aclresult;
1257 namespaceId = GetSysCacheOid(NAMESPACENAME,
1258 CStringGetDatum(nspname),
1260 if (!OidIsValid(namespaceId))
1262 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1263 errmsg("schema \"%s\" does not exist", nspname)));
1265 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1266 if (aclresult != ACLCHECK_OK)
1267 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1274 * LookupCreationNamespace
1275 * Look up the schema and verify we have CREATE rights on it.
1277 * This is just like LookupExplicitNamespace except for the permission check.
1280 LookupCreationNamespace(const char *nspname)
1283 AclResult aclresult;
1285 namespaceId = GetSysCacheOid(NAMESPACENAME,
1286 CStringGetDatum(nspname),
1288 if (!OidIsValid(namespaceId))
1290 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1291 errmsg("schema \"%s\" does not exist", nspname)));
1293 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
1294 if (aclresult != ACLCHECK_OK)
1295 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1302 * QualifiedNameGetCreationNamespace
1303 * Given a possibly-qualified name for an object (in List-of-Values
1304 * format), determine what namespace the object should be created in.
1305 * Also extract and return the object name (last component of list).
1307 * Note: this does not apply any permissions check. Callers must check
1308 * for CREATE rights on the selected namespace when appropriate.
1310 * This is *not* used for tables. Hence, the TEMP table namespace is
1311 * never selected as the creation target.
1314 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1320 /* deconstruct the name list */
1321 DeconstructQualifiedName(names, &schemaname, &objname);
1325 /* use exact schema given */
1326 namespaceId = GetSysCacheOid(NAMESPACENAME,
1327 CStringGetDatum(schemaname),
1329 if (!OidIsValid(namespaceId))
1331 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1332 errmsg("schema \"%s\" does not exist", schemaname)));
1333 /* we do not check for USAGE rights here! */
1337 /* use the default creation namespace */
1338 recomputeNamespacePath();
1339 namespaceId = defaultCreationNamespace;
1340 if (!OidIsValid(namespaceId))
1342 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1343 errmsg("no schema has been selected to create in")));
1346 *objname_p = objname;
1351 * makeRangeVarFromNameList
1352 * Utility routine to convert a qualified-name list into RangeVar form.
1355 makeRangeVarFromNameList(List *names)
1357 RangeVar *rel = makeRangeVar(NULL, NULL);
1359 switch (list_length(names))
1362 rel->relname = strVal(linitial(names));
1365 rel->schemaname = strVal(linitial(names));
1366 rel->relname = strVal(lsecond(names));
1369 rel->catalogname = strVal(linitial(names));
1370 rel->schemaname = strVal(lsecond(names));
1371 rel->relname = strVal(lthird(names));
1375 (errcode(ERRCODE_SYNTAX_ERROR),
1376 errmsg("improper relation name (too many dotted names): %s",
1377 NameListToString(names))));
1386 * Utility routine to convert a qualified-name list into a string.
1388 * This is used primarily to form error messages, and so we do not quote
1389 * the list elements, for the sake of legibility.
1392 NameListToString(List *names)
1394 StringInfoData string;
1397 initStringInfo(&string);
1401 if (l != list_head(names))
1402 appendStringInfoChar(&string, '.');
1403 appendStringInfoString(&string, strVal(lfirst(l)));
1410 * NameListToQuotedString
1411 * Utility routine to convert a qualified-name list into a string.
1413 * Same as above except that names will be double-quoted where necessary,
1414 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1417 NameListToQuotedString(List *names)
1419 StringInfoData string;
1422 initStringInfo(&string);
1426 if (l != list_head(names))
1427 appendStringInfoChar(&string, '.');
1428 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1435 * isTempNamespace - is the given namespace my temporary-table namespace?
1438 isTempNamespace(Oid namespaceId)
1440 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1446 * isAnyTempNamespace - is the given namespace a temporary-table namespace
1447 * (either my own, or another backend's)?
1450 isAnyTempNamespace(Oid namespaceId)
1455 /* If the namespace name starts with "pg_temp_", say "true" */
1456 nspname = get_namespace_name(namespaceId);
1458 return false; /* no such namespace? */
1459 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1465 * isOtherTempNamespace - is the given namespace some other backend's
1466 * temporary-table namespace?
1469 isOtherTempNamespace(Oid namespaceId)
1471 /* If it's my own temp namespace, say "false" */
1472 if (isTempNamespace(namespaceId))
1474 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1475 return isAnyTempNamespace(namespaceId);
1479 * PushSpecialNamespace - push a "special" namespace onto the front of the
1482 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1483 * Although the API is defined to allow a stack of pushed namespaces, we
1484 * presently only support one at a time.
1486 * The pushed namespace will be removed from the search path at end of
1487 * transaction, whether commit or abort.
1490 PushSpecialNamespace(Oid namespaceId)
1492 Assert(!OidIsValid(mySpecialNamespace));
1493 mySpecialNamespace = namespaceId;
1494 namespaceSearchPathValid = false;
1498 * PopSpecialNamespace - remove previously pushed special namespace.
1501 PopSpecialNamespace(Oid namespaceId)
1503 Assert(mySpecialNamespace == namespaceId);
1504 mySpecialNamespace = InvalidOid;
1505 namespaceSearchPathValid = false;
1509 * FindConversionByName - find a conversion by possibly qualified name
1512 FindConversionByName(List *name)
1515 char *conversion_name;
1520 /* deconstruct the name list */
1521 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1525 /* use exact schema given */
1526 namespaceId = LookupExplicitNamespace(schemaname);
1527 return FindConversion(conversion_name, namespaceId);
1531 /* search for it in search path */
1532 recomputeNamespacePath();
1534 foreach(l, namespaceSearchPath)
1536 namespaceId = lfirst_oid(l);
1537 conoid = FindConversion(conversion_name, namespaceId);
1538 if (OidIsValid(conoid))
1543 /* Not found in path */
1548 * FindDefaultConversionProc - find default encoding conversion proc
1551 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1556 recomputeNamespacePath();
1558 foreach(l, namespaceSearchPath)
1560 Oid namespaceId = lfirst_oid(l);
1562 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1563 if (OidIsValid(proc))
1567 /* Not found in path */
1572 * recomputeNamespacePath - recompute path derived variables if needed.
1575 recomputeNamespacePath(void)
1577 Oid roleid = GetUserId();
1584 MemoryContext oldcxt;
1587 * Do nothing if path is already valid.
1589 if (namespaceSearchPathValid && namespaceUser == roleid)
1592 /* Need a modifiable copy of namespace_search_path string */
1593 rawname = pstrdup(namespace_search_path);
1595 /* Parse string into list of identifiers */
1596 if (!SplitIdentifierString(rawname, ',', &namelist))
1598 /* syntax error in name list */
1599 /* this should not happen if GUC checked check_search_path */
1600 elog(ERROR, "invalid list syntax");
1604 * Convert the list of names to a list of OIDs. If any names are not
1605 * recognizable or we don't have read access, just leave them out of
1606 * the list. (We can't raise an error, since the search_path setting
1607 * has already been accepted.) Don't make duplicate entries, either.
1610 foreach(l, namelist)
1612 char *curname = (char *) lfirst(l);
1615 if (strcmp(curname, "$user") == 0)
1617 /* $user --- substitute namespace matching user name, if any */
1620 tuple = SearchSysCache(AUTHOID,
1621 ObjectIdGetDatum(roleid),
1623 if (HeapTupleIsValid(tuple))
1627 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
1628 namespaceId = GetSysCacheOid(NAMESPACENAME,
1629 CStringGetDatum(rname),
1631 ReleaseSysCache(tuple);
1632 if (OidIsValid(namespaceId) &&
1633 !list_member_oid(oidlist, namespaceId) &&
1634 pg_namespace_aclcheck(namespaceId, roleid,
1635 ACL_USAGE) == ACLCHECK_OK)
1636 oidlist = lappend_oid(oidlist, namespaceId);
1641 /* normal namespace reference */
1642 namespaceId = GetSysCacheOid(NAMESPACENAME,
1643 CStringGetDatum(curname),
1645 if (OidIsValid(namespaceId) &&
1646 !list_member_oid(oidlist, namespaceId) &&
1647 pg_namespace_aclcheck(namespaceId, roleid,
1648 ACL_USAGE) == ACLCHECK_OK)
1649 oidlist = lappend_oid(oidlist, namespaceId);
1654 * Remember the first member of the explicit list.
1657 firstNS = InvalidOid;
1659 firstNS = linitial_oid(oidlist);
1662 * Add any implicitly-searched namespaces to the list. Note these go
1663 * on the front, not the back; also notice that we do not check USAGE
1664 * permissions for these.
1666 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
1667 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
1669 if (OidIsValid(myTempNamespace) &&
1670 !list_member_oid(oidlist, myTempNamespace))
1671 oidlist = lcons_oid(myTempNamespace, oidlist);
1673 if (OidIsValid(mySpecialNamespace) &&
1674 !list_member_oid(oidlist, mySpecialNamespace))
1675 oidlist = lcons_oid(mySpecialNamespace, oidlist);
1678 * Now that we've successfully built the new list of namespace OIDs,
1679 * save it in permanent storage.
1681 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1682 newpath = list_copy(oidlist);
1683 MemoryContextSwitchTo(oldcxt);
1685 /* Now safe to assign to state variable. */
1686 list_free(namespaceSearchPath);
1687 namespaceSearchPath = newpath;
1690 * Update info derived from search path.
1692 firstExplicitNamespace = firstNS;
1693 if (OidIsValid(mySpecialNamespace))
1694 defaultCreationNamespace = mySpecialNamespace;
1696 defaultCreationNamespace = firstNS;
1698 /* Mark the path valid. */
1699 namespaceSearchPathValid = true;
1700 namespaceUser = roleid;
1704 list_free(namelist);
1709 * InitTempTableNamespace
1710 * Initialize temp table namespace on first use in a particular backend
1713 InitTempTableNamespace(void)
1715 char namespaceName[NAMEDATALEN];
1719 * First, do permission check to see if we are authorized to make temp
1720 * tables. We use a nonstandard error message here since
1721 * "databasename: permission denied" might be a tad cryptic.
1723 * Note that ACL_CREATE_TEMP rights are rechecked in
1724 * pg_namespace_aclmask; that's necessary since current user ID could
1725 * change during the session. But there's no need to make the
1726 * namespace in the first place until a temp table creation request is
1727 * made by someone with appropriate rights.
1729 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
1730 ACL_CREATE_TEMP) != ACLCHECK_OK)
1732 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1733 errmsg("permission denied to create temporary tables in database \"%s\"",
1734 get_database_name(MyDatabaseId))));
1736 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1738 namespaceId = GetSysCacheOid(NAMESPACENAME,
1739 CStringGetDatum(namespaceName),
1741 if (!OidIsValid(namespaceId))
1744 * First use of this temp namespace in this database; create it.
1745 * The temp namespaces are always owned by the superuser. We
1746 * leave their permissions at default --- i.e., no access except
1747 * to superuser --- to ensure that unprivileged users can't peek
1748 * at other backends' temp tables. This works because the places
1749 * that access the temp namespace for my own backend skip
1750 * permissions checks on it.
1752 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
1753 /* Advance command counter to make namespace visible */
1754 CommandCounterIncrement();
1759 * If the namespace already exists, clean it out (in case the
1760 * former owner crashed without doing so).
1762 RemoveTempRelations(namespaceId);
1766 * Okay, we've prepared the temp namespace ... but it's not committed
1767 * yet, so all our work could be undone by transaction rollback. Set
1768 * flag for AtEOXact_Namespace to know what to do.
1770 myTempNamespace = namespaceId;
1772 /* It should not be done already. */
1773 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
1774 myTempNamespaceSubID = GetCurrentSubTransactionId();
1776 namespaceSearchPathValid = false; /* need to rebuild list */
1780 * End-of-transaction cleanup for namespaces.
1783 AtEOXact_Namespace(bool isCommit)
1786 * If we abort the transaction in which a temp namespace was selected,
1787 * we'll have to do any creation or cleanout work over again. So,
1788 * just forget the namespace entirely until next time. On the other
1789 * hand, if we commit then register an exit callback to clean out the
1790 * temp tables at backend shutdown. (We only want to register the
1791 * callback once per session, so this is a good place to do it.)
1793 if (myTempNamespaceSubID != InvalidSubTransactionId)
1796 on_shmem_exit(RemoveTempRelationsCallback, 0);
1799 myTempNamespace = InvalidOid;
1800 namespaceSearchPathValid = false; /* need to rebuild list */
1802 myTempNamespaceSubID = InvalidSubTransactionId;
1806 * Clean up if someone failed to do PopSpecialNamespace
1808 if (OidIsValid(mySpecialNamespace))
1810 mySpecialNamespace = InvalidOid;
1811 namespaceSearchPathValid = false; /* need to rebuild list */
1816 * AtEOSubXact_Namespace
1818 * At subtransaction commit, propagate the temp-namespace-creation
1819 * flag to the parent subtransaction.
1821 * At subtransaction abort, forget the flag if we set it up.
1824 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
1825 SubTransactionId parentSubid)
1827 if (myTempNamespaceSubID == mySubid)
1830 myTempNamespaceSubID = parentSubid;
1833 myTempNamespaceSubID = InvalidSubTransactionId;
1834 /* TEMP namespace creation failed, so reset state */
1835 myTempNamespace = InvalidOid;
1836 namespaceSearchPathValid = false; /* need to rebuild list */
1842 * Remove all relations in the specified temp namespace.
1844 * This is called at backend shutdown (if we made any temp relations).
1845 * It is also called when we begin using a pre-existing temp namespace,
1846 * in order to clean out any relations that might have been created by
1847 * a crashed backend.
1850 RemoveTempRelations(Oid tempNamespaceId)
1852 ObjectAddress object;
1855 * We want to get rid of everything in the target namespace, but not
1856 * the namespace itself (deleting it only to recreate it later would
1857 * be a waste of cycles). We do this by finding everything that has a
1858 * dependency on the namespace.
1860 object.classId = NamespaceRelationId;
1861 object.objectId = tempNamespaceId;
1862 object.objectSubId = 0;
1864 deleteWhatDependsOn(&object, false);
1868 * Callback to remove temp relations at backend exit.
1871 RemoveTempRelationsCallback(int code, Datum arg)
1873 if (OidIsValid(myTempNamespace)) /* should always be true */
1875 /* Need to ensure we have a usable transaction. */
1876 AbortOutOfAnyTransaction();
1877 StartTransactionCommand();
1879 RemoveTempRelations(myTempNamespace);
1881 CommitTransactionCommand();
1887 * Routines for handling the GUC variable 'search_path'.
1890 /* assign_hook: validate new search_path, do extra actions as needed */
1892 assign_search_path(const char *newval, bool doit, GucSource source)
1898 /* Need a modifiable copy of string */
1899 rawname = pstrdup(newval);
1901 /* Parse string into list of identifiers */
1902 if (!SplitIdentifierString(rawname, ',', &namelist))
1904 /* syntax error in name list */
1906 list_free(namelist);
1911 * If we aren't inside a transaction, we cannot do database access so
1912 * cannot verify the individual names. Must accept the list on faith.
1914 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
1917 * Verify that all the names are either valid namespace names or
1918 * "$user". We do not require $user to correspond to a valid
1919 * namespace. We do not check for USAGE rights, either; should
1922 * When source == PGC_S_TEST, we are checking the argument of an
1923 * ALTER DATABASE SET or ALTER USER SET command. It could be that
1924 * the intended use of the search path is for some other database,
1925 * so we should not error out if it mentions schemas not present
1926 * in the current database. We reduce the message to NOTICE
1929 foreach(l, namelist)
1931 char *curname = (char *) lfirst(l);
1933 if (strcmp(curname, "$user") == 0)
1935 if (!SearchSysCacheExists(NAMESPACENAME,
1936 CStringGetDatum(curname),
1938 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
1939 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1940 errmsg("schema \"%s\" does not exist", curname)));
1945 list_free(namelist);
1948 * We mark the path as needing recomputation, but don't do anything
1949 * until it's needed. This avoids trying to do database access during
1950 * GUC initialization.
1953 namespaceSearchPathValid = false;
1959 * InitializeSearchPath: initialize module during InitPostgres.
1961 * This is called after we are up enough to be able to do catalog lookups.
1964 InitializeSearchPath(void)
1966 if (IsBootstrapProcessingMode())
1969 * In bootstrap mode, the search path must be 'pg_catalog' so that
1970 * tables are created in the proper namespace; ignore the GUC
1973 MemoryContext oldcxt;
1975 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1976 namespaceSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
1977 MemoryContextSwitchTo(oldcxt);
1978 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1979 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1980 namespaceSearchPathValid = true;
1981 namespaceUser = GetUserId();
1986 * In normal mode, arrange for a callback on any syscache
1987 * invalidation of pg_namespace rows.
1989 CacheRegisterSyscacheCallback(NAMESPACEOID,
1992 /* Force search path to be recomputed on next use */
1993 namespaceSearchPathValid = false;
1999 * Syscache inval callback function
2002 NamespaceCallback(Datum arg, Oid relid)
2004 /* Force search path to be recomputed on next use */
2005 namespaceSearchPathValid = false;
2009 * Fetch the active search path. The return value is a palloc'ed list
2010 * of OIDs; the caller is responsible for freeing this storage as
2013 * The returned list includes the implicitly-prepended namespaces only if
2014 * includeImplicit is true.
2017 fetch_search_path(bool includeImplicit)
2021 recomputeNamespacePath();
2023 result = list_copy(namespaceSearchPath);
2024 if (!includeImplicit)
2026 while (result && linitial_oid(result) != firstExplicitNamespace)
2027 result = list_delete_first(result);
2034 * Export the FooIsVisible functions as SQL-callable functions.
2038 pg_table_is_visible(PG_FUNCTION_ARGS)
2040 Oid oid = PG_GETARG_OID(0);
2042 PG_RETURN_BOOL(RelationIsVisible(oid));
2046 pg_type_is_visible(PG_FUNCTION_ARGS)
2048 Oid oid = PG_GETARG_OID(0);
2050 PG_RETURN_BOOL(TypeIsVisible(oid));
2054 pg_function_is_visible(PG_FUNCTION_ARGS)
2056 Oid oid = PG_GETARG_OID(0);
2058 PG_RETURN_BOOL(FunctionIsVisible(oid));
2062 pg_operator_is_visible(PG_FUNCTION_ARGS)
2064 Oid oid = PG_GETARG_OID(0);
2066 PG_RETURN_BOOL(OperatorIsVisible(oid));
2070 pg_opclass_is_visible(PG_FUNCTION_ARGS)
2072 Oid oid = PG_GETARG_OID(0);
2074 PG_RETURN_BOOL(OpclassIsVisible(oid));
2078 pg_conversion_is_visible(PG_FUNCTION_ARGS)
2080 Oid oid = PG_GETARG_OID(0);
2082 PG_RETURN_BOOL(ConversionIsVisible(oid));