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.39 2002/11/09 23:56:39 momjian 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 "commands/tablecmds.h"
38 #include "lib/stringinfo.h"
39 #include "miscadmin.h"
40 #include "nodes/makefuncs.h"
41 #include "storage/backendid.h"
42 #include "storage/ipc.h"
43 #include "utils/acl.h"
44 #include "utils/builtins.h"
45 #include "utils/catcache.h"
46 #include "utils/fmgroids.h"
47 #include "utils/guc.h"
48 #include "utils/inval.h"
49 #include "utils/lsyscache.h"
50 #include "utils/syscache.h"
54 * The namespace search path is a possibly-empty list of namespace OIDs.
55 * In addition to the explicit list, several implicitly-searched namespaces
58 * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
59 * always searched first. (This is a hack for CREATE SCHEMA.)
61 * 2. If a TEMP table namespace has been initialized in this session, it
62 * is always searched just after any special namespace.
64 * 3. The system catalog namespace is always searched. If the system
65 * namespace is present in the explicit path then it will be searched in
66 * the specified order; otherwise it will be searched after TEMP tables and
67 * *before* the explicit list. (It might seem that the system namespace
68 * should be implicitly last, but this behavior appears to be required by
69 * SQL99. Also, this provides a way to search the system namespace first
70 * without thereby making it the default creation target namespace.)
72 * The default creation target namespace is normally equal to the first
73 * element of the explicit list, but is the "special" namespace when one
74 * has been set. If the explicit list is empty and there is no special
75 * namespace, there is no default target.
77 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
78 * the system namespace is the only one searched or inserted into.
79 * The initdb script is also careful to set search_path to 'pg_catalog' for
80 * its post-bootstrap standalone backend runs. Otherwise the default search
81 * path is determined by GUC. The factory default path contains the PUBLIC
82 * namespace (if it exists), preceded by the user's personal namespace
85 * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
86 * derived variables) need to be recomputed from namespace_search_path.
87 * We mark it invalid upon an assignment to namespace_search_path or receipt
88 * of a syscache invalidation event for pg_namespace. The recomputation
89 * is done during the next lookup attempt.
91 * Any namespaces mentioned in namespace_search_path that are not readable
92 * by the current user ID are simply left out of namespaceSearchPath; so
93 * we have to be willing to recompute the path when current userid changes.
94 * namespaceUser is the userid the path has been computed for.
97 static List *namespaceSearchPath = NIL;
99 static Oid namespaceUser = InvalidOid;
101 /* default place to create stuff; if InvalidOid, no default */
102 static Oid defaultCreationNamespace = InvalidOid;
104 /* first explicit member of list; usually same as defaultCreationNamespace */
105 static Oid firstExplicitNamespace = InvalidOid;
107 /* The above four values are valid only if namespaceSearchPathValid */
108 static bool namespaceSearchPathValid = true;
111 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
112 * in a particular backend session (this happens when a CREATE TEMP TABLE
113 * command is first executed). Thereafter it's the OID of the temp namespace.
114 * firstTempTransaction flags whether we've committed creation of the TEMP
117 static Oid myTempNamespace = InvalidOid;
119 static bool firstTempTransaction = false;
122 * "Special" namespace for CREATE SCHEMA. If set, it's the first search
123 * path element, and also the default creation namespace.
125 static Oid mySpecialNamespace = InvalidOid;
128 * This is the text equivalent of the search path --- it's the value
129 * of the GUC variable 'search_path'.
131 char *namespace_search_path = NULL;
134 /* Local functions */
135 static void recomputeNamespacePath(void);
136 static void InitTempTableNamespace(void);
137 static void RemoveTempRelations(Oid tempNamespaceId);
138 static void RemoveTempRelationsCallback(void);
139 static void NamespaceCallback(Datum arg, Oid relid);
141 /* These don't really need to appear in any header file */
142 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
143 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
144 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
145 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
146 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
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 * DeconstructQualifiedName
1041 * Given a possibly-qualified name expressed as a list of String nodes,
1042 * extract the schema name and object name.
1044 * *nspname_p is set to NULL if there is no explicit schema name.
1047 DeconstructQualifiedName(List *names,
1052 char *schemaname = NULL;
1053 char *objname = NULL;
1055 switch (length(names))
1058 objname = strVal(lfirst(names));
1061 schemaname = strVal(lfirst(names));
1062 objname = strVal(lsecond(names));
1065 catalogname = strVal(lfirst(names));
1066 schemaname = strVal(lsecond(names));
1067 objname = strVal(lfirst(lnext(lnext(names))));
1070 * We check the catalog name and then ignore it.
1072 if (strcmp(catalogname, DatabaseName) != 0)
1073 elog(ERROR, "Cross-database references are not implemented");
1076 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1077 NameListToString(names));
1081 *nspname_p = schemaname;
1082 *objname_p = objname;
1086 * LookupExplicitNamespace
1087 * Process an explicitly-specified schema name: look up the schema
1088 * and verify we have USAGE (lookup) rights in it.
1090 * Returns the namespace OID. Raises elog if any problem.
1093 LookupExplicitNamespace(const char *nspname)
1096 AclResult aclresult;
1098 namespaceId = GetSysCacheOid(NAMESPACENAME,
1099 CStringGetDatum(nspname),
1101 if (!OidIsValid(namespaceId))
1102 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1104 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1105 if (aclresult != ACLCHECK_OK)
1106 aclcheck_error(aclresult, nspname);
1112 * QualifiedNameGetCreationNamespace
1113 * Given a possibly-qualified name for an object (in List-of-Values
1114 * format), determine what namespace the object should be created in.
1115 * Also extract and return the object name (last component of list).
1117 * This is *not* used for tables. Hence, the TEMP table namespace is
1118 * never selected as the creation target.
1121 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1127 /* deconstruct the name list */
1128 DeconstructQualifiedName(names, &schemaname, &objname);
1132 /* use exact schema given */
1133 namespaceId = GetSysCacheOid(NAMESPACENAME,
1134 CStringGetDatum(schemaname),
1136 if (!OidIsValid(namespaceId))
1137 elog(ERROR, "Namespace \"%s\" does not exist",
1139 /* we do not check for USAGE rights here! */
1143 /* use the default creation namespace */
1144 recomputeNamespacePath();
1145 namespaceId = defaultCreationNamespace;
1146 if (!OidIsValid(namespaceId))
1147 elog(ERROR, "No namespace has been selected to create in");
1150 /* Note: callers will check for CREATE rights when appropriate */
1152 *objname_p = objname;
1157 * makeRangeVarFromNameList
1158 * Utility routine to convert a qualified-name list into RangeVar form.
1161 makeRangeVarFromNameList(List *names)
1163 RangeVar *rel = makeRangeVar(NULL, NULL);
1165 switch (length(names))
1168 rel->relname = strVal(lfirst(names));
1171 rel->schemaname = strVal(lfirst(names));
1172 rel->relname = strVal(lsecond(names));
1175 rel->catalogname = strVal(lfirst(names));
1176 rel->schemaname = strVal(lsecond(names));
1177 rel->relname = strVal(lfirst(lnext(lnext(names))));
1180 elog(ERROR, "Improper relation name (too many dotted names)");
1189 * Utility routine to convert a qualified-name list into a string.
1191 * This is used primarily to form error messages, and so we do not quote
1192 * the list elements, for the sake of legibility.
1195 NameListToString(List *names)
1197 StringInfoData string;
1200 initStringInfo(&string);
1205 appendStringInfoChar(&string, '.');
1206 appendStringInfo(&string, "%s", strVal(lfirst(l)));
1213 * NameListToQuotedString
1214 * Utility routine to convert a qualified-name list into a string.
1216 * Same as above except that names will be double-quoted where necessary,
1217 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1220 NameListToQuotedString(List *names)
1222 StringInfoData string;
1225 initStringInfo(&string);
1230 appendStringInfoChar(&string, '.');
1231 appendStringInfo(&string, "%s", quote_identifier(strVal(lfirst(l))));
1238 * isTempNamespace - is the given namespace my temporary-table namespace?
1241 isTempNamespace(Oid namespaceId)
1243 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1249 * isOtherTempNamespace - is the given namespace some other backend's
1250 * temporary-table namespace?
1253 isOtherTempNamespace(Oid namespaceId)
1258 /* If it's my own temp namespace, say "false" */
1259 if (isTempNamespace(namespaceId))
1261 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1262 nspname = get_namespace_name(namespaceId);
1264 return false; /* no such namespace? */
1265 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1271 * PushSpecialNamespace - push a "special" namespace onto the front of the
1274 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1275 * Although the API is defined to allow a stack of pushed namespaces, we
1276 * presently only support one at a time.
1278 * The pushed namespace will be removed from the search path at end of
1279 * transaction, whether commit or abort.
1282 PushSpecialNamespace(Oid namespaceId)
1284 Assert(!OidIsValid(mySpecialNamespace));
1285 mySpecialNamespace = namespaceId;
1286 namespaceSearchPathValid = false;
1290 * PopSpecialNamespace - remove previously pushed special namespace.
1293 PopSpecialNamespace(Oid namespaceId)
1295 Assert(mySpecialNamespace == namespaceId);
1296 mySpecialNamespace = InvalidOid;
1297 namespaceSearchPathValid = false;
1301 * FindConversionByName - find a conversion by possibly qualified name
1304 FindConversionByName(List *name)
1307 char *conversion_name;
1312 /* deconstruct the name list */
1313 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1317 /* use exact schema given */
1318 namespaceId = LookupExplicitNamespace(schemaname);
1319 return FindConversion(conversion_name, namespaceId);
1323 /* search for it in search path */
1324 recomputeNamespacePath();
1326 foreach(lptr, namespaceSearchPath)
1328 namespaceId = (Oid) lfirsti(lptr);
1329 conoid = FindConversion(conversion_name, namespaceId);
1330 if (OidIsValid(conoid))
1335 /* Not found in path */
1340 * FindDefaultConversionProc - find default encoding conversion proc
1343 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1348 recomputeNamespacePath();
1350 foreach(lptr, namespaceSearchPath)
1352 Oid namespaceId = (Oid) lfirsti(lptr);
1354 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1355 if (OidIsValid(proc))
1359 /* Not found in path */
1364 * recomputeNamespacePath - recompute path derived variables if needed.
1367 recomputeNamespacePath(void)
1369 Oid userId = GetUserId();
1376 MemoryContext oldcxt;
1379 * Do nothing if path is already valid.
1381 if (namespaceSearchPathValid && namespaceUser == userId)
1384 /* Need a modifiable copy of namespace_search_path string */
1385 rawname = pstrdup(namespace_search_path);
1387 /* Parse string into list of identifiers */
1388 if (!SplitIdentifierString(rawname, ',', &namelist))
1390 /* syntax error in name list */
1391 /* this should not happen if GUC checked check_search_path */
1392 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1396 * Convert the list of names to a list of OIDs. If any names are not
1397 * recognizable or we don't have read access, just leave them out of
1398 * the list. (We can't raise an error, since the search_path setting
1399 * has already been accepted.) Don't make duplicate entries, either.
1402 foreach(l, namelist)
1404 char *curname = (char *) lfirst(l);
1407 if (strcmp(curname, "$user") == 0)
1409 /* $user --- substitute namespace matching user name, if any */
1412 tuple = SearchSysCache(SHADOWSYSID,
1413 ObjectIdGetDatum(userId),
1415 if (HeapTupleIsValid(tuple))
1419 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1420 namespaceId = GetSysCacheOid(NAMESPACENAME,
1421 CStringGetDatum(uname),
1423 ReleaseSysCache(tuple);
1424 if (OidIsValid(namespaceId) &&
1425 !intMember(namespaceId, oidlist) &&
1426 pg_namespace_aclcheck(namespaceId, userId,
1427 ACL_USAGE) == ACLCHECK_OK)
1428 oidlist = lappendi(oidlist, namespaceId);
1433 /* normal namespace reference */
1434 namespaceId = GetSysCacheOid(NAMESPACENAME,
1435 CStringGetDatum(curname),
1437 if (OidIsValid(namespaceId) &&
1438 !intMember(namespaceId, oidlist) &&
1439 pg_namespace_aclcheck(namespaceId, userId,
1440 ACL_USAGE) == ACLCHECK_OK)
1441 oidlist = lappendi(oidlist, namespaceId);
1446 * Remember the first member of the explicit list.
1449 firstNS = InvalidOid;
1451 firstNS = (Oid) lfirsti(oidlist);
1454 * Add any implicitly-searched namespaces to the list. Note these go
1455 * on the front, not the back; also notice that we do not check USAGE
1456 * permissions for these.
1458 if (!intMember(PG_CATALOG_NAMESPACE, oidlist))
1459 oidlist = lconsi(PG_CATALOG_NAMESPACE, oidlist);
1461 if (OidIsValid(myTempNamespace) &&
1462 !intMember(myTempNamespace, oidlist))
1463 oidlist = lconsi(myTempNamespace, oidlist);
1465 if (OidIsValid(mySpecialNamespace) &&
1466 !intMember(mySpecialNamespace, oidlist))
1467 oidlist = lconsi(mySpecialNamespace, oidlist);
1470 * Now that we've successfully built the new list of namespace OIDs,
1471 * save it in permanent storage.
1473 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1474 newpath = listCopy(oidlist);
1475 MemoryContextSwitchTo(oldcxt);
1477 /* Now safe to assign to state variable. */
1478 freeList(namespaceSearchPath);
1479 namespaceSearchPath = newpath;
1482 * Update info derived from search path.
1484 firstExplicitNamespace = firstNS;
1485 if (OidIsValid(mySpecialNamespace))
1486 defaultCreationNamespace = mySpecialNamespace;
1488 defaultCreationNamespace = firstNS;
1490 /* Mark the path valid. */
1491 namespaceSearchPathValid = true;
1492 namespaceUser = userId;
1501 * InitTempTableNamespace
1502 * Initialize temp table namespace on first use in a particular backend
1505 InitTempTableNamespace(void)
1507 char namespaceName[NAMEDATALEN];
1511 * First, do permission check to see if we are authorized to make temp
1512 * tables. We use a nonstandard error message here since
1513 * "databasename: permission denied" might be a tad cryptic.
1515 * Note we apply the check to the session user, not the currently active
1516 * userid, since we are not going to change our minds about temp table
1517 * availability during the session.
1519 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1520 ACL_CREATE_TEMP) != ACLCHECK_OK)
1521 elog(ERROR, "%s: not authorized to create temp tables",
1524 snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
1526 namespaceId = GetSysCacheOid(NAMESPACENAME,
1527 CStringGetDatum(namespaceName),
1529 if (!OidIsValid(namespaceId))
1532 * First use of this temp namespace in this database; create it.
1533 * The temp namespaces are always owned by the superuser. We
1534 * leave their permissions at default --- i.e., no access except
1535 * to superuser --- to ensure that unprivileged users can't peek
1536 * at other backends' temp tables. This works because the places
1537 * that access the temp namespace for my own backend skip
1538 * permissions checks on it.
1540 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1541 /* Advance command counter to make namespace visible */
1542 CommandCounterIncrement();
1547 * If the namespace already exists, clean it out (in case the
1548 * former owner crashed without doing so).
1550 RemoveTempRelations(namespaceId);
1554 * Okay, we've prepared the temp namespace ... but it's not committed
1555 * yet, so all our work could be undone by transaction rollback. Set
1556 * flag for AtEOXact_Namespace to know what to do.
1558 myTempNamespace = namespaceId;
1560 firstTempTransaction = true;
1562 namespaceSearchPathValid = false; /* need to rebuild list */
1566 * End-of-transaction cleanup for namespaces.
1569 AtEOXact_Namespace(bool isCommit)
1572 * If we abort the transaction in which a temp namespace was selected,
1573 * we'll have to do any creation or cleanout work over again. So,
1574 * just forget the namespace entirely until next time. On the other
1575 * hand, if we commit then register an exit callback to clean out the
1576 * temp tables at backend shutdown. (We only want to register the
1577 * callback once per session, so this is a good place to do it.)
1579 if (firstTempTransaction)
1582 on_shmem_exit(RemoveTempRelationsCallback, 0);
1585 myTempNamespace = InvalidOid;
1586 namespaceSearchPathValid = false; /* need to rebuild list */
1588 firstTempTransaction = false;
1592 * Clean up if someone failed to do PopSpecialNamespace
1594 if (OidIsValid(mySpecialNamespace))
1596 mySpecialNamespace = InvalidOid;
1597 namespaceSearchPathValid = false; /* need to rebuild list */
1602 * Remove all relations in the specified temp namespace.
1604 * This is called at backend shutdown (if we made any temp relations).
1605 * It is also called when we begin using a pre-existing temp namespace,
1606 * in order to clean out any relations that might have been created by
1607 * a crashed backend.
1610 RemoveTempRelations(Oid tempNamespaceId)
1616 ObjectAddress object;
1619 * Scan pg_class to find all the relations in the target namespace.
1620 * Ignore indexes, though, on the assumption that they'll go away when
1621 * their tables are deleted.
1623 * NOTE: if there are deletion constraints between temp relations, then
1624 * our CASCADE delete call may cause as-yet-unvisited objects to go
1625 * away. This is okay because we are using SnapshotNow; when the scan
1626 * does reach those pg_class tuples, they'll be ignored as already
1629 ScanKeyEntryInitialize(&key, 0x0,
1630 Anum_pg_class_relnamespace,
1632 ObjectIdGetDatum(tempNamespaceId));
1634 pgclass = heap_openr(RelationRelationName, AccessShareLock);
1635 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
1637 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1639 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1641 case RELKIND_RELATION:
1642 case RELKIND_SEQUENCE:
1644 object.classId = RelOid_pg_class;
1645 object.objectId = HeapTupleGetOid(tuple);
1646 object.objectSubId = 0;
1647 performDeletion(&object, DROP_CASCADE);
1655 heap_close(pgclass, AccessShareLock);
1659 * Callback to remove temp relations at backend exit.
1662 RemoveTempRelationsCallback(void)
1664 if (OidIsValid(myTempNamespace)) /* should always be true */
1666 /* Need to ensure we have a usable transaction. */
1667 AbortOutOfAnyTransaction();
1668 StartTransactionCommand(true);
1670 RemoveTempRelations(myTempNamespace);
1672 CommitTransactionCommand(true);
1679 * Routines for handling the GUC variable 'search_path'.
1682 /* assign_hook: validate new search_path, do extra actions as needed */
1684 assign_search_path(const char *newval, bool doit, bool interactive)
1690 /* Need a modifiable copy of string */
1691 rawname = pstrdup(newval);
1693 /* Parse string into list of identifiers */
1694 if (!SplitIdentifierString(rawname, ',', &namelist))
1696 /* syntax error in name list */
1703 * If we aren't inside a transaction, we cannot do database access so
1704 * cannot verify the individual names. Must accept the list on faith.
1706 if (interactive && IsTransactionState())
1709 * Verify that all the names are either valid namespace names or
1710 * "$user". We do not require $user to correspond to a valid
1711 * namespace. We do not check for USAGE rights, either; should
1714 foreach(l, namelist)
1716 char *curname = (char *) lfirst(l);
1718 if (strcmp(curname, "$user") == 0)
1720 if (!SearchSysCacheExists(NAMESPACENAME,
1721 CStringGetDatum(curname),
1723 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1731 * We mark the path as needing recomputation, but don't do anything
1732 * until it's needed. This avoids trying to do database access during
1733 * GUC initialization.
1736 namespaceSearchPathValid = false;
1742 * InitializeSearchPath: initialize module during InitPostgres.
1744 * This is called after we are up enough to be able to do catalog lookups.
1747 InitializeSearchPath(void)
1749 if (IsBootstrapProcessingMode())
1752 * In bootstrap mode, the search path must be 'pg_catalog' so that
1753 * tables are created in the proper namespace; ignore the GUC
1756 MemoryContext oldcxt;
1758 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1759 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1760 MemoryContextSwitchTo(oldcxt);
1761 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1762 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1763 namespaceSearchPathValid = true;
1764 namespaceUser = GetUserId();
1769 * In normal mode, arrange for a callback on any syscache
1770 * invalidation of pg_namespace rows.
1772 CacheRegisterSyscacheCallback(NAMESPACEOID,
1775 /* Force search path to be recomputed on next use */
1776 namespaceSearchPathValid = false;
1782 * Syscache inval callback function
1785 NamespaceCallback(Datum arg, Oid relid)
1787 /* Force search path to be recomputed on next use */
1788 namespaceSearchPathValid = false;
1792 * Fetch the active search path, expressed as a List of OIDs.
1794 * The returned list includes the implicitly-prepended namespaces only if
1795 * includeImplicit is true.
1797 * NB: caller must treat the list as read-only!
1800 fetch_search_path(bool includeImplicit)
1804 recomputeNamespacePath();
1806 result = namespaceSearchPath;
1807 if (!includeImplicit)
1809 while (result && (Oid) lfirsti(result) != firstExplicitNamespace)
1810 result = lnext(result);
1817 * Export the FooIsVisible functions as SQL-callable functions.
1821 pg_table_is_visible(PG_FUNCTION_ARGS)
1823 Oid oid = PG_GETARG_OID(0);
1825 PG_RETURN_BOOL(RelationIsVisible(oid));
1829 pg_type_is_visible(PG_FUNCTION_ARGS)
1831 Oid oid = PG_GETARG_OID(0);
1833 PG_RETURN_BOOL(TypeIsVisible(oid));
1837 pg_function_is_visible(PG_FUNCTION_ARGS)
1839 Oid oid = PG_GETARG_OID(0);
1841 PG_RETURN_BOOL(FunctionIsVisible(oid));
1845 pg_operator_is_visible(PG_FUNCTION_ARGS)
1847 Oid oid = PG_GETARG_OID(0);
1849 PG_RETURN_BOOL(OperatorIsVisible(oid));
1853 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1855 Oid oid = PG_GETARG_OID(0);
1857 PG_RETURN_BOOL(OpclassIsVisible(oid));