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-2002, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
16 * $Header: /cvsroot/pgsql/src/backend/catalog/namespace.c,v 1.33 2002/08/30 22:18:05 tgl Exp $
18 *-------------------------------------------------------------------------
22 #include "access/heapam.h"
23 #include "access/xact.h"
24 #include "catalog/catalog.h"
25 #include "catalog/catname.h"
26 #include "catalog/dependency.h"
27 #include "catalog/heap.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_conversion.h"
30 #include "catalog/pg_inherits.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_operator.h"
34 #include "catalog/pg_proc.h"
35 #include "catalog/pg_shadow.h"
36 #include "catalog/pg_type.h"
37 #include "lib/stringinfo.h"
38 #include "miscadmin.h"
39 #include "nodes/makefuncs.h"
40 #include "storage/backendid.h"
41 #include "storage/ipc.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/catcache.h"
45 #include "utils/fmgroids.h"
46 #include "utils/guc.h"
47 #include "utils/inval.h"
48 #include "utils/lsyscache.h"
49 #include "utils/syscache.h"
53 * The namespace search path is a possibly-empty list of namespace OIDs.
54 * In addition to the explicit list, several implicitly-searched namespaces
57 * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
58 * always searched first. (This is a hack for CREATE SCHEMA.)
60 * 2. If a TEMP table namespace has been initialized in this session, it
61 * is always searched just after any special namespace.
63 * 3. The system catalog namespace is always searched. If the system
64 * namespace is present in the explicit path then it will be searched in
65 * the specified order; otherwise it will be searched after TEMP tables and
66 * *before* the explicit list. (It might seem that the system namespace
67 * should be implicitly last, but this behavior appears to be required by
68 * SQL99. Also, this provides a way to search the system namespace first
69 * without thereby making it the default creation target namespace.)
71 * The default creation target namespace is normally equal to the first
72 * element of the explicit list, but is the "special" namespace when one
73 * has been set. If the explicit list is empty and there is no special
74 * namespace, there is no default target.
76 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
77 * the system namespace is the only one searched or inserted into.
78 * The initdb script is also careful to set search_path to 'pg_catalog' for
79 * its post-bootstrap standalone backend runs. Otherwise the default search
80 * path is determined by GUC. The factory default path contains the PUBLIC
81 * namespace (if it exists), preceded by the user's personal namespace
84 * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
85 * derived variables) need to be recomputed from namespace_search_path.
86 * We mark it invalid upon an assignment to namespace_search_path or receipt
87 * of a syscache invalidation event for pg_namespace. The recomputation
88 * is done during the next lookup attempt.
90 * Any namespaces mentioned in namespace_search_path that are not readable
91 * by the current user ID are simply left out of namespaceSearchPath; so
92 * we have to be willing to recompute the path when current userid changes.
93 * namespaceUser is the userid the path has been computed for.
96 static List *namespaceSearchPath = NIL;
98 static Oid namespaceUser = InvalidOid;
100 /* default place to create stuff; if InvalidOid, no default */
101 static Oid defaultCreationNamespace = InvalidOid;
103 /* first explicit member of list; usually same as defaultCreationNamespace */
104 static Oid firstExplicitNamespace = InvalidOid;
106 /* The above four values are valid only if namespaceSearchPathValid */
107 static bool namespaceSearchPathValid = true;
110 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
111 * in a particular backend session (this happens when a CREATE TEMP TABLE
112 * command is first executed). Thereafter it's the OID of the temp namespace.
113 * firstTempTransaction flags whether we've committed creation of the TEMP
116 static Oid myTempNamespace = InvalidOid;
118 static bool firstTempTransaction = false;
121 * "Special" namespace for CREATE SCHEMA. If set, it's the first search
122 * path element, and also the default creation namespace.
124 static Oid mySpecialNamespace = InvalidOid;
127 * This is the text equivalent of the search path --- it's the value
128 * of the GUC variable 'search_path'.
130 char *namespace_search_path = NULL;
133 /* Local functions */
134 static void recomputeNamespacePath(void);
135 static void InitTempTableNamespace(void);
136 static void RemoveTempRelations(Oid tempNamespaceId);
137 static void RemoveTempRelationsCallback(void);
138 static void NamespaceCallback(Datum arg, Oid relid);
140 /* These don't really need to appear in any header file */
141 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
142 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
143 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
144 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
145 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
150 * Given a RangeVar describing an existing relation,
151 * select the proper namespace and look up the relation OID.
153 * If the relation is not found, return InvalidOid if failOK = true,
154 * otherwise raise an error.
157 RangeVarGetRelid(const RangeVar *relation, bool failOK)
163 * We check the catalog name and then ignore it.
165 if (relation->catalogname)
167 if (strcmp(relation->catalogname, DatabaseName) != 0)
168 elog(ERROR, "Cross-database references are not implemented");
171 if (relation->schemaname)
173 /* use exact schema given */
174 namespaceId = LookupExplicitNamespace(relation->schemaname);
175 relId = get_relname_relid(relation->relname, namespaceId);
179 /* search the namespace path */
180 relId = RelnameGetRelid(relation->relname);
183 if (!OidIsValid(relId) && !failOK)
185 if (relation->schemaname)
186 elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
187 relation->schemaname, relation->relname);
189 elog(ERROR, "Relation \"%s\" does not exist",
196 * RangeVarGetCreationNamespace
197 * Given a RangeVar describing a to-be-created relation,
198 * choose which namespace to create it in.
200 * Note: calling this may result in a CommandCounterIncrement operation.
201 * That will happen on the first request for a temp table in any particular
202 * backend run; we will need to either create or clean out the temp schema.
205 RangeVarGetCreationNamespace(const RangeVar *newRelation)
210 * We check the catalog name and then ignore it.
212 if (newRelation->catalogname)
214 if (strcmp(newRelation->catalogname, DatabaseName) != 0)
215 elog(ERROR, "Cross-database references are not implemented");
218 if (newRelation->istemp)
220 /* TEMP tables are created in our backend-local temp namespace */
221 if (newRelation->schemaname)
222 elog(ERROR, "TEMP tables may not specify a namespace");
223 /* Initialize temp namespace if first time through */
224 if (!OidIsValid(myTempNamespace))
225 InitTempTableNamespace();
226 return myTempNamespace;
229 if (newRelation->schemaname)
231 /* use exact schema given */
232 namespaceId = GetSysCacheOid(NAMESPACENAME,
233 CStringGetDatum(newRelation->schemaname),
235 if (!OidIsValid(namespaceId))
236 elog(ERROR, "Namespace \"%s\" does not exist",
237 newRelation->schemaname);
238 /* we do not check for USAGE rights here! */
242 /* use the default creation namespace */
243 recomputeNamespacePath();
244 namespaceId = defaultCreationNamespace;
245 if (!OidIsValid(namespaceId))
246 elog(ERROR, "No namespace has been selected to create in");
249 /* Note: callers will check for CREATE rights when appropriate */
256 * Try to resolve an unqualified relation name.
257 * Returns OID if relation found in search path, else InvalidOid.
260 RelnameGetRelid(const char *relname)
265 recomputeNamespacePath();
267 foreach(lptr, namespaceSearchPath)
269 Oid namespaceId = (Oid) lfirsti(lptr);
271 relid = get_relname_relid(relname, namespaceId);
272 if (OidIsValid(relid))
276 /* Not found in path */
282 * Determine whether a relation (identified by OID) is visible in the
283 * current search path. Visible means "would be found by searching
284 * for the unqualified relation name".
287 RelationIsVisible(Oid relid)
290 Form_pg_class relform;
294 reltup = SearchSysCache(RELOID,
295 ObjectIdGetDatum(relid),
297 if (!HeapTupleIsValid(reltup))
298 elog(ERROR, "Cache lookup failed for relation %u", relid);
299 relform = (Form_pg_class) GETSTRUCT(reltup);
301 recomputeNamespacePath();
304 * Quick check: if it ain't in the path at all, it ain't visible.
305 * Items in the system namespace are surely in the path and so we
306 * needn't even do intMember() for them.
308 relnamespace = relform->relnamespace;
309 if (relnamespace != PG_CATALOG_NAMESPACE &&
310 !intMember(relnamespace, namespaceSearchPath))
315 * If it is in the path, it might still not be visible; it could be
316 * hidden by another relation of the same name earlier in the path.
317 * So we must do a slow check to see if this rel would be found by
320 char *relname = NameStr(relform->relname);
322 visible = (RelnameGetRelid(relname) == relid);
325 ReleaseSysCache(reltup);
333 * Try to resolve an unqualified datatype name.
334 * Returns OID if type found in search path, else InvalidOid.
336 * This is essentially the same as RelnameGetRelid.
339 TypenameGetTypid(const char *typname)
344 recomputeNamespacePath();
346 foreach(lptr, namespaceSearchPath)
348 Oid namespaceId = (Oid) lfirsti(lptr);
350 typid = GetSysCacheOid(TYPENAMENSP,
351 PointerGetDatum(typname),
352 ObjectIdGetDatum(namespaceId),
354 if (OidIsValid(typid))
358 /* Not found in path */
364 * Determine whether a type (identified by OID) is visible in the
365 * current search path. Visible means "would be found by searching
366 * for the unqualified type name".
369 TypeIsVisible(Oid typid)
372 Form_pg_type typform;
376 typtup = SearchSysCache(TYPEOID,
377 ObjectIdGetDatum(typid),
379 if (!HeapTupleIsValid(typtup))
380 elog(ERROR, "Cache lookup failed for type %u", typid);
381 typform = (Form_pg_type) GETSTRUCT(typtup);
383 recomputeNamespacePath();
386 * Quick check: if it ain't in the path at all, it ain't visible.
387 * Items in the system namespace are surely in the path and so we
388 * needn't even do intMember() for them.
390 typnamespace = typform->typnamespace;
391 if (typnamespace != PG_CATALOG_NAMESPACE &&
392 !intMember(typnamespace, namespaceSearchPath))
397 * If it is in the path, it might still not be visible; it could be
398 * hidden by another type of the same name earlier in the path.
399 * So we must do a slow check to see if this type would be found by
402 char *typname = NameStr(typform->typname);
404 visible = (TypenameGetTypid(typname) == typid);
407 ReleaseSysCache(typtup);
414 * FuncnameGetCandidates
415 * Given a possibly-qualified function name and argument count,
416 * retrieve a list of the possible matches.
418 * If nargs is -1, we return all functions matching the given name,
419 * regardless of argument count.
421 * We search a single namespace if the function name is qualified, else
422 * all namespaces in the search path. The return list will never contain
423 * multiple entries with identical argument lists --- in the multiple-
424 * namespace case, we arrange for entries in earlier namespaces to mask
425 * identical entries in later namespaces.
428 FuncnameGetCandidates(List *names, int nargs)
430 FuncCandidateList resultList = NULL;
437 /* deconstruct the name list */
438 DeconstructQualifiedName(names, &schemaname, &funcname);
442 /* use exact schema given */
443 namespaceId = LookupExplicitNamespace(schemaname);
447 /* flag to indicate we need namespace search */
448 namespaceId = InvalidOid;
449 recomputeNamespacePath();
452 /* Search syscache by name and (optionally) nargs only */
454 catlist = SearchSysCacheList(PROCNAMENSP, 2,
455 CStringGetDatum(funcname),
456 Int16GetDatum(nargs),
459 catlist = SearchSysCacheList(PROCNAMENSP, 1,
460 CStringGetDatum(funcname),
463 for (i = 0; i < catlist->n_members; i++)
465 HeapTuple proctup = &catlist->members[i]->tuple;
466 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
468 FuncCandidateList newResult;
470 nargs = procform->pronargs;
472 if (OidIsValid(namespaceId))
474 /* Consider only procs in specified namespace */
475 if (procform->pronamespace != namespaceId)
477 /* No need to check args, they must all be different */
481 /* Consider only procs that are in the search path */
484 foreach(nsp, namespaceSearchPath)
486 if (procform->pronamespace == (Oid) lfirsti(nsp))
491 continue; /* proc is not in search path */
494 * Okay, it's in the search path, but does it have the same
495 * arguments as something we already accepted? If so, keep
496 * only the one that appears earlier in the search path.
498 * If we have an ordered list from SearchSysCacheList (the
499 * normal case), then any conflicting proc must immediately
500 * adjoin this one in the list, so we only need to look at
501 * the newest result item. If we have an unordered list,
502 * we have to scan the whole result list.
506 FuncCandidateList prevResult;
508 if (catlist->ordered)
510 if (nargs == resultList->nargs &&
511 memcmp(procform->proargtypes, resultList->args,
512 nargs * sizeof(Oid)) == 0)
513 prevResult = resultList;
519 for (prevResult = resultList;
521 prevResult = prevResult->next)
523 if (nargs == prevResult->nargs &&
524 memcmp(procform->proargtypes, prevResult->args,
525 nargs * sizeof(Oid)) == 0)
531 /* We have a match with a previous result */
532 Assert(pathpos != prevResult->pathpos);
533 if (pathpos > prevResult->pathpos)
534 continue; /* keep previous result */
535 /* replace previous result */
536 prevResult->pathpos = pathpos;
537 prevResult->oid = HeapTupleGetOid(proctup);
538 continue; /* args are same, of course */
544 * Okay to add it to result list
546 newResult = (FuncCandidateList)
547 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
548 + nargs * sizeof(Oid));
549 newResult->pathpos = pathpos;
550 newResult->oid = HeapTupleGetOid(proctup);
551 newResult->nargs = nargs;
552 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
554 newResult->next = resultList;
555 resultList = newResult;
558 ReleaseSysCacheList(catlist);
565 * Determine whether a function (identified by OID) is visible in the
566 * current search path. Visible means "would be found by searching
567 * for the unqualified function name with exact argument matches".
570 FunctionIsVisible(Oid funcid)
573 Form_pg_proc procform;
577 proctup = SearchSysCache(PROCOID,
578 ObjectIdGetDatum(funcid),
580 if (!HeapTupleIsValid(proctup))
581 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
582 procform = (Form_pg_proc) GETSTRUCT(proctup);
584 recomputeNamespacePath();
587 * Quick check: if it ain't in the path at all, it ain't visible.
588 * Items in the system namespace are surely in the path and so we
589 * needn't even do intMember() for them.
591 pronamespace = procform->pronamespace;
592 if (pronamespace != PG_CATALOG_NAMESPACE &&
593 !intMember(pronamespace, namespaceSearchPath))
598 * If it is in the path, it might still not be visible; it could be
599 * hidden by another proc of the same name and arguments earlier
600 * in the path. So we must do a slow check to see if this is the
601 * same proc that would be found by FuncnameGetCandidates.
603 char *proname = NameStr(procform->proname);
604 int nargs = procform->pronargs;
605 FuncCandidateList clist;
609 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
611 for (; clist; clist = clist->next)
613 if (memcmp(clist->args, procform->proargtypes,
614 nargs * sizeof(Oid)) == 0)
616 /* Found the expected entry; is it the right proc? */
617 visible = (clist->oid == funcid);
623 ReleaseSysCache(proctup);
630 * OpernameGetCandidates
631 * Given a possibly-qualified operator name and operator kind,
632 * retrieve a list of the possible matches.
634 * If oprkind is '\0', we return all operators matching the given name,
635 * regardless of arguments.
637 * We search a single namespace if the operator name is qualified, else
638 * all namespaces in the search path. The return list will never contain
639 * multiple entries with identical argument lists --- in the multiple-
640 * namespace case, we arrange for entries in earlier namespaces to mask
641 * identical entries in later namespaces.
643 * The returned items always have two args[] entries --- one or the other
644 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
647 OpernameGetCandidates(List *names, char oprkind)
649 FuncCandidateList resultList = NULL;
656 /* deconstruct the name list */
657 DeconstructQualifiedName(names, &schemaname, &opername);
661 /* use exact schema given */
662 namespaceId = LookupExplicitNamespace(schemaname);
666 /* flag to indicate we need namespace search */
667 namespaceId = InvalidOid;
668 recomputeNamespacePath();
671 /* Search syscache by name only */
672 catlist = SearchSysCacheList(OPERNAMENSP, 1,
673 CStringGetDatum(opername),
676 for (i = 0; i < catlist->n_members; i++)
678 HeapTuple opertup = &catlist->members[i]->tuple;
679 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
681 FuncCandidateList newResult;
683 /* Ignore operators of wrong kind, if specific kind requested */
684 if (oprkind && operform->oprkind != oprkind)
687 if (OidIsValid(namespaceId))
689 /* Consider only opers in specified namespace */
690 if (operform->oprnamespace != namespaceId)
692 /* No need to check args, they must all be different */
696 /* Consider only opers that are in the search path */
699 foreach(nsp, namespaceSearchPath)
701 if (operform->oprnamespace == (Oid) lfirsti(nsp))
706 continue; /* oper is not in search path */
709 * Okay, it's in the search path, but does it have the same
710 * arguments as something we already accepted? If so, keep
711 * only the one that appears earlier in the search path.
713 * If we have an ordered list from SearchSysCacheList (the
714 * normal case), then any conflicting oper must immediately
715 * adjoin this one in the list, so we only need to look at
716 * the newest result item. If we have an unordered list,
717 * we have to scan the whole result list.
721 FuncCandidateList prevResult;
723 if (catlist->ordered)
725 if (operform->oprleft == resultList->args[0] &&
726 operform->oprright == resultList->args[1])
727 prevResult = resultList;
733 for (prevResult = resultList;
735 prevResult = prevResult->next)
737 if (operform->oprleft == prevResult->args[0] &&
738 operform->oprright == prevResult->args[1])
744 /* We have a match with a previous result */
745 Assert(pathpos != prevResult->pathpos);
746 if (pathpos > prevResult->pathpos)
747 continue; /* keep previous result */
748 /* replace previous result */
749 prevResult->pathpos = pathpos;
750 prevResult->oid = HeapTupleGetOid(opertup);
751 continue; /* args are same, of course */
757 * Okay to add it to result list
759 newResult = (FuncCandidateList)
760 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
761 newResult->pathpos = pathpos;
762 newResult->oid = HeapTupleGetOid(opertup);
763 newResult->nargs = 2;
764 newResult->args[0] = operform->oprleft;
765 newResult->args[1] = operform->oprright;
766 newResult->next = resultList;
767 resultList = newResult;
770 ReleaseSysCacheList(catlist);
777 * Determine whether an operator (identified by OID) is visible in the
778 * current search path. Visible means "would be found by searching
779 * for the unqualified operator name with exact argument matches".
782 OperatorIsVisible(Oid oprid)
785 Form_pg_operator oprform;
789 oprtup = SearchSysCache(OPEROID,
790 ObjectIdGetDatum(oprid),
792 if (!HeapTupleIsValid(oprtup))
793 elog(ERROR, "Cache lookup failed for operator %u", oprid);
794 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
796 recomputeNamespacePath();
799 * Quick check: if it ain't in the path at all, it ain't visible.
800 * Items in the system namespace are surely in the path and so we
801 * needn't even do intMember() for them.
803 oprnamespace = oprform->oprnamespace;
804 if (oprnamespace != PG_CATALOG_NAMESPACE &&
805 !intMember(oprnamespace, namespaceSearchPath))
810 * If it is in the path, it might still not be visible; it could be
811 * hidden by another operator of the same name and arguments earlier
812 * in the path. So we must do a slow check to see if this is the
813 * same operator that would be found by OpernameGetCandidates.
815 char *oprname = NameStr(oprform->oprname);
816 FuncCandidateList clist;
820 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
823 for (; clist; clist = clist->next)
825 if (clist->args[0] == oprform->oprleft &&
826 clist->args[1] == oprform->oprright)
828 /* Found the expected entry; is it the right op? */
829 visible = (clist->oid == oprid);
835 ReleaseSysCache(oprtup);
842 * OpclassGetCandidates
843 * Given an index access method OID, retrieve a list of all the
844 * opclasses for that AM that are visible in the search path.
846 * NOTE: the opcname_tmp field in the returned structs should not be used
847 * by callers, because it points at syscache entries that we release at
848 * the end of this routine. If any callers needed the name information,
849 * we could pstrdup() the names ... but at present it'd be wasteful.
852 OpclassGetCandidates(Oid amid)
854 OpclassCandidateList resultList = NULL;
858 /* Search syscache by AM OID only */
859 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
860 ObjectIdGetDatum(amid),
863 recomputeNamespacePath();
865 for (i = 0; i < catlist->n_members; i++)
867 HeapTuple opctup = &catlist->members[i]->tuple;
868 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
870 OpclassCandidateList newResult;
873 /* Consider only opclasses that are in the search path */
874 foreach(nsp, namespaceSearchPath)
876 if (opcform->opcnamespace == (Oid) lfirsti(nsp))
881 continue; /* opclass is not in search path */
884 * Okay, it's in the search path, but does it have the same name
885 * as something we already accepted? If so, keep
886 * only the one that appears earlier in the search path.
888 * If we have an ordered list from SearchSysCacheList (the
889 * normal case), then any conflicting opclass must immediately
890 * adjoin this one in the list, so we only need to look at
891 * the newest result item. If we have an unordered list,
892 * we have to scan the whole result list.
896 OpclassCandidateList prevResult;
898 if (catlist->ordered)
900 if (strcmp(NameStr(opcform->opcname),
901 resultList->opcname_tmp) == 0)
902 prevResult = resultList;
908 for (prevResult = resultList;
910 prevResult = prevResult->next)
912 if (strcmp(NameStr(opcform->opcname),
913 prevResult->opcname_tmp) == 0)
919 /* We have a match with a previous result */
920 Assert(pathpos != prevResult->pathpos);
921 if (pathpos > prevResult->pathpos)
922 continue; /* keep previous result */
923 /* replace previous result */
924 prevResult->opcname_tmp = NameStr(opcform->opcname);
925 prevResult->pathpos = pathpos;
926 prevResult->oid = HeapTupleGetOid(opctup);
927 prevResult->opcintype = opcform->opcintype;
928 prevResult->opcdefault = opcform->opcdefault;
929 prevResult->opckeytype = opcform->opckeytype;
935 * Okay to add it to result list
937 newResult = (OpclassCandidateList)
938 palloc(sizeof(struct _OpclassCandidateList));
939 newResult->opcname_tmp = NameStr(opcform->opcname);
940 newResult->pathpos = pathpos;
941 newResult->oid = HeapTupleGetOid(opctup);
942 newResult->opcintype = opcform->opcintype;
943 newResult->opcdefault = opcform->opcdefault;
944 newResult->opckeytype = opcform->opckeytype;
945 newResult->next = resultList;
946 resultList = newResult;
949 ReleaseSysCacheList(catlist);
955 * OpclassnameGetOpcid
956 * Try to resolve an unqualified index opclass name.
957 * Returns OID if opclass found in search path, else InvalidOid.
959 * This is essentially the same as TypenameGetTypid, but we have to have
960 * an extra argument for the index AM OID.
963 OpclassnameGetOpcid(Oid amid, const char *opcname)
968 recomputeNamespacePath();
970 foreach(lptr, namespaceSearchPath)
972 Oid namespaceId = (Oid) lfirsti(lptr);
974 opcid = GetSysCacheOid(CLAAMNAMENSP,
975 ObjectIdGetDatum(amid),
976 PointerGetDatum(opcname),
977 ObjectIdGetDatum(namespaceId),
979 if (OidIsValid(opcid))
983 /* Not found in path */
989 * Determine whether an opclass (identified by OID) is visible in the
990 * current search path. Visible means "would be found by searching
991 * for the unqualified opclass name".
994 OpclassIsVisible(Oid opcid)
997 Form_pg_opclass opcform;
1001 opctup = SearchSysCache(CLAOID,
1002 ObjectIdGetDatum(opcid),
1004 if (!HeapTupleIsValid(opctup))
1005 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1006 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1008 recomputeNamespacePath();
1011 * Quick check: if it ain't in the path at all, it ain't visible.
1012 * Items in the system namespace are surely in the path and so we
1013 * needn't even do intMember() for them.
1015 opcnamespace = opcform->opcnamespace;
1016 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1017 !intMember(opcnamespace, namespaceSearchPath))
1022 * If it is in the path, it might still not be visible; it could be
1023 * hidden by another opclass of the same name earlier in the path.
1024 * So we must do a slow check to see if this opclass would be found by
1025 * OpclassnameGetOpcid.
1027 char *opcname = NameStr(opcform->opcname);
1029 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1032 ReleaseSysCache(opctup);
1038 * DeconstructQualifiedName
1039 * Given a possibly-qualified name expressed as a list of String nodes,
1040 * extract the schema name and object name.
1042 * *nspname_p is set to NULL if there is no explicit schema name.
1045 DeconstructQualifiedName(List *names,
1050 char *schemaname = NULL;
1051 char *objname = NULL;
1053 switch (length(names))
1056 objname = strVal(lfirst(names));
1059 schemaname = strVal(lfirst(names));
1060 objname = strVal(lsecond(names));
1063 catalogname = strVal(lfirst(names));
1064 schemaname = strVal(lsecond(names));
1065 objname = strVal(lfirst(lnext(lnext(names))));
1067 * We check the catalog name and then ignore it.
1069 if (strcmp(catalogname, DatabaseName) != 0)
1070 elog(ERROR, "Cross-database references are not implemented");
1073 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1074 NameListToString(names));
1078 *nspname_p = schemaname;
1079 *objname_p = objname;
1083 * LookupExplicitNamespace
1084 * Process an explicitly-specified schema name: look up the schema
1085 * and verify we have USAGE (lookup) rights in it.
1087 * Returns the namespace OID. Raises elog if any problem.
1090 LookupExplicitNamespace(const char *nspname)
1093 AclResult aclresult;
1095 namespaceId = GetSysCacheOid(NAMESPACENAME,
1096 CStringGetDatum(nspname),
1098 if (!OidIsValid(namespaceId))
1099 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1101 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1102 if (aclresult != ACLCHECK_OK)
1103 aclcheck_error(aclresult, nspname);
1109 * QualifiedNameGetCreationNamespace
1110 * Given a possibly-qualified name for an object (in List-of-Values
1111 * format), determine what namespace the object should be created in.
1112 * Also extract and return the object name (last component of list).
1114 * This is *not* used for tables. Hence, the TEMP table namespace is
1115 * never selected as the creation target.
1118 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1124 /* deconstruct the name list */
1125 DeconstructQualifiedName(names, &schemaname, &objname);
1129 /* use exact schema given */
1130 namespaceId = GetSysCacheOid(NAMESPACENAME,
1131 CStringGetDatum(schemaname),
1133 if (!OidIsValid(namespaceId))
1134 elog(ERROR, "Namespace \"%s\" does not exist",
1136 /* we do not check for USAGE rights here! */
1140 /* use the default creation namespace */
1141 recomputeNamespacePath();
1142 namespaceId = defaultCreationNamespace;
1143 if (!OidIsValid(namespaceId))
1144 elog(ERROR, "No namespace has been selected to create in");
1147 /* Note: callers will check for CREATE rights when appropriate */
1149 *objname_p = objname;
1154 * makeRangeVarFromNameList
1155 * Utility routine to convert a qualified-name list into RangeVar form.
1158 makeRangeVarFromNameList(List *names)
1160 RangeVar *rel = makeRangeVar(NULL, NULL);
1162 switch (length(names))
1165 rel->relname = strVal(lfirst(names));
1168 rel->schemaname = strVal(lfirst(names));
1169 rel->relname = strVal(lsecond(names));
1172 rel->catalogname = strVal(lfirst(names));
1173 rel->schemaname = strVal(lsecond(names));
1174 rel->relname = strVal(lfirst(lnext(lnext(names))));
1177 elog(ERROR, "Improper relation name (too many dotted names)");
1186 * Utility routine to convert a qualified-name list into a string.
1187 * Used primarily to form error messages.
1190 NameListToString(List *names)
1192 StringInfoData string;
1195 initStringInfo(&string);
1200 appendStringInfoChar(&string, '.');
1201 appendStringInfo(&string, "%s", strVal(lfirst(l)));
1208 * isTempNamespace - is the given namespace my temporary-table namespace?
1211 isTempNamespace(Oid namespaceId)
1213 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1219 * PushSpecialNamespace - push a "special" namespace onto the front of the
1222 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1223 * Although the API is defined to allow a stack of pushed namespaces, we
1224 * presently only support one at a time.
1226 * The pushed namespace will be removed from the search path at end of
1227 * transaction, whether commit or abort.
1230 PushSpecialNamespace(Oid namespaceId)
1232 Assert(!OidIsValid(mySpecialNamespace));
1233 mySpecialNamespace = namespaceId;
1234 namespaceSearchPathValid = false;
1238 * PopSpecialNamespace - remove previously pushed special namespace.
1241 PopSpecialNamespace(Oid namespaceId)
1243 Assert(mySpecialNamespace == namespaceId);
1244 mySpecialNamespace = InvalidOid;
1245 namespaceSearchPathValid = false;
1249 * FindConversionByName - find a conversion by possibly qualified name
1251 Oid FindConversionByName(List *name)
1253 char *conversion_name;
1258 /* Convert list of names to a name and namespace */
1259 namespaceId = QualifiedNameGetCreationNamespace(name, &conversion_name);
1261 if (length(name) > 1)
1263 /* Check we have usage rights in target namespace */
1264 if (pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
1267 return FindConversion(conversion_name, namespaceId);
1270 recomputeNamespacePath();
1272 foreach(lptr, namespaceSearchPath)
1274 Oid namespaceId = (Oid) lfirsti(lptr);
1276 conoid = FindConversion(conversion_name, namespaceId);
1277 if (OidIsValid(conoid))
1281 /* Not found in path */
1286 * FindDefaultConversionProc - find default encoding cnnversion proc
1288 Oid FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1293 recomputeNamespacePath();
1295 foreach(lptr, namespaceSearchPath)
1297 Oid namespaceId = (Oid) lfirsti(lptr);
1299 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1300 if (OidIsValid(proc))
1304 /* Not found in path */
1309 * recomputeNamespacePath - recompute path derived variables if needed.
1312 recomputeNamespacePath(void)
1314 Oid userId = GetUserId();
1321 MemoryContext oldcxt;
1324 * Do nothing if path is already valid.
1326 if (namespaceSearchPathValid && namespaceUser == userId)
1329 /* Need a modifiable copy of namespace_search_path string */
1330 rawname = pstrdup(namespace_search_path);
1332 /* Parse string into list of identifiers */
1333 if (!SplitIdentifierString(rawname, ',', &namelist))
1335 /* syntax error in name list */
1336 /* this should not happen if GUC checked check_search_path */
1337 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1341 * Convert the list of names to a list of OIDs. If any names are not
1342 * recognizable or we don't have read access, just leave them out of
1343 * the list. (We can't raise an error, since the search_path setting
1344 * has already been accepted.) Don't make duplicate entries, either.
1347 foreach(l, namelist)
1349 char *curname = (char *) lfirst(l);
1352 if (strcmp(curname, "$user") == 0)
1354 /* $user --- substitute namespace matching user name, if any */
1357 tuple = SearchSysCache(SHADOWSYSID,
1358 ObjectIdGetDatum(userId),
1360 if (HeapTupleIsValid(tuple))
1364 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1365 namespaceId = GetSysCacheOid(NAMESPACENAME,
1366 CStringGetDatum(uname),
1368 ReleaseSysCache(tuple);
1369 if (OidIsValid(namespaceId) &&
1370 !intMember(namespaceId, oidlist) &&
1371 pg_namespace_aclcheck(namespaceId, userId,
1372 ACL_USAGE) == ACLCHECK_OK)
1373 oidlist = lappendi(oidlist, namespaceId);
1378 /* normal namespace reference */
1379 namespaceId = GetSysCacheOid(NAMESPACENAME,
1380 CStringGetDatum(curname),
1382 if (OidIsValid(namespaceId) &&
1383 !intMember(namespaceId, oidlist) &&
1384 pg_namespace_aclcheck(namespaceId, userId,
1385 ACL_USAGE) == ACLCHECK_OK)
1386 oidlist = lappendi(oidlist, namespaceId);
1391 * Remember the first member of the explicit list.
1394 firstNS = InvalidOid;
1396 firstNS = (Oid) lfirsti(oidlist);
1399 * Add any implicitly-searched namespaces to the list. Note these
1400 * go on the front, not the back; also notice that we do not check
1401 * USAGE permissions for these.
1403 if (!intMember(PG_CATALOG_NAMESPACE, oidlist))
1404 oidlist = lconsi(PG_CATALOG_NAMESPACE, oidlist);
1406 if (OidIsValid(myTempNamespace) &&
1407 !intMember(myTempNamespace, oidlist))
1408 oidlist = lconsi(myTempNamespace, oidlist);
1410 if (OidIsValid(mySpecialNamespace) &&
1411 !intMember(mySpecialNamespace, oidlist))
1412 oidlist = lconsi(mySpecialNamespace, oidlist);
1415 * Now that we've successfully built the new list of namespace OIDs,
1416 * save it in permanent storage.
1418 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1419 newpath = listCopy(oidlist);
1420 MemoryContextSwitchTo(oldcxt);
1422 /* Now safe to assign to state variable. */
1423 freeList(namespaceSearchPath);
1424 namespaceSearchPath = newpath;
1427 * Update info derived from search path.
1429 firstExplicitNamespace = firstNS;
1430 if (OidIsValid(mySpecialNamespace))
1431 defaultCreationNamespace = mySpecialNamespace;
1433 defaultCreationNamespace = firstNS;
1435 /* Mark the path valid. */
1436 namespaceSearchPathValid = true;
1437 namespaceUser = userId;
1446 * InitTempTableNamespace
1447 * Initialize temp table namespace on first use in a particular backend
1450 InitTempTableNamespace(void)
1452 char namespaceName[NAMEDATALEN];
1456 * First, do permission check to see if we are authorized to make
1457 * temp tables. We use a nonstandard error message here since
1458 * "databasename: permission denied" might be a tad cryptic.
1460 * Note we apply the check to the session user, not the currently
1461 * active userid, since we are not going to change our minds about
1462 * temp table availability during the session.
1464 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1465 ACL_CREATE_TEMP) != ACLCHECK_OK)
1466 elog(ERROR, "%s: not authorized to create temp tables",
1469 snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
1471 namespaceId = GetSysCacheOid(NAMESPACENAME,
1472 CStringGetDatum(namespaceName),
1474 if (!OidIsValid(namespaceId))
1477 * First use of this temp namespace in this database; create it.
1478 * The temp namespaces are always owned by the superuser. We
1479 * leave their permissions at default --- i.e., no access except to
1480 * superuser --- to ensure that unprivileged users can't peek
1481 * at other backends' temp tables. This works because the places
1482 * that access the temp namespace for my own backend skip permissions
1485 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1486 /* Advance command counter to make namespace visible */
1487 CommandCounterIncrement();
1492 * If the namespace already exists, clean it out (in case the
1493 * former owner crashed without doing so).
1495 RemoveTempRelations(namespaceId);
1499 * Okay, we've prepared the temp namespace ... but it's not committed
1500 * yet, so all our work could be undone by transaction rollback. Set
1501 * flag for AtEOXact_Namespace to know what to do.
1503 myTempNamespace = namespaceId;
1505 firstTempTransaction = true;
1507 namespaceSearchPathValid = false; /* need to rebuild list */
1511 * End-of-transaction cleanup for namespaces.
1514 AtEOXact_Namespace(bool isCommit)
1517 * If we abort the transaction in which a temp namespace was selected,
1518 * we'll have to do any creation or cleanout work over again. So,
1519 * just forget the namespace entirely until next time. On the other
1520 * hand, if we commit then register an exit callback to clean out the
1521 * temp tables at backend shutdown. (We only want to register the
1522 * callback once per session, so this is a good place to do it.)
1524 if (firstTempTransaction)
1527 on_shmem_exit(RemoveTempRelationsCallback, 0);
1530 myTempNamespace = InvalidOid;
1531 namespaceSearchPathValid = false; /* need to rebuild list */
1533 firstTempTransaction = false;
1536 * Clean up if someone failed to do PopSpecialNamespace
1538 if (OidIsValid(mySpecialNamespace))
1540 mySpecialNamespace = InvalidOid;
1541 namespaceSearchPathValid = false; /* need to rebuild list */
1546 * Remove all relations in the specified temp namespace.
1548 * This is called at backend shutdown (if we made any temp relations).
1549 * It is also called when we begin using a pre-existing temp namespace,
1550 * in order to clean out any relations that might have been created by
1551 * a crashed backend.
1554 RemoveTempRelations(Oid tempNamespaceId)
1560 ObjectAddress object;
1563 * Scan pg_class to find all the relations in the target namespace.
1564 * Ignore indexes, though, on the assumption that they'll go away
1565 * when their tables are deleted.
1567 * NOTE: if there are deletion constraints between temp relations,
1568 * then our CASCADE delete call may cause as-yet-unvisited objects
1569 * to go away. This is okay because we are using SnapshotNow; when
1570 * the scan does reach those pg_class tuples, they'll be ignored as
1573 ScanKeyEntryInitialize(&key, 0x0,
1574 Anum_pg_class_relnamespace,
1576 ObjectIdGetDatum(tempNamespaceId));
1578 pgclass = heap_openr(RelationRelationName, AccessShareLock);
1579 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
1581 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1583 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1585 case RELKIND_RELATION:
1586 case RELKIND_SEQUENCE:
1588 AssertTupleDescHasOid(pgclass->rd_att);
1589 object.classId = RelOid_pg_class;
1590 object.objectId = HeapTupleGetOid(tuple);
1591 object.objectSubId = 0;
1592 performDeletion(&object, DROP_CASCADE);
1600 heap_close(pgclass, AccessShareLock);
1604 * Callback to remove temp relations at backend exit.
1607 RemoveTempRelationsCallback(void)
1609 if (OidIsValid(myTempNamespace)) /* should always be true */
1611 /* Need to ensure we have a usable transaction. */
1612 AbortOutOfAnyTransaction();
1613 StartTransactionCommand(true);
1615 RemoveTempRelations(myTempNamespace);
1617 CommitTransactionCommand(true);
1623 * Routines for handling the GUC variable 'search_path'.
1626 /* assign_hook: validate new search_path, do extra actions as needed */
1628 assign_search_path(const char *newval, bool doit, bool interactive)
1634 /* Need a modifiable copy of string */
1635 rawname = pstrdup(newval);
1637 /* Parse string into list of identifiers */
1638 if (!SplitIdentifierString(rawname, ',', &namelist))
1640 /* syntax error in name list */
1647 * If we aren't inside a transaction, we cannot do database access so
1648 * cannot verify the individual names. Must accept the list on faith.
1650 if (interactive && IsTransactionState())
1653 * Verify that all the names are either valid namespace names or
1654 * "$user". We do not require $user to correspond to a valid
1655 * namespace. We do not check for USAGE rights, either; should we?
1657 foreach(l, namelist)
1659 char *curname = (char *) lfirst(l);
1661 if (strcmp(curname, "$user") == 0)
1663 if (!SearchSysCacheExists(NAMESPACENAME,
1664 CStringGetDatum(curname),
1666 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1674 * We mark the path as needing recomputation, but don't do anything until
1675 * it's needed. This avoids trying to do database access during GUC
1679 namespaceSearchPathValid = false;
1685 * InitializeSearchPath: initialize module during InitPostgres.
1687 * This is called after we are up enough to be able to do catalog lookups.
1690 InitializeSearchPath(void)
1692 if (IsBootstrapProcessingMode())
1695 * In bootstrap mode, the search path must be 'pg_catalog' so that
1696 * tables are created in the proper namespace; ignore the GUC setting.
1698 MemoryContext oldcxt;
1700 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1701 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1702 MemoryContextSwitchTo(oldcxt);
1703 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1704 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1705 namespaceSearchPathValid = true;
1706 namespaceUser = GetUserId();
1711 * In normal mode, arrange for a callback on any syscache invalidation
1712 * of pg_namespace rows.
1714 CacheRegisterSyscacheCallback(NAMESPACEOID,
1717 /* Force search path to be recomputed on next use */
1718 namespaceSearchPathValid = false;
1724 * Syscache inval callback function
1727 NamespaceCallback(Datum arg, Oid relid)
1729 /* Force search path to be recomputed on next use */
1730 namespaceSearchPathValid = false;
1734 * Fetch the active search path, expressed as a List of OIDs.
1736 * The returned list includes the implicitly-prepended namespaces only if
1737 * includeImplicit is true.
1739 * NB: caller must treat the list as read-only!
1742 fetch_search_path(bool includeImplicit)
1746 recomputeNamespacePath();
1748 result = namespaceSearchPath;
1749 if (!includeImplicit)
1751 while (result && (Oid) lfirsti(result) != firstExplicitNamespace)
1752 result = lnext(result);
1759 * Export the FooIsVisible functions as SQL-callable functions.
1763 pg_table_is_visible(PG_FUNCTION_ARGS)
1765 Oid oid = PG_GETARG_OID(0);
1767 PG_RETURN_BOOL(RelationIsVisible(oid));
1771 pg_type_is_visible(PG_FUNCTION_ARGS)
1773 Oid oid = PG_GETARG_OID(0);
1775 PG_RETURN_BOOL(TypeIsVisible(oid));
1779 pg_function_is_visible(PG_FUNCTION_ARGS)
1781 Oid oid = PG_GETARG_OID(0);
1783 PG_RETURN_BOOL(FunctionIsVisible(oid));
1787 pg_operator_is_visible(PG_FUNCTION_ARGS)
1789 Oid oid = PG_GETARG_OID(0);
1791 PG_RETURN_BOOL(OperatorIsVisible(oid));
1795 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1797 Oid oid = PG_GETARG_OID(0);
1799 PG_RETURN_BOOL(OpclassIsVisible(oid));