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.45 2003/01/12 18:19:37 petere 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);
146 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
151 * Given a RangeVar describing an existing relation,
152 * select the proper namespace and look up the relation OID.
154 * If the relation is not found, return InvalidOid if failOK = true,
155 * otherwise raise an error.
158 RangeVarGetRelid(const RangeVar *relation, bool failOK)
164 * We check the catalog name and then ignore it.
166 if (relation->catalogname)
168 if (strcmp(relation->catalogname, DatabaseName) != 0)
169 elog(ERROR, "Cross-database references are not implemented");
172 if (relation->schemaname)
174 /* use exact schema given */
175 namespaceId = LookupExplicitNamespace(relation->schemaname);
176 relId = get_relname_relid(relation->relname, namespaceId);
180 /* search the namespace path */
181 relId = RelnameGetRelid(relation->relname);
184 if (!OidIsValid(relId) && !failOK)
186 if (relation->schemaname)
187 elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
188 relation->schemaname, relation->relname);
190 elog(ERROR, "Relation \"%s\" does not exist",
197 * RangeVarGetCreationNamespace
198 * Given a RangeVar describing a to-be-created relation,
199 * choose which namespace to create it in.
201 * Note: calling this may result in a CommandCounterIncrement operation.
202 * That will happen on the first request for a temp table in any particular
203 * backend run; we will need to either create or clean out the temp schema.
206 RangeVarGetCreationNamespace(const RangeVar *newRelation)
211 * We check the catalog name and then ignore it.
213 if (newRelation->catalogname)
215 if (strcmp(newRelation->catalogname, DatabaseName) != 0)
216 elog(ERROR, "Cross-database references are not implemented");
219 if (newRelation->istemp)
221 /* TEMP tables are created in our backend-local temp namespace */
222 if (newRelation->schemaname)
223 elog(ERROR, "TEMP tables may not specify a namespace");
224 /* Initialize temp namespace if first time through */
225 if (!OidIsValid(myTempNamespace))
226 InitTempTableNamespace();
227 return myTempNamespace;
230 if (newRelation->schemaname)
232 /* use exact schema given */
233 namespaceId = GetSysCacheOid(NAMESPACENAME,
234 CStringGetDatum(newRelation->schemaname),
236 if (!OidIsValid(namespaceId))
237 elog(ERROR, "Namespace \"%s\" does not exist",
238 newRelation->schemaname);
239 /* we do not check for USAGE rights here! */
243 /* use the default creation namespace */
244 recomputeNamespacePath();
245 namespaceId = defaultCreationNamespace;
246 if (!OidIsValid(namespaceId))
247 elog(ERROR, "No namespace has been selected to create in");
250 /* Note: callers will check for CREATE rights when appropriate */
257 * Try to resolve an unqualified relation name.
258 * Returns OID if relation found in search path, else InvalidOid.
261 RelnameGetRelid(const char *relname)
266 recomputeNamespacePath();
268 foreach(lptr, namespaceSearchPath)
270 Oid namespaceId = (Oid) lfirsti(lptr);
272 relid = get_relname_relid(relname, namespaceId);
273 if (OidIsValid(relid))
277 /* Not found in path */
284 * Determine whether a relation (identified by OID) is visible in the
285 * current search path. Visible means "would be found by searching
286 * for the unqualified relation name".
289 RelationIsVisible(Oid relid)
292 Form_pg_class relform;
296 reltup = SearchSysCache(RELOID,
297 ObjectIdGetDatum(relid),
299 if (!HeapTupleIsValid(reltup))
300 elog(ERROR, "Cache lookup failed for relation %u", relid);
301 relform = (Form_pg_class) GETSTRUCT(reltup);
303 recomputeNamespacePath();
306 * Quick check: if it ain't in the path at all, it ain't visible.
307 * Items in the system namespace are surely in the path and so we
308 * needn't even do intMember() for them.
310 relnamespace = relform->relnamespace;
311 if (relnamespace != PG_CATALOG_NAMESPACE &&
312 !intMember(relnamespace, namespaceSearchPath))
317 * If it is in the path, it might still not be visible; it could
318 * be hidden by another relation of the same name earlier in the
319 * path. So we must do a slow check to see if this rel would be
320 * found by RelnameGetRelid.
322 char *relname = NameStr(relform->relname);
324 visible = (RelnameGetRelid(relname) == relid);
327 ReleaseSysCache(reltup);
335 * Try to resolve an unqualified datatype name.
336 * Returns OID if type found in search path, else InvalidOid.
338 * This is essentially the same as RelnameGetRelid.
341 TypenameGetTypid(const char *typname)
346 recomputeNamespacePath();
348 foreach(lptr, namespaceSearchPath)
350 Oid namespaceId = (Oid) lfirsti(lptr);
352 typid = GetSysCacheOid(TYPENAMENSP,
353 PointerGetDatum(typname),
354 ObjectIdGetDatum(namespaceId),
356 if (OidIsValid(typid))
360 /* Not found in path */
366 * Determine whether a type (identified by OID) is visible in the
367 * current search path. Visible means "would be found by searching
368 * for the unqualified type name".
371 TypeIsVisible(Oid typid)
374 Form_pg_type typform;
378 typtup = SearchSysCache(TYPEOID,
379 ObjectIdGetDatum(typid),
381 if (!HeapTupleIsValid(typtup))
382 elog(ERROR, "Cache lookup failed for type %u", typid);
383 typform = (Form_pg_type) GETSTRUCT(typtup);
385 recomputeNamespacePath();
388 * Quick check: if it ain't in the path at all, it ain't visible.
389 * Items in the system namespace are surely in the path and so we
390 * needn't even do intMember() for them.
392 typnamespace = typform->typnamespace;
393 if (typnamespace != PG_CATALOG_NAMESPACE &&
394 !intMember(typnamespace, namespaceSearchPath))
399 * If it is in the path, it might still not be visible; it could
400 * be hidden by another type of the same name earlier in the path.
401 * So we must do a slow check to see if this type would be found
402 * by TypenameGetTypid.
404 char *typname = NameStr(typform->typname);
406 visible = (TypenameGetTypid(typname) == typid);
409 ReleaseSysCache(typtup);
416 * FuncnameGetCandidates
417 * Given a possibly-qualified function name and argument count,
418 * retrieve a list of the possible matches.
420 * If nargs is -1, we return all functions matching the given name,
421 * regardless of argument count.
423 * We search a single namespace if the function name is qualified, else
424 * all namespaces in the search path. The return list will never contain
425 * multiple entries with identical argument lists --- in the multiple-
426 * namespace case, we arrange for entries in earlier namespaces to mask
427 * identical entries in later namespaces.
430 FuncnameGetCandidates(List *names, int nargs)
432 FuncCandidateList resultList = NULL;
439 /* deconstruct the name list */
440 DeconstructQualifiedName(names, &schemaname, &funcname);
444 /* use exact schema given */
445 namespaceId = LookupExplicitNamespace(schemaname);
449 /* flag to indicate we need namespace search */
450 namespaceId = InvalidOid;
451 recomputeNamespacePath();
454 /* Search syscache by name and (optionally) nargs only */
456 catlist = SearchSysCacheList(PROCNAMENSP, 2,
457 CStringGetDatum(funcname),
458 Int16GetDatum(nargs),
461 catlist = SearchSysCacheList(PROCNAMENSP, 1,
462 CStringGetDatum(funcname),
465 for (i = 0; i < catlist->n_members; i++)
467 HeapTuple proctup = &catlist->members[i]->tuple;
468 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
470 FuncCandidateList newResult;
472 nargs = procform->pronargs;
474 if (OidIsValid(namespaceId))
476 /* Consider only procs in specified namespace */
477 if (procform->pronamespace != namespaceId)
479 /* No need to check args, they must all be different */
483 /* Consider only procs that are in the search path */
486 foreach(nsp, namespaceSearchPath)
488 if (procform->pronamespace == (Oid) lfirsti(nsp))
493 continue; /* proc is not in search path */
496 * Okay, it's in the search path, but does it have the same
497 * arguments as something we already accepted? If so, keep
498 * only the one that appears earlier in the search path.
500 * If we have an ordered list from SearchSysCacheList (the normal
501 * case), then any conflicting proc must immediately adjoin
502 * this one in the list, so we only need to look at the newest
503 * result item. If we have an unordered list, we have to scan
504 * the whole result list.
508 FuncCandidateList prevResult;
510 if (catlist->ordered)
512 if (nargs == resultList->nargs &&
513 memcmp(procform->proargtypes, resultList->args,
514 nargs * sizeof(Oid)) == 0)
515 prevResult = resultList;
521 for (prevResult = resultList;
523 prevResult = prevResult->next)
525 if (nargs == prevResult->nargs &&
526 memcmp(procform->proargtypes, prevResult->args,
527 nargs * sizeof(Oid)) == 0)
533 /* We have a match with a previous result */
534 Assert(pathpos != prevResult->pathpos);
535 if (pathpos > prevResult->pathpos)
536 continue; /* keep previous result */
537 /* replace previous result */
538 prevResult->pathpos = pathpos;
539 prevResult->oid = HeapTupleGetOid(proctup);
540 continue; /* args are same, of course */
546 * Okay to add it to result list
548 newResult = (FuncCandidateList)
549 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
550 + nargs * sizeof(Oid));
551 newResult->pathpos = pathpos;
552 newResult->oid = HeapTupleGetOid(proctup);
553 newResult->nargs = nargs;
554 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
556 newResult->next = resultList;
557 resultList = newResult;
560 ReleaseSysCacheList(catlist);
567 * Determine whether a function (identified by OID) is visible in the
568 * current search path. Visible means "would be found by searching
569 * for the unqualified function name with exact argument matches".
572 FunctionIsVisible(Oid funcid)
575 Form_pg_proc procform;
579 proctup = SearchSysCache(PROCOID,
580 ObjectIdGetDatum(funcid),
582 if (!HeapTupleIsValid(proctup))
583 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
584 procform = (Form_pg_proc) GETSTRUCT(proctup);
586 recomputeNamespacePath();
589 * Quick check: if it ain't in the path at all, it ain't visible.
590 * Items in the system namespace are surely in the path and so we
591 * needn't even do intMember() for them.
593 pronamespace = procform->pronamespace;
594 if (pronamespace != PG_CATALOG_NAMESPACE &&
595 !intMember(pronamespace, namespaceSearchPath))
600 * If it is in the path, it might still not be visible; it could
601 * be hidden by another proc of the same name and arguments
602 * earlier in the path. So we must do a slow check to see if this
603 * is the same proc that would be found by FuncnameGetCandidates.
605 char *proname = NameStr(procform->proname);
606 int nargs = procform->pronargs;
607 FuncCandidateList clist;
611 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
613 for (; clist; clist = clist->next)
615 if (memcmp(clist->args, procform->proargtypes,
616 nargs * sizeof(Oid)) == 0)
618 /* Found the expected entry; is it the right proc? */
619 visible = (clist->oid == funcid);
625 ReleaseSysCache(proctup);
632 * OpernameGetCandidates
633 * Given a possibly-qualified operator name and operator kind,
634 * retrieve a list of the possible matches.
636 * If oprkind is '\0', we return all operators matching the given name,
637 * regardless of arguments.
639 * We search a single namespace if the operator name is qualified, else
640 * all namespaces in the search path. The return list will never contain
641 * multiple entries with identical argument lists --- in the multiple-
642 * namespace case, we arrange for entries in earlier namespaces to mask
643 * identical entries in later namespaces.
645 * The returned items always have two args[] entries --- one or the other
646 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
649 OpernameGetCandidates(List *names, char oprkind)
651 FuncCandidateList resultList = NULL;
658 /* deconstruct the name list */
659 DeconstructQualifiedName(names, &schemaname, &opername);
663 /* use exact schema given */
664 namespaceId = LookupExplicitNamespace(schemaname);
668 /* flag to indicate we need namespace search */
669 namespaceId = InvalidOid;
670 recomputeNamespacePath();
673 /* Search syscache by name only */
674 catlist = SearchSysCacheList(OPERNAMENSP, 1,
675 CStringGetDatum(opername),
678 for (i = 0; i < catlist->n_members; i++)
680 HeapTuple opertup = &catlist->members[i]->tuple;
681 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
683 FuncCandidateList newResult;
685 /* Ignore operators of wrong kind, if specific kind requested */
686 if (oprkind && operform->oprkind != oprkind)
689 if (OidIsValid(namespaceId))
691 /* Consider only opers in specified namespace */
692 if (operform->oprnamespace != namespaceId)
694 /* No need to check args, they must all be different */
698 /* Consider only opers that are in the search path */
701 foreach(nsp, namespaceSearchPath)
703 if (operform->oprnamespace == (Oid) lfirsti(nsp))
708 continue; /* oper is not in search path */
711 * Okay, it's in the search path, but does it have the same
712 * arguments as something we already accepted? If so, keep
713 * only the one that appears earlier in the search path.
715 * If we have an ordered list from SearchSysCacheList (the normal
716 * case), then any conflicting oper must immediately adjoin
717 * this one in the list, so we only need to look at the newest
718 * result item. If we have an unordered list, we have to scan
719 * the whole result list.
723 FuncCandidateList prevResult;
725 if (catlist->ordered)
727 if (operform->oprleft == resultList->args[0] &&
728 operform->oprright == resultList->args[1])
729 prevResult = resultList;
735 for (prevResult = resultList;
737 prevResult = prevResult->next)
739 if (operform->oprleft == prevResult->args[0] &&
740 operform->oprright == prevResult->args[1])
746 /* We have a match with a previous result */
747 Assert(pathpos != prevResult->pathpos);
748 if (pathpos > prevResult->pathpos)
749 continue; /* keep previous result */
750 /* replace previous result */
751 prevResult->pathpos = pathpos;
752 prevResult->oid = HeapTupleGetOid(opertup);
753 continue; /* args are same, of course */
759 * Okay to add it to result list
761 newResult = (FuncCandidateList)
762 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
763 newResult->pathpos = pathpos;
764 newResult->oid = HeapTupleGetOid(opertup);
765 newResult->nargs = 2;
766 newResult->args[0] = operform->oprleft;
767 newResult->args[1] = operform->oprright;
768 newResult->next = resultList;
769 resultList = newResult;
772 ReleaseSysCacheList(catlist);
779 * Determine whether an operator (identified by OID) is visible in the
780 * current search path. Visible means "would be found by searching
781 * for the unqualified operator name with exact argument matches".
784 OperatorIsVisible(Oid oprid)
787 Form_pg_operator oprform;
791 oprtup = SearchSysCache(OPEROID,
792 ObjectIdGetDatum(oprid),
794 if (!HeapTupleIsValid(oprtup))
795 elog(ERROR, "Cache lookup failed for operator %u", oprid);
796 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
798 recomputeNamespacePath();
801 * Quick check: if it ain't in the path at all, it ain't visible.
802 * Items in the system namespace are surely in the path and so we
803 * needn't even do intMember() for them.
805 oprnamespace = oprform->oprnamespace;
806 if (oprnamespace != PG_CATALOG_NAMESPACE &&
807 !intMember(oprnamespace, namespaceSearchPath))
812 * If it is in the path, it might still not be visible; it could
813 * be hidden by another operator of the same name and arguments
814 * earlier in the path. So we must do a slow check to see if this
815 * is the same operator that would be found by
816 * OpernameGetCandidates.
818 char *oprname = NameStr(oprform->oprname);
819 FuncCandidateList clist;
823 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
826 for (; clist; clist = clist->next)
828 if (clist->args[0] == oprform->oprleft &&
829 clist->args[1] == oprform->oprright)
831 /* Found the expected entry; is it the right op? */
832 visible = (clist->oid == oprid);
838 ReleaseSysCache(oprtup);
845 * OpclassGetCandidates
846 * Given an index access method OID, retrieve a list of all the
847 * opclasses for that AM that are visible in the search path.
849 * NOTE: the opcname_tmp field in the returned structs should not be used
850 * by callers, because it points at syscache entries that we release at
851 * the end of this routine. If any callers needed the name information,
852 * we could pstrdup() the names ... but at present it'd be wasteful.
855 OpclassGetCandidates(Oid amid)
857 OpclassCandidateList resultList = NULL;
861 /* Search syscache by AM OID only */
862 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
863 ObjectIdGetDatum(amid),
866 recomputeNamespacePath();
868 for (i = 0; i < catlist->n_members; i++)
870 HeapTuple opctup = &catlist->members[i]->tuple;
871 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
873 OpclassCandidateList newResult;
876 /* Consider only opclasses that are in the search path */
877 foreach(nsp, namespaceSearchPath)
879 if (opcform->opcnamespace == (Oid) lfirsti(nsp))
884 continue; /* opclass is not in search path */
887 * Okay, it's in the search path, but does it have the same name
888 * as something we already accepted? If so, keep only the one
889 * that appears earlier in the search path.
891 * If we have an ordered list from SearchSysCacheList (the normal
892 * case), then any conflicting opclass must immediately adjoin
893 * this one in the list, so we only need to look at the newest
894 * result item. If we have an unordered list, we have to scan the
899 OpclassCandidateList prevResult;
901 if (catlist->ordered)
903 if (strcmp(NameStr(opcform->opcname),
904 resultList->opcname_tmp) == 0)
905 prevResult = resultList;
911 for (prevResult = resultList;
913 prevResult = prevResult->next)
915 if (strcmp(NameStr(opcform->opcname),
916 prevResult->opcname_tmp) == 0)
922 /* We have a match with a previous result */
923 Assert(pathpos != prevResult->pathpos);
924 if (pathpos > prevResult->pathpos)
925 continue; /* keep previous result */
926 /* replace previous result */
927 prevResult->opcname_tmp = NameStr(opcform->opcname);
928 prevResult->pathpos = pathpos;
929 prevResult->oid = HeapTupleGetOid(opctup);
930 prevResult->opcintype = opcform->opcintype;
931 prevResult->opcdefault = opcform->opcdefault;
932 prevResult->opckeytype = opcform->opckeytype;
938 * Okay to add it to result list
940 newResult = (OpclassCandidateList)
941 palloc(sizeof(struct _OpclassCandidateList));
942 newResult->opcname_tmp = NameStr(opcform->opcname);
943 newResult->pathpos = pathpos;
944 newResult->oid = HeapTupleGetOid(opctup);
945 newResult->opcintype = opcform->opcintype;
946 newResult->opcdefault = opcform->opcdefault;
947 newResult->opckeytype = opcform->opckeytype;
948 newResult->next = resultList;
949 resultList = newResult;
952 ReleaseSysCacheList(catlist);
958 * OpclassnameGetOpcid
959 * Try to resolve an unqualified index opclass name.
960 * Returns OID if opclass found in search path, else InvalidOid.
962 * This is essentially the same as TypenameGetTypid, but we have to have
963 * an extra argument for the index AM OID.
966 OpclassnameGetOpcid(Oid amid, const char *opcname)
971 recomputeNamespacePath();
973 foreach(lptr, namespaceSearchPath)
975 Oid namespaceId = (Oid) lfirsti(lptr);
977 opcid = GetSysCacheOid(CLAAMNAMENSP,
978 ObjectIdGetDatum(amid),
979 PointerGetDatum(opcname),
980 ObjectIdGetDatum(namespaceId),
982 if (OidIsValid(opcid))
986 /* Not found in path */
992 * Determine whether an opclass (identified by OID) is visible in the
993 * current search path. Visible means "would be found by searching
994 * for the unqualified opclass name".
997 OpclassIsVisible(Oid opcid)
1000 Form_pg_opclass opcform;
1004 opctup = SearchSysCache(CLAOID,
1005 ObjectIdGetDatum(opcid),
1007 if (!HeapTupleIsValid(opctup))
1008 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1009 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1011 recomputeNamespacePath();
1014 * Quick check: if it ain't in the path at all, it ain't visible.
1015 * Items in the system namespace are surely in the path and so we
1016 * needn't even do intMember() for them.
1018 opcnamespace = opcform->opcnamespace;
1019 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1020 !intMember(opcnamespace, namespaceSearchPath))
1025 * If it is in the path, it might still not be visible; it could
1026 * be hidden by another opclass of the same name earlier in the
1027 * path. So we must do a slow check to see if this opclass would
1028 * be found by OpclassnameGetOpcid.
1030 char *opcname = NameStr(opcform->opcname);
1032 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1035 ReleaseSysCache(opctup);
1041 * ConversionGetConid
1042 * Try to resolve an unqualified conversion name.
1043 * Returns OID if conversion found in search path, else InvalidOid.
1045 * This is essentially the same as RelnameGetRelid.
1048 ConversionGetConid(const char *conname)
1053 recomputeNamespacePath();
1055 foreach(lptr, namespaceSearchPath)
1057 Oid namespaceId = (Oid) lfirsti(lptr);
1059 conid = GetSysCacheOid(CONNAMENSP,
1060 PointerGetDatum(conname),
1061 ObjectIdGetDatum(namespaceId),
1063 if (OidIsValid(conid))
1067 /* Not found in path */
1072 * ConversionIsVisible
1073 * Determine whether a conversion (identified by OID) is visible in the
1074 * current search path. Visible means "would be found by searching
1075 * for the unqualified conversion name".
1078 ConversionIsVisible(Oid conid)
1081 Form_pg_conversion conform;
1085 contup = SearchSysCache(CONOID,
1086 ObjectIdGetDatum(conid),
1088 if (!HeapTupleIsValid(contup))
1089 elog(ERROR, "Cache lookup failed for conversion %u", conid);
1090 conform = (Form_pg_conversion) GETSTRUCT(contup);
1092 recomputeNamespacePath();
1095 * Quick check: if it ain't in the path at all, it ain't visible.
1096 * Items in the system namespace are surely in the path and so we
1097 * needn't even do intMember() for them.
1099 connamespace = conform->connamespace;
1100 if (connamespace != PG_CATALOG_NAMESPACE &&
1101 !intMember(connamespace, namespaceSearchPath))
1106 * If it is in the path, it might still not be visible; it could
1107 * be hidden by another conversion of the same name earlier in the
1108 * path. So we must do a slow check to see if this conversion would
1109 * be found by ConversionGetConid.
1111 char *conname = NameStr(conform->conname);
1113 visible = (ConversionGetConid(conname) == conid);
1116 ReleaseSysCache(contup);
1122 * DeconstructQualifiedName
1123 * Given a possibly-qualified name expressed as a list of String nodes,
1124 * extract the schema name and object name.
1126 * *nspname_p is set to NULL if there is no explicit schema name.
1129 DeconstructQualifiedName(List *names,
1134 char *schemaname = NULL;
1135 char *objname = NULL;
1137 switch (length(names))
1140 objname = strVal(lfirst(names));
1143 schemaname = strVal(lfirst(names));
1144 objname = strVal(lsecond(names));
1147 catalogname = strVal(lfirst(names));
1148 schemaname = strVal(lsecond(names));
1149 objname = strVal(lfirst(lnext(lnext(names))));
1152 * We check the catalog name and then ignore it.
1154 if (strcmp(catalogname, DatabaseName) != 0)
1155 elog(ERROR, "Cross-database references are not implemented");
1158 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1159 NameListToString(names));
1163 *nspname_p = schemaname;
1164 *objname_p = objname;
1168 * LookupExplicitNamespace
1169 * Process an explicitly-specified schema name: look up the schema
1170 * and verify we have USAGE (lookup) rights in it.
1172 * Returns the namespace OID. Raises elog if any problem.
1175 LookupExplicitNamespace(const char *nspname)
1178 AclResult aclresult;
1180 namespaceId = GetSysCacheOid(NAMESPACENAME,
1181 CStringGetDatum(nspname),
1183 if (!OidIsValid(namespaceId))
1184 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1186 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1187 if (aclresult != ACLCHECK_OK)
1188 aclcheck_error(aclresult, nspname);
1194 * QualifiedNameGetCreationNamespace
1195 * Given a possibly-qualified name for an object (in List-of-Values
1196 * format), determine what namespace the object should be created in.
1197 * Also extract and return the object name (last component of list).
1199 * This is *not* used for tables. Hence, the TEMP table namespace is
1200 * never selected as the creation target.
1203 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1209 /* deconstruct the name list */
1210 DeconstructQualifiedName(names, &schemaname, &objname);
1214 /* use exact schema given */
1215 namespaceId = GetSysCacheOid(NAMESPACENAME,
1216 CStringGetDatum(schemaname),
1218 if (!OidIsValid(namespaceId))
1219 elog(ERROR, "Namespace \"%s\" does not exist",
1221 /* we do not check for USAGE rights here! */
1225 /* use the default creation namespace */
1226 recomputeNamespacePath();
1227 namespaceId = defaultCreationNamespace;
1228 if (!OidIsValid(namespaceId))
1229 elog(ERROR, "No namespace has been selected to create in");
1232 /* Note: callers will check for CREATE rights when appropriate */
1234 *objname_p = objname;
1239 * makeRangeVarFromNameList
1240 * Utility routine to convert a qualified-name list into RangeVar form.
1243 makeRangeVarFromNameList(List *names)
1245 RangeVar *rel = makeRangeVar(NULL, NULL);
1247 switch (length(names))
1250 rel->relname = strVal(lfirst(names));
1253 rel->schemaname = strVal(lfirst(names));
1254 rel->relname = strVal(lsecond(names));
1257 rel->catalogname = strVal(lfirst(names));
1258 rel->schemaname = strVal(lsecond(names));
1259 rel->relname = strVal(lfirst(lnext(lnext(names))));
1262 elog(ERROR, "Improper relation name (too many dotted names)");
1271 * Utility routine to convert a qualified-name list into a string.
1273 * This is used primarily to form error messages, and so we do not quote
1274 * the list elements, for the sake of legibility.
1277 NameListToString(List *names)
1279 StringInfoData string;
1282 initStringInfo(&string);
1287 appendStringInfoChar(&string, '.');
1288 appendStringInfo(&string, "%s", strVal(lfirst(l)));
1295 * NameListToQuotedString
1296 * Utility routine to convert a qualified-name list into a string.
1298 * Same as above except that names will be double-quoted where necessary,
1299 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1302 NameListToQuotedString(List *names)
1304 StringInfoData string;
1307 initStringInfo(&string);
1312 appendStringInfoChar(&string, '.');
1313 appendStringInfo(&string, "%s", quote_identifier(strVal(lfirst(l))));
1320 * isTempNamespace - is the given namespace my temporary-table namespace?
1323 isTempNamespace(Oid namespaceId)
1325 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1331 * isOtherTempNamespace - is the given namespace some other backend's
1332 * temporary-table namespace?
1335 isOtherTempNamespace(Oid namespaceId)
1340 /* If it's my own temp namespace, say "false" */
1341 if (isTempNamespace(namespaceId))
1343 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1344 nspname = get_namespace_name(namespaceId);
1346 return false; /* no such namespace? */
1347 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1353 * PushSpecialNamespace - push a "special" namespace onto the front of the
1356 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1357 * Although the API is defined to allow a stack of pushed namespaces, we
1358 * presently only support one at a time.
1360 * The pushed namespace will be removed from the search path at end of
1361 * transaction, whether commit or abort.
1364 PushSpecialNamespace(Oid namespaceId)
1366 Assert(!OidIsValid(mySpecialNamespace));
1367 mySpecialNamespace = namespaceId;
1368 namespaceSearchPathValid = false;
1372 * PopSpecialNamespace - remove previously pushed special namespace.
1375 PopSpecialNamespace(Oid namespaceId)
1377 Assert(mySpecialNamespace == namespaceId);
1378 mySpecialNamespace = InvalidOid;
1379 namespaceSearchPathValid = false;
1383 * FindConversionByName - find a conversion by possibly qualified name
1386 FindConversionByName(List *name)
1389 char *conversion_name;
1394 /* deconstruct the name list */
1395 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1399 /* use exact schema given */
1400 namespaceId = LookupExplicitNamespace(schemaname);
1401 return FindConversion(conversion_name, namespaceId);
1405 /* search for it in search path */
1406 recomputeNamespacePath();
1408 foreach(lptr, namespaceSearchPath)
1410 namespaceId = (Oid) lfirsti(lptr);
1411 conoid = FindConversion(conversion_name, namespaceId);
1412 if (OidIsValid(conoid))
1417 /* Not found in path */
1422 * FindDefaultConversionProc - find default encoding conversion proc
1425 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1430 recomputeNamespacePath();
1432 foreach(lptr, namespaceSearchPath)
1434 Oid namespaceId = (Oid) lfirsti(lptr);
1436 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1437 if (OidIsValid(proc))
1441 /* Not found in path */
1446 * recomputeNamespacePath - recompute path derived variables if needed.
1449 recomputeNamespacePath(void)
1451 AclId userId = GetUserId();
1458 MemoryContext oldcxt;
1461 * Do nothing if path is already valid.
1463 if (namespaceSearchPathValid && namespaceUser == userId)
1466 /* Need a modifiable copy of namespace_search_path string */
1467 rawname = pstrdup(namespace_search_path);
1469 /* Parse string into list of identifiers */
1470 if (!SplitIdentifierString(rawname, ',', &namelist))
1472 /* syntax error in name list */
1473 /* this should not happen if GUC checked check_search_path */
1474 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1478 * Convert the list of names to a list of OIDs. If any names are not
1479 * recognizable or we don't have read access, just leave them out of
1480 * the list. (We can't raise an error, since the search_path setting
1481 * has already been accepted.) Don't make duplicate entries, either.
1484 foreach(l, namelist)
1486 char *curname = (char *) lfirst(l);
1489 if (strcmp(curname, "$user") == 0)
1491 /* $user --- substitute namespace matching user name, if any */
1494 tuple = SearchSysCache(SHADOWSYSID,
1495 ObjectIdGetDatum(userId),
1497 if (HeapTupleIsValid(tuple))
1501 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1502 namespaceId = GetSysCacheOid(NAMESPACENAME,
1503 CStringGetDatum(uname),
1505 ReleaseSysCache(tuple);
1506 if (OidIsValid(namespaceId) &&
1507 !intMember(namespaceId, oidlist) &&
1508 pg_namespace_aclcheck(namespaceId, userId,
1509 ACL_USAGE) == ACLCHECK_OK)
1510 oidlist = lappendi(oidlist, namespaceId);
1515 /* normal namespace reference */
1516 namespaceId = GetSysCacheOid(NAMESPACENAME,
1517 CStringGetDatum(curname),
1519 if (OidIsValid(namespaceId) &&
1520 !intMember(namespaceId, oidlist) &&
1521 pg_namespace_aclcheck(namespaceId, userId,
1522 ACL_USAGE) == ACLCHECK_OK)
1523 oidlist = lappendi(oidlist, namespaceId);
1528 * Remember the first member of the explicit list.
1531 firstNS = InvalidOid;
1533 firstNS = (Oid) lfirsti(oidlist);
1536 * Add any implicitly-searched namespaces to the list. Note these go
1537 * on the front, not the back; also notice that we do not check USAGE
1538 * permissions for these.
1540 if (!intMember(PG_CATALOG_NAMESPACE, oidlist))
1541 oidlist = lconsi(PG_CATALOG_NAMESPACE, oidlist);
1543 if (OidIsValid(myTempNamespace) &&
1544 !intMember(myTempNamespace, oidlist))
1545 oidlist = lconsi(myTempNamespace, oidlist);
1547 if (OidIsValid(mySpecialNamespace) &&
1548 !intMember(mySpecialNamespace, oidlist))
1549 oidlist = lconsi(mySpecialNamespace, oidlist);
1552 * Now that we've successfully built the new list of namespace OIDs,
1553 * save it in permanent storage.
1555 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1556 newpath = listCopy(oidlist);
1557 MemoryContextSwitchTo(oldcxt);
1559 /* Now safe to assign to state variable. */
1560 freeList(namespaceSearchPath);
1561 namespaceSearchPath = newpath;
1564 * Update info derived from search path.
1566 firstExplicitNamespace = firstNS;
1567 if (OidIsValid(mySpecialNamespace))
1568 defaultCreationNamespace = mySpecialNamespace;
1570 defaultCreationNamespace = firstNS;
1572 /* Mark the path valid. */
1573 namespaceSearchPathValid = true;
1574 namespaceUser = userId;
1583 * InitTempTableNamespace
1584 * Initialize temp table namespace on first use in a particular backend
1587 InitTempTableNamespace(void)
1589 char namespaceName[NAMEDATALEN];
1593 * First, do permission check to see if we are authorized to make temp
1594 * tables. We use a nonstandard error message here since
1595 * "databasename: permission denied" might be a tad cryptic.
1597 * Note we apply the check to the session user, not the currently active
1598 * userid, since we are not going to change our minds about temp table
1599 * availability during the session.
1601 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1602 ACL_CREATE_TEMP) != ACLCHECK_OK)
1603 elog(ERROR, "%s: not authorized to create temp tables",
1606 snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
1608 namespaceId = GetSysCacheOid(NAMESPACENAME,
1609 CStringGetDatum(namespaceName),
1611 if (!OidIsValid(namespaceId))
1614 * First use of this temp namespace in this database; create it.
1615 * The temp namespaces are always owned by the superuser. We
1616 * leave their permissions at default --- i.e., no access except
1617 * to superuser --- to ensure that unprivileged users can't peek
1618 * at other backends' temp tables. This works because the places
1619 * that access the temp namespace for my own backend skip
1620 * permissions checks on it.
1622 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1623 /* Advance command counter to make namespace visible */
1624 CommandCounterIncrement();
1629 * If the namespace already exists, clean it out (in case the
1630 * former owner crashed without doing so).
1632 RemoveTempRelations(namespaceId);
1636 * Okay, we've prepared the temp namespace ... but it's not committed
1637 * yet, so all our work could be undone by transaction rollback. Set
1638 * flag for AtEOXact_Namespace to know what to do.
1640 myTempNamespace = namespaceId;
1642 firstTempTransaction = true;
1644 namespaceSearchPathValid = false; /* need to rebuild list */
1648 * End-of-transaction cleanup for namespaces.
1651 AtEOXact_Namespace(bool isCommit)
1654 * If we abort the transaction in which a temp namespace was selected,
1655 * we'll have to do any creation or cleanout work over again. So,
1656 * just forget the namespace entirely until next time. On the other
1657 * hand, if we commit then register an exit callback to clean out the
1658 * temp tables at backend shutdown. (We only want to register the
1659 * callback once per session, so this is a good place to do it.)
1661 if (firstTempTransaction)
1664 on_shmem_exit(RemoveTempRelationsCallback, 0);
1667 myTempNamespace = InvalidOid;
1668 namespaceSearchPathValid = false; /* need to rebuild list */
1670 firstTempTransaction = false;
1674 * Clean up if someone failed to do PopSpecialNamespace
1676 if (OidIsValid(mySpecialNamespace))
1678 mySpecialNamespace = InvalidOid;
1679 namespaceSearchPathValid = false; /* need to rebuild list */
1684 * Remove all relations in the specified temp namespace.
1686 * This is called at backend shutdown (if we made any temp relations).
1687 * It is also called when we begin using a pre-existing temp namespace,
1688 * in order to clean out any relations that might have been created by
1689 * a crashed backend.
1692 RemoveTempRelations(Oid tempNamespaceId)
1698 ObjectAddress object;
1701 * Scan pg_class to find all the relations in the target namespace.
1702 * Ignore indexes, though, on the assumption that they'll go away when
1703 * their tables are deleted.
1705 * NOTE: if there are deletion constraints between temp relations, then
1706 * our CASCADE delete call may cause as-yet-unvisited objects to go
1707 * away. This is okay because we are using SnapshotNow; when the scan
1708 * does reach those pg_class tuples, they'll be ignored as already
1711 ScanKeyEntryInitialize(&key, 0x0,
1712 Anum_pg_class_relnamespace,
1714 ObjectIdGetDatum(tempNamespaceId));
1716 pgclass = heap_openr(RelationRelationName, AccessShareLock);
1717 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
1719 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1721 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1723 case RELKIND_RELATION:
1724 case RELKIND_SEQUENCE:
1726 object.classId = RelOid_pg_class;
1727 object.objectId = HeapTupleGetOid(tuple);
1728 object.objectSubId = 0;
1729 performDeletion(&object, DROP_CASCADE);
1737 heap_close(pgclass, AccessShareLock);
1741 * Callback to remove temp relations at backend exit.
1744 RemoveTempRelationsCallback(void)
1746 if (OidIsValid(myTempNamespace)) /* should always be true */
1748 /* Need to ensure we have a usable transaction. */
1749 AbortOutOfAnyTransaction();
1750 StartTransactionCommand(true);
1752 RemoveTempRelations(myTempNamespace);
1754 CommitTransactionCommand(true);
1760 * Routines for handling the GUC variable 'search_path'.
1763 /* assign_hook: validate new search_path, do extra actions as needed */
1765 assign_search_path(const char *newval, bool doit, bool interactive)
1771 /* Need a modifiable copy of string */
1772 rawname = pstrdup(newval);
1774 /* Parse string into list of identifiers */
1775 if (!SplitIdentifierString(rawname, ',', &namelist))
1777 /* syntax error in name list */
1784 * If we aren't inside a transaction, we cannot do database access so
1785 * cannot verify the individual names. Must accept the list on faith.
1787 if (interactive && IsTransactionState())
1790 * Verify that all the names are either valid namespace names or
1791 * "$user". We do not require $user to correspond to a valid
1792 * namespace. We do not check for USAGE rights, either; should
1795 foreach(l, namelist)
1797 char *curname = (char *) lfirst(l);
1799 if (strcmp(curname, "$user") == 0)
1801 if (!SearchSysCacheExists(NAMESPACENAME,
1802 CStringGetDatum(curname),
1804 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1812 * We mark the path as needing recomputation, but don't do anything
1813 * until it's needed. This avoids trying to do database access during
1814 * GUC initialization.
1817 namespaceSearchPathValid = false;
1823 * InitializeSearchPath: initialize module during InitPostgres.
1825 * This is called after we are up enough to be able to do catalog lookups.
1828 InitializeSearchPath(void)
1830 if (IsBootstrapProcessingMode())
1833 * In bootstrap mode, the search path must be 'pg_catalog' so that
1834 * tables are created in the proper namespace; ignore the GUC
1837 MemoryContext oldcxt;
1839 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1840 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1841 MemoryContextSwitchTo(oldcxt);
1842 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1843 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1844 namespaceSearchPathValid = true;
1845 namespaceUser = GetUserId();
1850 * In normal mode, arrange for a callback on any syscache
1851 * invalidation of pg_namespace rows.
1853 CacheRegisterSyscacheCallback(NAMESPACEOID,
1856 /* Force search path to be recomputed on next use */
1857 namespaceSearchPathValid = false;
1863 * Syscache inval callback function
1866 NamespaceCallback(Datum arg, Oid relid)
1868 /* Force search path to be recomputed on next use */
1869 namespaceSearchPathValid = false;
1873 * Fetch the active search path, expressed as a List of OIDs.
1875 * The returned list includes the implicitly-prepended namespaces only if
1876 * includeImplicit is true.
1878 * NB: caller must treat the list as read-only!
1881 fetch_search_path(bool includeImplicit)
1885 recomputeNamespacePath();
1887 result = namespaceSearchPath;
1888 if (!includeImplicit)
1890 while (result && (Oid) lfirsti(result) != firstExplicitNamespace)
1891 result = lnext(result);
1898 * Export the FooIsVisible functions as SQL-callable functions.
1902 pg_table_is_visible(PG_FUNCTION_ARGS)
1904 Oid oid = PG_GETARG_OID(0);
1906 PG_RETURN_BOOL(RelationIsVisible(oid));
1910 pg_type_is_visible(PG_FUNCTION_ARGS)
1912 Oid oid = PG_GETARG_OID(0);
1914 PG_RETURN_BOOL(TypeIsVisible(oid));
1918 pg_function_is_visible(PG_FUNCTION_ARGS)
1920 Oid oid = PG_GETARG_OID(0);
1922 PG_RETURN_BOOL(FunctionIsVisible(oid));
1926 pg_operator_is_visible(PG_FUNCTION_ARGS)
1928 Oid oid = PG_GETARG_OID(0);
1930 PG_RETURN_BOOL(OperatorIsVisible(oid));
1934 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1936 Oid oid = PG_GETARG_OID(0);
1938 PG_RETURN_BOOL(OpclassIsVisible(oid));
1942 pg_conversion_is_visible(PG_FUNCTION_ARGS)
1944 Oid oid = PG_GETARG_OID(0);
1946 PG_RETURN_BOOL(ConversionIsVisible(oid));