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.43 2003/01/07 20:56:06 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);
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 */
283 * Determine whether a relation (identified by OID) is visible in the
284 * current search path. Visible means "would be found by searching
285 * for the unqualified relation name".
288 RelationIsVisible(Oid relid)
291 Form_pg_class relform;
295 reltup = SearchSysCache(RELOID,
296 ObjectIdGetDatum(relid),
298 if (!HeapTupleIsValid(reltup))
299 elog(ERROR, "Cache lookup failed for relation %u", relid);
300 relform = (Form_pg_class) GETSTRUCT(reltup);
302 recomputeNamespacePath();
305 * Quick check: if it ain't in the path at all, it ain't visible.
306 * Items in the system namespace are surely in the path and so we
307 * needn't even do intMember() for them.
309 relnamespace = relform->relnamespace;
310 if (relnamespace != PG_CATALOG_NAMESPACE &&
311 !intMember(relnamespace, namespaceSearchPath))
316 * If it is in the path, it might still not be visible; it could
317 * be hidden by another relation of the same name earlier in the
318 * path. So we must do a slow check to see if this rel would be
319 * found by RelnameGetRelid.
321 char *relname = NameStr(relform->relname);
323 visible = (RelnameGetRelid(relname) == relid);
326 ReleaseSysCache(reltup);
334 * Try to resolve an unqualified datatype name.
335 * Returns OID if type found in search path, else InvalidOid.
337 * This is essentially the same as RelnameGetRelid.
340 TypenameGetTypid(const char *typname)
345 recomputeNamespacePath();
347 foreach(lptr, namespaceSearchPath)
349 Oid namespaceId = (Oid) lfirsti(lptr);
351 typid = GetSysCacheOid(TYPENAMENSP,
352 PointerGetDatum(typname),
353 ObjectIdGetDatum(namespaceId),
355 if (OidIsValid(typid))
359 /* Not found in path */
365 * Determine whether a type (identified by OID) is visible in the
366 * current search path. Visible means "would be found by searching
367 * for the unqualified type name".
370 TypeIsVisible(Oid typid)
373 Form_pg_type typform;
377 typtup = SearchSysCache(TYPEOID,
378 ObjectIdGetDatum(typid),
380 if (!HeapTupleIsValid(typtup))
381 elog(ERROR, "Cache lookup failed for type %u", typid);
382 typform = (Form_pg_type) GETSTRUCT(typtup);
384 recomputeNamespacePath();
387 * Quick check: if it ain't in the path at all, it ain't visible.
388 * Items in the system namespace are surely in the path and so we
389 * needn't even do intMember() for them.
391 typnamespace = typform->typnamespace;
392 if (typnamespace != PG_CATALOG_NAMESPACE &&
393 !intMember(typnamespace, namespaceSearchPath))
398 * If it is in the path, it might still not be visible; it could
399 * be hidden by another type of the same name earlier in the path.
400 * So we must do a slow check to see if this type would be found
401 * by TypenameGetTypid.
403 char *typname = NameStr(typform->typname);
405 visible = (TypenameGetTypid(typname) == typid);
408 ReleaseSysCache(typtup);
415 * FuncnameGetCandidates
416 * Given a possibly-qualified function name and argument count,
417 * retrieve a list of the possible matches.
419 * If nargs is -1, we return all functions matching the given name,
420 * regardless of argument count.
422 * We search a single namespace if the function name is qualified, else
423 * all namespaces in the search path. The return list will never contain
424 * multiple entries with identical argument lists --- in the multiple-
425 * namespace case, we arrange for entries in earlier namespaces to mask
426 * identical entries in later namespaces.
429 FuncnameGetCandidates(List *names, int nargs)
431 FuncCandidateList resultList = NULL;
438 /* deconstruct the name list */
439 DeconstructQualifiedName(names, &schemaname, &funcname);
443 /* use exact schema given */
444 namespaceId = LookupExplicitNamespace(schemaname);
448 /* flag to indicate we need namespace search */
449 namespaceId = InvalidOid;
450 recomputeNamespacePath();
453 /* Search syscache by name and (optionally) nargs only */
455 catlist = SearchSysCacheList(PROCNAMENSP, 2,
456 CStringGetDatum(funcname),
457 Int16GetDatum(nargs),
460 catlist = SearchSysCacheList(PROCNAMENSP, 1,
461 CStringGetDatum(funcname),
464 for (i = 0; i < catlist->n_members; i++)
466 HeapTuple proctup = &catlist->members[i]->tuple;
467 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
469 FuncCandidateList newResult;
471 nargs = procform->pronargs;
473 if (OidIsValid(namespaceId))
475 /* Consider only procs in specified namespace */
476 if (procform->pronamespace != namespaceId)
478 /* No need to check args, they must all be different */
482 /* Consider only procs that are in the search path */
485 foreach(nsp, namespaceSearchPath)
487 if (procform->pronamespace == (Oid) lfirsti(nsp))
492 continue; /* proc is not in search path */
495 * Okay, it's in the search path, but does it have the same
496 * arguments as something we already accepted? If so, keep
497 * only the one that appears earlier in the search path.
499 * If we have an ordered list from SearchSysCacheList (the normal
500 * case), then any conflicting proc must immediately adjoin
501 * this one in the list, so we only need to look at the newest
502 * result item. If we have an unordered list, we have to scan
503 * the whole result list.
507 FuncCandidateList prevResult;
509 if (catlist->ordered)
511 if (nargs == resultList->nargs &&
512 memcmp(procform->proargtypes, resultList->args,
513 nargs * sizeof(Oid)) == 0)
514 prevResult = resultList;
520 for (prevResult = resultList;
522 prevResult = prevResult->next)
524 if (nargs == prevResult->nargs &&
525 memcmp(procform->proargtypes, prevResult->args,
526 nargs * sizeof(Oid)) == 0)
532 /* We have a match with a previous result */
533 Assert(pathpos != prevResult->pathpos);
534 if (pathpos > prevResult->pathpos)
535 continue; /* keep previous result */
536 /* replace previous result */
537 prevResult->pathpos = pathpos;
538 prevResult->oid = HeapTupleGetOid(proctup);
539 continue; /* args are same, of course */
545 * Okay to add it to result list
547 newResult = (FuncCandidateList)
548 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
549 + nargs * sizeof(Oid));
550 newResult->pathpos = pathpos;
551 newResult->oid = HeapTupleGetOid(proctup);
552 newResult->nargs = nargs;
553 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
555 newResult->next = resultList;
556 resultList = newResult;
559 ReleaseSysCacheList(catlist);
566 * Determine whether a function (identified by OID) is visible in the
567 * current search path. Visible means "would be found by searching
568 * for the unqualified function name with exact argument matches".
571 FunctionIsVisible(Oid funcid)
574 Form_pg_proc procform;
578 proctup = SearchSysCache(PROCOID,
579 ObjectIdGetDatum(funcid),
581 if (!HeapTupleIsValid(proctup))
582 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
583 procform = (Form_pg_proc) GETSTRUCT(proctup);
585 recomputeNamespacePath();
588 * Quick check: if it ain't in the path at all, it ain't visible.
589 * Items in the system namespace are surely in the path and so we
590 * needn't even do intMember() for them.
592 pronamespace = procform->pronamespace;
593 if (pronamespace != PG_CATALOG_NAMESPACE &&
594 !intMember(pronamespace, namespaceSearchPath))
599 * If it is in the path, it might still not be visible; it could
600 * be hidden by another proc of the same name and arguments
601 * earlier in the path. So we must do a slow check to see if this
602 * is the same proc that would be found by FuncnameGetCandidates.
604 char *proname = NameStr(procform->proname);
605 int nargs = procform->pronargs;
606 FuncCandidateList clist;
610 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
612 for (; clist; clist = clist->next)
614 if (memcmp(clist->args, procform->proargtypes,
615 nargs * sizeof(Oid)) == 0)
617 /* Found the expected entry; is it the right proc? */
618 visible = (clist->oid == funcid);
624 ReleaseSysCache(proctup);
631 * OpernameGetCandidates
632 * Given a possibly-qualified operator name and operator kind,
633 * retrieve a list of the possible matches.
635 * If oprkind is '\0', we return all operators matching the given name,
636 * regardless of arguments.
638 * We search a single namespace if the operator name is qualified, else
639 * all namespaces in the search path. The return list will never contain
640 * multiple entries with identical argument lists --- in the multiple-
641 * namespace case, we arrange for entries in earlier namespaces to mask
642 * identical entries in later namespaces.
644 * The returned items always have two args[] entries --- one or the other
645 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
648 OpernameGetCandidates(List *names, char oprkind)
650 FuncCandidateList resultList = NULL;
657 /* deconstruct the name list */
658 DeconstructQualifiedName(names, &schemaname, &opername);
662 /* use exact schema given */
663 namespaceId = LookupExplicitNamespace(schemaname);
667 /* flag to indicate we need namespace search */
668 namespaceId = InvalidOid;
669 recomputeNamespacePath();
672 /* Search syscache by name only */
673 catlist = SearchSysCacheList(OPERNAMENSP, 1,
674 CStringGetDatum(opername),
677 for (i = 0; i < catlist->n_members; i++)
679 HeapTuple opertup = &catlist->members[i]->tuple;
680 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
682 FuncCandidateList newResult;
684 /* Ignore operators of wrong kind, if specific kind requested */
685 if (oprkind && operform->oprkind != oprkind)
688 if (OidIsValid(namespaceId))
690 /* Consider only opers in specified namespace */
691 if (operform->oprnamespace != namespaceId)
693 /* No need to check args, they must all be different */
697 /* Consider only opers that are in the search path */
700 foreach(nsp, namespaceSearchPath)
702 if (operform->oprnamespace == (Oid) lfirsti(nsp))
707 continue; /* oper is not in search path */
710 * Okay, it's in the search path, but does it have the same
711 * arguments as something we already accepted? If so, keep
712 * only the one that appears earlier in the search path.
714 * If we have an ordered list from SearchSysCacheList (the normal
715 * case), then any conflicting oper must immediately adjoin
716 * this one in the list, so we only need to look at the newest
717 * result item. If we have an unordered list, we have to scan
718 * the whole result list.
722 FuncCandidateList prevResult;
724 if (catlist->ordered)
726 if (operform->oprleft == resultList->args[0] &&
727 operform->oprright == resultList->args[1])
728 prevResult = resultList;
734 for (prevResult = resultList;
736 prevResult = prevResult->next)
738 if (operform->oprleft == prevResult->args[0] &&
739 operform->oprright == prevResult->args[1])
745 /* We have a match with a previous result */
746 Assert(pathpos != prevResult->pathpos);
747 if (pathpos > prevResult->pathpos)
748 continue; /* keep previous result */
749 /* replace previous result */
750 prevResult->pathpos = pathpos;
751 prevResult->oid = HeapTupleGetOid(opertup);
752 continue; /* args are same, of course */
758 * Okay to add it to result list
760 newResult = (FuncCandidateList)
761 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
762 newResult->pathpos = pathpos;
763 newResult->oid = HeapTupleGetOid(opertup);
764 newResult->nargs = 2;
765 newResult->args[0] = operform->oprleft;
766 newResult->args[1] = operform->oprright;
767 newResult->next = resultList;
768 resultList = newResult;
771 ReleaseSysCacheList(catlist);
778 * Determine whether an operator (identified by OID) is visible in the
779 * current search path. Visible means "would be found by searching
780 * for the unqualified operator name with exact argument matches".
783 OperatorIsVisible(Oid oprid)
786 Form_pg_operator oprform;
790 oprtup = SearchSysCache(OPEROID,
791 ObjectIdGetDatum(oprid),
793 if (!HeapTupleIsValid(oprtup))
794 elog(ERROR, "Cache lookup failed for operator %u", oprid);
795 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
797 recomputeNamespacePath();
800 * Quick check: if it ain't in the path at all, it ain't visible.
801 * Items in the system namespace are surely in the path and so we
802 * needn't even do intMember() for them.
804 oprnamespace = oprform->oprnamespace;
805 if (oprnamespace != PG_CATALOG_NAMESPACE &&
806 !intMember(oprnamespace, namespaceSearchPath))
811 * If it is in the path, it might still not be visible; it could
812 * be hidden by another operator of the same name and arguments
813 * earlier in the path. So we must do a slow check to see if this
814 * is the same operator that would be found by
815 * OpernameGetCandidates.
817 char *oprname = NameStr(oprform->oprname);
818 FuncCandidateList clist;
822 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
825 for (; clist; clist = clist->next)
827 if (clist->args[0] == oprform->oprleft &&
828 clist->args[1] == oprform->oprright)
830 /* Found the expected entry; is it the right op? */
831 visible = (clist->oid == oprid);
837 ReleaseSysCache(oprtup);
844 * OpclassGetCandidates
845 * Given an index access method OID, retrieve a list of all the
846 * opclasses for that AM that are visible in the search path.
848 * NOTE: the opcname_tmp field in the returned structs should not be used
849 * by callers, because it points at syscache entries that we release at
850 * the end of this routine. If any callers needed the name information,
851 * we could pstrdup() the names ... but at present it'd be wasteful.
854 OpclassGetCandidates(Oid amid)
856 OpclassCandidateList resultList = NULL;
860 /* Search syscache by AM OID only */
861 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
862 ObjectIdGetDatum(amid),
865 recomputeNamespacePath();
867 for (i = 0; i < catlist->n_members; i++)
869 HeapTuple opctup = &catlist->members[i]->tuple;
870 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
872 OpclassCandidateList newResult;
875 /* Consider only opclasses that are in the search path */
876 foreach(nsp, namespaceSearchPath)
878 if (opcform->opcnamespace == (Oid) lfirsti(nsp))
883 continue; /* opclass is not in search path */
886 * Okay, it's in the search path, but does it have the same name
887 * as something we already accepted? If so, keep only the one
888 * that appears earlier in the search path.
890 * If we have an ordered list from SearchSysCacheList (the normal
891 * case), then any conflicting opclass must immediately adjoin
892 * this one in the list, so we only need to look at the newest
893 * result item. If we have an unordered list, we have to scan the
898 OpclassCandidateList prevResult;
900 if (catlist->ordered)
902 if (strcmp(NameStr(opcform->opcname),
903 resultList->opcname_tmp) == 0)
904 prevResult = resultList;
910 for (prevResult = resultList;
912 prevResult = prevResult->next)
914 if (strcmp(NameStr(opcform->opcname),
915 prevResult->opcname_tmp) == 0)
921 /* We have a match with a previous result */
922 Assert(pathpos != prevResult->pathpos);
923 if (pathpos > prevResult->pathpos)
924 continue; /* keep previous result */
925 /* replace previous result */
926 prevResult->opcname_tmp = NameStr(opcform->opcname);
927 prevResult->pathpos = pathpos;
928 prevResult->oid = HeapTupleGetOid(opctup);
929 prevResult->opcintype = opcform->opcintype;
930 prevResult->opcdefault = opcform->opcdefault;
931 prevResult->opckeytype = opcform->opckeytype;
937 * Okay to add it to result list
939 newResult = (OpclassCandidateList)
940 palloc(sizeof(struct _OpclassCandidateList));
941 newResult->opcname_tmp = NameStr(opcform->opcname);
942 newResult->pathpos = pathpos;
943 newResult->oid = HeapTupleGetOid(opctup);
944 newResult->opcintype = opcform->opcintype;
945 newResult->opcdefault = opcform->opcdefault;
946 newResult->opckeytype = opcform->opckeytype;
947 newResult->next = resultList;
948 resultList = newResult;
951 ReleaseSysCacheList(catlist);
957 * OpclassnameGetOpcid
958 * Try to resolve an unqualified index opclass name.
959 * Returns OID if opclass found in search path, else InvalidOid.
961 * This is essentially the same as TypenameGetTypid, but we have to have
962 * an extra argument for the index AM OID.
965 OpclassnameGetOpcid(Oid amid, const char *opcname)
970 recomputeNamespacePath();
972 foreach(lptr, namespaceSearchPath)
974 Oid namespaceId = (Oid) lfirsti(lptr);
976 opcid = GetSysCacheOid(CLAAMNAMENSP,
977 ObjectIdGetDatum(amid),
978 PointerGetDatum(opcname),
979 ObjectIdGetDatum(namespaceId),
981 if (OidIsValid(opcid))
985 /* Not found in path */
991 * Determine whether an opclass (identified by OID) is visible in the
992 * current search path. Visible means "would be found by searching
993 * for the unqualified opclass name".
996 OpclassIsVisible(Oid opcid)
999 Form_pg_opclass opcform;
1003 opctup = SearchSysCache(CLAOID,
1004 ObjectIdGetDatum(opcid),
1006 if (!HeapTupleIsValid(opctup))
1007 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1008 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1010 recomputeNamespacePath();
1013 * Quick check: if it ain't in the path at all, it ain't visible.
1014 * Items in the system namespace are surely in the path and so we
1015 * needn't even do intMember() for them.
1017 opcnamespace = opcform->opcnamespace;
1018 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1019 !intMember(opcnamespace, namespaceSearchPath))
1024 * If it is in the path, it might still not be visible; it could
1025 * be hidden by another opclass of the same name earlier in the
1026 * path. So we must do a slow check to see if this opclass would
1027 * be found by OpclassnameGetOpcid.
1029 char *opcname = NameStr(opcform->opcname);
1031 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1034 ReleaseSysCache(opctup);
1040 * ConversionGetConid
1041 * Try to resolve an unqualified conversion name.
1042 * Returns OID if conversion found in search path, else InvalidOid.
1044 * This is essentially the same as RelnameGetRelid.
1047 ConversionGetConid(const char *conname)
1052 recomputeNamespacePath();
1054 foreach(lptr, namespaceSearchPath)
1056 Oid namespaceId = (Oid) lfirsti(lptr);
1058 conid = GetSysCacheOid(CONNAMENSP,
1059 PointerGetDatum(conname),
1060 ObjectIdGetDatum(namespaceId),
1062 if (OidIsValid(conid))
1066 /* Not found in path */
1071 * ConversionIsVisible
1072 * Determine whether a conversion (identified by OID) is visible in the
1073 * current search path. Visible means "would be found by searching
1074 * for the unqualified conversion name".
1077 ConversionIsVisible(Oid conid)
1080 Form_pg_conversion conform;
1084 contup = SearchSysCache(CONOID,
1085 ObjectIdGetDatum(conid),
1087 if (!HeapTupleIsValid(contup))
1088 elog(ERROR, "Cache lookup failed for conversion %u", conid);
1089 conform = (Form_pg_conversion) GETSTRUCT(contup);
1091 recomputeNamespacePath();
1094 * Quick check: if it ain't in the path at all, it ain't visible.
1095 * Items in the system namespace are surely in the path and so we
1096 * needn't even do intMember() for them.
1098 connamespace = conform->connamespace;
1099 if (connamespace != PG_CATALOG_NAMESPACE &&
1100 !intMember(connamespace, namespaceSearchPath))
1105 * If it is in the path, it might still not be visible; it could
1106 * be hidden by another conversion of the same name earlier in the
1107 * path. So we must do a slow check to see if this conversion would
1108 * be found by ConversionGetConid.
1110 char *conname = NameStr(conform->conname);
1112 visible = (ConversionGetConid(conname) == conid);
1115 ReleaseSysCache(contup);
1121 * DeconstructQualifiedName
1122 * Given a possibly-qualified name expressed as a list of String nodes,
1123 * extract the schema name and object name.
1125 * *nspname_p is set to NULL if there is no explicit schema name.
1128 DeconstructQualifiedName(List *names,
1133 char *schemaname = NULL;
1134 char *objname = NULL;
1136 switch (length(names))
1139 objname = strVal(lfirst(names));
1142 schemaname = strVal(lfirst(names));
1143 objname = strVal(lsecond(names));
1146 catalogname = strVal(lfirst(names));
1147 schemaname = strVal(lsecond(names));
1148 objname = strVal(lfirst(lnext(lnext(names))));
1151 * We check the catalog name and then ignore it.
1153 if (strcmp(catalogname, DatabaseName) != 0)
1154 elog(ERROR, "Cross-database references are not implemented");
1157 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1158 NameListToString(names));
1162 *nspname_p = schemaname;
1163 *objname_p = objname;
1167 * LookupExplicitNamespace
1168 * Process an explicitly-specified schema name: look up the schema
1169 * and verify we have USAGE (lookup) rights in it.
1171 * Returns the namespace OID. Raises elog if any problem.
1174 LookupExplicitNamespace(const char *nspname)
1177 AclResult aclresult;
1179 namespaceId = GetSysCacheOid(NAMESPACENAME,
1180 CStringGetDatum(nspname),
1182 if (!OidIsValid(namespaceId))
1183 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1185 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1186 if (aclresult != ACLCHECK_OK)
1187 aclcheck_error(aclresult, nspname);
1193 * QualifiedNameGetCreationNamespace
1194 * Given a possibly-qualified name for an object (in List-of-Values
1195 * format), determine what namespace the object should be created in.
1196 * Also extract and return the object name (last component of list).
1198 * This is *not* used for tables. Hence, the TEMP table namespace is
1199 * never selected as the creation target.
1202 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1208 /* deconstruct the name list */
1209 DeconstructQualifiedName(names, &schemaname, &objname);
1213 /* use exact schema given */
1214 namespaceId = GetSysCacheOid(NAMESPACENAME,
1215 CStringGetDatum(schemaname),
1217 if (!OidIsValid(namespaceId))
1218 elog(ERROR, "Namespace \"%s\" does not exist",
1220 /* we do not check for USAGE rights here! */
1224 /* use the default creation namespace */
1225 recomputeNamespacePath();
1226 namespaceId = defaultCreationNamespace;
1227 if (!OidIsValid(namespaceId))
1228 elog(ERROR, "No namespace has been selected to create in");
1231 /* Note: callers will check for CREATE rights when appropriate */
1233 *objname_p = objname;
1238 * makeRangeVarFromNameList
1239 * Utility routine to convert a qualified-name list into RangeVar form.
1242 makeRangeVarFromNameList(List *names)
1244 RangeVar *rel = makeRangeVar(NULL, NULL);
1246 switch (length(names))
1249 rel->relname = strVal(lfirst(names));
1252 rel->schemaname = strVal(lfirst(names));
1253 rel->relname = strVal(lsecond(names));
1256 rel->catalogname = strVal(lfirst(names));
1257 rel->schemaname = strVal(lsecond(names));
1258 rel->relname = strVal(lfirst(lnext(lnext(names))));
1261 elog(ERROR, "Improper relation name (too many dotted names)");
1270 * Utility routine to convert a qualified-name list into a string.
1272 * This is used primarily to form error messages, and so we do not quote
1273 * the list elements, for the sake of legibility.
1276 NameListToString(List *names)
1278 StringInfoData string;
1281 initStringInfo(&string);
1286 appendStringInfoChar(&string, '.');
1287 appendStringInfo(&string, "%s", strVal(lfirst(l)));
1294 * NameListToQuotedString
1295 * Utility routine to convert a qualified-name list into a string.
1297 * Same as above except that names will be double-quoted where necessary,
1298 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1301 NameListToQuotedString(List *names)
1303 StringInfoData string;
1306 initStringInfo(&string);
1311 appendStringInfoChar(&string, '.');
1312 appendStringInfo(&string, "%s", quote_identifier(strVal(lfirst(l))));
1319 * isTempNamespace - is the given namespace my temporary-table namespace?
1322 isTempNamespace(Oid namespaceId)
1324 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1330 * isOtherTempNamespace - is the given namespace some other backend's
1331 * temporary-table namespace?
1334 isOtherTempNamespace(Oid namespaceId)
1339 /* If it's my own temp namespace, say "false" */
1340 if (isTempNamespace(namespaceId))
1342 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1343 nspname = get_namespace_name(namespaceId);
1345 return false; /* no such namespace? */
1346 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1352 * PushSpecialNamespace - push a "special" namespace onto the front of the
1355 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1356 * Although the API is defined to allow a stack of pushed namespaces, we
1357 * presently only support one at a time.
1359 * The pushed namespace will be removed from the search path at end of
1360 * transaction, whether commit or abort.
1363 PushSpecialNamespace(Oid namespaceId)
1365 Assert(!OidIsValid(mySpecialNamespace));
1366 mySpecialNamespace = namespaceId;
1367 namespaceSearchPathValid = false;
1371 * PopSpecialNamespace - remove previously pushed special namespace.
1374 PopSpecialNamespace(Oid namespaceId)
1376 Assert(mySpecialNamespace == namespaceId);
1377 mySpecialNamespace = InvalidOid;
1378 namespaceSearchPathValid = false;
1382 * FindConversionByName - find a conversion by possibly qualified name
1385 FindConversionByName(List *name)
1388 char *conversion_name;
1393 /* deconstruct the name list */
1394 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1398 /* use exact schema given */
1399 namespaceId = LookupExplicitNamespace(schemaname);
1400 return FindConversion(conversion_name, namespaceId);
1404 /* search for it in search path */
1405 recomputeNamespacePath();
1407 foreach(lptr, namespaceSearchPath)
1409 namespaceId = (Oid) lfirsti(lptr);
1410 conoid = FindConversion(conversion_name, namespaceId);
1411 if (OidIsValid(conoid))
1416 /* Not found in path */
1421 * FindDefaultConversionProc - find default encoding conversion proc
1424 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1429 recomputeNamespacePath();
1431 foreach(lptr, namespaceSearchPath)
1433 Oid namespaceId = (Oid) lfirsti(lptr);
1435 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1436 if (OidIsValid(proc))
1440 /* Not found in path */
1445 * recomputeNamespacePath - recompute path derived variables if needed.
1448 recomputeNamespacePath(void)
1450 AclId userId = GetUserId();
1457 MemoryContext oldcxt;
1460 * Do nothing if path is already valid.
1462 if (namespaceSearchPathValid && namespaceUser == userId)
1465 /* Need a modifiable copy of namespace_search_path string */
1466 rawname = pstrdup(namespace_search_path);
1468 /* Parse string into list of identifiers */
1469 if (!SplitIdentifierString(rawname, ',', &namelist))
1471 /* syntax error in name list */
1472 /* this should not happen if GUC checked check_search_path */
1473 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1477 * Convert the list of names to a list of OIDs. If any names are not
1478 * recognizable or we don't have read access, just leave them out of
1479 * the list. (We can't raise an error, since the search_path setting
1480 * has already been accepted.) Don't make duplicate entries, either.
1483 foreach(l, namelist)
1485 char *curname = (char *) lfirst(l);
1488 if (strcmp(curname, "$user") == 0)
1490 /* $user --- substitute namespace matching user name, if any */
1493 tuple = SearchSysCache(SHADOWSYSID,
1494 ObjectIdGetDatum(userId),
1496 if (HeapTupleIsValid(tuple))
1500 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1501 namespaceId = GetSysCacheOid(NAMESPACENAME,
1502 CStringGetDatum(uname),
1504 ReleaseSysCache(tuple);
1505 if (OidIsValid(namespaceId) &&
1506 !intMember(namespaceId, oidlist) &&
1507 pg_namespace_aclcheck(namespaceId, userId,
1508 ACL_USAGE) == ACLCHECK_OK)
1509 oidlist = lappendi(oidlist, namespaceId);
1514 /* normal namespace reference */
1515 namespaceId = GetSysCacheOid(NAMESPACENAME,
1516 CStringGetDatum(curname),
1518 if (OidIsValid(namespaceId) &&
1519 !intMember(namespaceId, oidlist) &&
1520 pg_namespace_aclcheck(namespaceId, userId,
1521 ACL_USAGE) == ACLCHECK_OK)
1522 oidlist = lappendi(oidlist, namespaceId);
1527 * Remember the first member of the explicit list.
1530 firstNS = InvalidOid;
1532 firstNS = (Oid) lfirsti(oidlist);
1535 * Add any implicitly-searched namespaces to the list. Note these go
1536 * on the front, not the back; also notice that we do not check USAGE
1537 * permissions for these.
1539 if (!intMember(PG_CATALOG_NAMESPACE, oidlist))
1540 oidlist = lconsi(PG_CATALOG_NAMESPACE, oidlist);
1542 if (OidIsValid(myTempNamespace) &&
1543 !intMember(myTempNamespace, oidlist))
1544 oidlist = lconsi(myTempNamespace, oidlist);
1546 if (OidIsValid(mySpecialNamespace) &&
1547 !intMember(mySpecialNamespace, oidlist))
1548 oidlist = lconsi(mySpecialNamespace, oidlist);
1551 * Now that we've successfully built the new list of namespace OIDs,
1552 * save it in permanent storage.
1554 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1555 newpath = listCopy(oidlist);
1556 MemoryContextSwitchTo(oldcxt);
1558 /* Now safe to assign to state variable. */
1559 freeList(namespaceSearchPath);
1560 namespaceSearchPath = newpath;
1563 * Update info derived from search path.
1565 firstExplicitNamespace = firstNS;
1566 if (OidIsValid(mySpecialNamespace))
1567 defaultCreationNamespace = mySpecialNamespace;
1569 defaultCreationNamespace = firstNS;
1571 /* Mark the path valid. */
1572 namespaceSearchPathValid = true;
1573 namespaceUser = userId;
1582 * InitTempTableNamespace
1583 * Initialize temp table namespace on first use in a particular backend
1586 InitTempTableNamespace(void)
1588 char namespaceName[NAMEDATALEN];
1592 * First, do permission check to see if we are authorized to make temp
1593 * tables. We use a nonstandard error message here since
1594 * "databasename: permission denied" might be a tad cryptic.
1596 * Note we apply the check to the session user, not the currently active
1597 * userid, since we are not going to change our minds about temp table
1598 * availability during the session.
1600 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1601 ACL_CREATE_TEMP) != ACLCHECK_OK)
1602 elog(ERROR, "%s: not authorized to create temp tables",
1605 snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
1607 namespaceId = GetSysCacheOid(NAMESPACENAME,
1608 CStringGetDatum(namespaceName),
1610 if (!OidIsValid(namespaceId))
1613 * First use of this temp namespace in this database; create it.
1614 * The temp namespaces are always owned by the superuser. We
1615 * leave their permissions at default --- i.e., no access except
1616 * to superuser --- to ensure that unprivileged users can't peek
1617 * at other backends' temp tables. This works because the places
1618 * that access the temp namespace for my own backend skip
1619 * permissions checks on it.
1621 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1622 /* Advance command counter to make namespace visible */
1623 CommandCounterIncrement();
1628 * If the namespace already exists, clean it out (in case the
1629 * former owner crashed without doing so).
1631 RemoveTempRelations(namespaceId);
1635 * Okay, we've prepared the temp namespace ... but it's not committed
1636 * yet, so all our work could be undone by transaction rollback. Set
1637 * flag for AtEOXact_Namespace to know what to do.
1639 myTempNamespace = namespaceId;
1641 firstTempTransaction = true;
1643 namespaceSearchPathValid = false; /* need to rebuild list */
1647 * End-of-transaction cleanup for namespaces.
1650 AtEOXact_Namespace(bool isCommit)
1653 * If we abort the transaction in which a temp namespace was selected,
1654 * we'll have to do any creation or cleanout work over again. So,
1655 * just forget the namespace entirely until next time. On the other
1656 * hand, if we commit then register an exit callback to clean out the
1657 * temp tables at backend shutdown. (We only want to register the
1658 * callback once per session, so this is a good place to do it.)
1660 if (firstTempTransaction)
1663 on_shmem_exit(RemoveTempRelationsCallback, 0);
1666 myTempNamespace = InvalidOid;
1667 namespaceSearchPathValid = false; /* need to rebuild list */
1669 firstTempTransaction = false;
1673 * Clean up if someone failed to do PopSpecialNamespace
1675 if (OidIsValid(mySpecialNamespace))
1677 mySpecialNamespace = InvalidOid;
1678 namespaceSearchPathValid = false; /* need to rebuild list */
1683 * Remove all relations in the specified temp namespace.
1685 * This is called at backend shutdown (if we made any temp relations).
1686 * It is also called when we begin using a pre-existing temp namespace,
1687 * in order to clean out any relations that might have been created by
1688 * a crashed backend.
1691 RemoveTempRelations(Oid tempNamespaceId)
1697 ObjectAddress object;
1700 * Scan pg_class to find all the relations in the target namespace.
1701 * Ignore indexes, though, on the assumption that they'll go away when
1702 * their tables are deleted.
1704 * NOTE: if there are deletion constraints between temp relations, then
1705 * our CASCADE delete call may cause as-yet-unvisited objects to go
1706 * away. This is okay because we are using SnapshotNow; when the scan
1707 * does reach those pg_class tuples, they'll be ignored as already
1710 ScanKeyEntryInitialize(&key, 0x0,
1711 Anum_pg_class_relnamespace,
1713 ObjectIdGetDatum(tempNamespaceId));
1715 pgclass = heap_openr(RelationRelationName, AccessShareLock);
1716 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
1718 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1720 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1722 case RELKIND_RELATION:
1723 case RELKIND_SEQUENCE:
1725 object.classId = RelOid_pg_class;
1726 object.objectId = HeapTupleGetOid(tuple);
1727 object.objectSubId = 0;
1728 performDeletion(&object, DROP_CASCADE);
1736 heap_close(pgclass, AccessShareLock);
1740 * Callback to remove temp relations at backend exit.
1743 RemoveTempRelationsCallback(void)
1745 if (OidIsValid(myTempNamespace)) /* should always be true */
1747 /* Need to ensure we have a usable transaction. */
1748 AbortOutOfAnyTransaction();
1749 StartTransactionCommand(true);
1751 RemoveTempRelations(myTempNamespace);
1753 CommitTransactionCommand(true);
1759 * Routines for handling the GUC variable 'search_path'.
1762 /* assign_hook: validate new search_path, do extra actions as needed */
1764 assign_search_path(const char *newval, bool doit, bool interactive)
1770 /* Need a modifiable copy of string */
1771 rawname = pstrdup(newval);
1773 /* Parse string into list of identifiers */
1774 if (!SplitIdentifierString(rawname, ',', &namelist))
1776 /* syntax error in name list */
1783 * If we aren't inside a transaction, we cannot do database access so
1784 * cannot verify the individual names. Must accept the list on faith.
1786 if (interactive && IsTransactionState())
1789 * Verify that all the names are either valid namespace names or
1790 * "$user". We do not require $user to correspond to a valid
1791 * namespace. We do not check for USAGE rights, either; should
1794 foreach(l, namelist)
1796 char *curname = (char *) lfirst(l);
1798 if (strcmp(curname, "$user") == 0)
1800 if (!SearchSysCacheExists(NAMESPACENAME,
1801 CStringGetDatum(curname),
1803 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1811 * We mark the path as needing recomputation, but don't do anything
1812 * until it's needed. This avoids trying to do database access during
1813 * GUC initialization.
1816 namespaceSearchPathValid = false;
1822 * InitializeSearchPath: initialize module during InitPostgres.
1824 * This is called after we are up enough to be able to do catalog lookups.
1827 InitializeSearchPath(void)
1829 if (IsBootstrapProcessingMode())
1832 * In bootstrap mode, the search path must be 'pg_catalog' so that
1833 * tables are created in the proper namespace; ignore the GUC
1836 MemoryContext oldcxt;
1838 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1839 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1840 MemoryContextSwitchTo(oldcxt);
1841 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1842 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1843 namespaceSearchPathValid = true;
1844 namespaceUser = GetUserId();
1849 * In normal mode, arrange for a callback on any syscache
1850 * invalidation of pg_namespace rows.
1852 CacheRegisterSyscacheCallback(NAMESPACEOID,
1855 /* Force search path to be recomputed on next use */
1856 namespaceSearchPathValid = false;
1862 * Syscache inval callback function
1865 NamespaceCallback(Datum arg, Oid relid)
1867 /* Force search path to be recomputed on next use */
1868 namespaceSearchPathValid = false;
1872 * Fetch the active search path, expressed as a List of OIDs.
1874 * The returned list includes the implicitly-prepended namespaces only if
1875 * includeImplicit is true.
1877 * NB: caller must treat the list as read-only!
1880 fetch_search_path(bool includeImplicit)
1884 recomputeNamespacePath();
1886 result = namespaceSearchPath;
1887 if (!includeImplicit)
1889 while (result && (Oid) lfirsti(result) != firstExplicitNamespace)
1890 result = lnext(result);
1897 * Export the FooIsVisible functions as SQL-callable functions.
1901 pg_table_is_visible(PG_FUNCTION_ARGS)
1903 Oid oid = PG_GETARG_OID(0);
1905 PG_RETURN_BOOL(RelationIsVisible(oid));
1909 pg_type_is_visible(PG_FUNCTION_ARGS)
1911 Oid oid = PG_GETARG_OID(0);
1913 PG_RETURN_BOOL(TypeIsVisible(oid));
1917 pg_function_is_visible(PG_FUNCTION_ARGS)
1919 Oid oid = PG_GETARG_OID(0);
1921 PG_RETURN_BOOL(FunctionIsVisible(oid));
1925 pg_operator_is_visible(PG_FUNCTION_ARGS)
1927 Oid oid = PG_GETARG_OID(0);
1929 PG_RETURN_BOOL(OperatorIsVisible(oid));
1933 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1935 Oid oid = PG_GETARG_OID(0);
1937 PG_RETURN_BOOL(OpclassIsVisible(oid));
1941 pg_conversion_is_visible(PG_FUNCTION_ARGS)
1943 Oid oid = PG_GETARG_OID(0);
1945 PG_RETURN_BOOL(ConversionIsVisible(oid));