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.50 2003/04/24 21:16:42 tgl Exp $
18 *-------------------------------------------------------------------------
22 #include "access/xact.h"
23 #include "catalog/catname.h"
24 #include "catalog/dependency.h"
25 #include "catalog/namespace.h"
26 #include "catalog/pg_conversion.h"
27 #include "catalog/pg_namespace.h"
28 #include "catalog/pg_opclass.h"
29 #include "catalog/pg_operator.h"
30 #include "catalog/pg_proc.h"
31 #include "catalog/pg_shadow.h"
32 #include "catalog/pg_type.h"
33 #include "lib/stringinfo.h"
34 #include "miscadmin.h"
35 #include "nodes/makefuncs.h"
36 #include "storage/backendid.h"
37 #include "storage/ipc.h"
38 #include "utils/acl.h"
39 #include "utils/builtins.h"
40 #include "utils/catcache.h"
41 #include "utils/inval.h"
42 #include "utils/lsyscache.h"
43 #include "utils/memutils.h"
44 #include "utils/syscache.h"
48 * The namespace search path is a possibly-empty list of namespace OIDs.
49 * In addition to the explicit list, several implicitly-searched namespaces
52 * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
53 * always searched first. (This is a hack for CREATE SCHEMA.)
55 * 2. If a TEMP table namespace has been initialized in this session, it
56 * is always searched just after any special namespace.
58 * 3. The system catalog namespace is always searched. If the system
59 * namespace is present in the explicit path then it will be searched in
60 * the specified order; otherwise it will be searched after TEMP tables and
61 * *before* the explicit list. (It might seem that the system namespace
62 * should be implicitly last, but this behavior appears to be required by
63 * SQL99. Also, this provides a way to search the system namespace first
64 * without thereby making it the default creation target namespace.)
66 * The default creation target namespace is normally equal to the first
67 * element of the explicit list, but is the "special" namespace when one
68 * has been set. If the explicit list is empty and there is no special
69 * namespace, there is no default target.
71 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
72 * the system namespace is the only one searched or inserted into.
73 * The initdb script is also careful to set search_path to 'pg_catalog' for
74 * its post-bootstrap standalone backend runs. Otherwise the default search
75 * path is determined by GUC. The factory default path contains the PUBLIC
76 * namespace (if it exists), preceded by the user's personal namespace
79 * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
80 * derived variables) need to be recomputed from namespace_search_path.
81 * We mark it invalid upon an assignment to namespace_search_path or receipt
82 * of a syscache invalidation event for pg_namespace. The recomputation
83 * is done during the next lookup attempt.
85 * Any namespaces mentioned in namespace_search_path that are not readable
86 * by the current user ID are simply left out of namespaceSearchPath; so
87 * we have to be willing to recompute the path when current userid changes.
88 * namespaceUser is the userid the path has been computed for.
91 static List *namespaceSearchPath = NIL;
93 static Oid namespaceUser = InvalidOid;
95 /* default place to create stuff; if InvalidOid, no default */
96 static Oid defaultCreationNamespace = InvalidOid;
98 /* first explicit member of list; usually same as defaultCreationNamespace */
99 static Oid firstExplicitNamespace = InvalidOid;
101 /* The above four values are valid only if namespaceSearchPathValid */
102 static bool namespaceSearchPathValid = true;
105 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
106 * in a particular backend session (this happens when a CREATE TEMP TABLE
107 * command is first executed). Thereafter it's the OID of the temp namespace.
108 * firstTempTransaction flags whether we've committed creation of the TEMP
111 static Oid myTempNamespace = InvalidOid;
113 static bool firstTempTransaction = false;
116 * "Special" namespace for CREATE SCHEMA. If set, it's the first search
117 * path element, and also the default creation namespace.
119 static Oid mySpecialNamespace = InvalidOid;
122 * This is the text equivalent of the search path --- it's the value
123 * of the GUC variable 'search_path'.
125 char *namespace_search_path = NULL;
128 /* Local functions */
129 static void recomputeNamespacePath(void);
130 static void InitTempTableNamespace(void);
131 static void RemoveTempRelations(Oid tempNamespaceId);
132 static void RemoveTempRelationsCallback(void);
133 static void NamespaceCallback(Datum arg, Oid relid);
135 /* These don't really need to appear in any header file */
136 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
137 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
138 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
139 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
140 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
141 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
146 * Given a RangeVar describing an existing relation,
147 * select the proper namespace and look up the relation OID.
149 * If the relation is not found, return InvalidOid if failOK = true,
150 * otherwise raise an error.
153 RangeVarGetRelid(const RangeVar *relation, bool failOK)
159 * We check the catalog name and then ignore it.
161 if (relation->catalogname)
163 if (strcmp(relation->catalogname, DatabaseName) != 0)
164 elog(ERROR, "Cross-database references are not implemented");
167 if (relation->schemaname)
169 /* use exact schema given */
170 namespaceId = LookupExplicitNamespace(relation->schemaname);
171 relId = get_relname_relid(relation->relname, namespaceId);
175 /* search the namespace path */
176 relId = RelnameGetRelid(relation->relname);
179 if (!OidIsValid(relId) && !failOK)
181 if (relation->schemaname)
182 elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
183 relation->schemaname, relation->relname);
185 elog(ERROR, "Relation \"%s\" does not exist",
192 * RangeVarGetCreationNamespace
193 * Given a RangeVar describing a to-be-created relation,
194 * choose which namespace to create it in.
196 * Note: calling this may result in a CommandCounterIncrement operation.
197 * That will happen on the first request for a temp table in any particular
198 * backend run; we will need to either create or clean out the temp schema.
201 RangeVarGetCreationNamespace(const RangeVar *newRelation)
206 * We check the catalog name and then ignore it.
208 if (newRelation->catalogname)
210 if (strcmp(newRelation->catalogname, DatabaseName) != 0)
211 elog(ERROR, "Cross-database references are not implemented");
214 if (newRelation->istemp)
216 /* TEMP tables are created in our backend-local temp namespace */
217 if (newRelation->schemaname)
218 elog(ERROR, "TEMP tables may not specify a namespace");
219 /* Initialize temp namespace if first time through */
220 if (!OidIsValid(myTempNamespace))
221 InitTempTableNamespace();
222 return myTempNamespace;
225 if (newRelation->schemaname)
227 /* use exact schema given */
228 namespaceId = GetSysCacheOid(NAMESPACENAME,
229 CStringGetDatum(newRelation->schemaname),
231 if (!OidIsValid(namespaceId))
232 elog(ERROR, "Namespace \"%s\" does not exist",
233 newRelation->schemaname);
234 /* we do not check for USAGE rights here! */
238 /* use the default creation namespace */
239 recomputeNamespacePath();
240 namespaceId = defaultCreationNamespace;
241 if (!OidIsValid(namespaceId))
242 elog(ERROR, "No namespace has been selected to create in");
245 /* Note: callers will check for CREATE rights when appropriate */
252 * Try to resolve an unqualified relation name.
253 * Returns OID if relation found in search path, else InvalidOid.
256 RelnameGetRelid(const char *relname)
261 recomputeNamespacePath();
263 foreach(lptr, namespaceSearchPath)
265 Oid namespaceId = lfirsto(lptr);
267 relid = get_relname_relid(relname, namespaceId);
268 if (OidIsValid(relid))
272 /* Not found in path */
279 * Determine whether a relation (identified by OID) is visible in the
280 * current search path. Visible means "would be found by searching
281 * for the unqualified relation name".
284 RelationIsVisible(Oid relid)
287 Form_pg_class relform;
291 reltup = SearchSysCache(RELOID,
292 ObjectIdGetDatum(relid),
294 if (!HeapTupleIsValid(reltup))
295 elog(ERROR, "Cache lookup failed for relation %u", relid);
296 relform = (Form_pg_class) GETSTRUCT(reltup);
298 recomputeNamespacePath();
301 * Quick check: if it ain't in the path at all, it ain't visible.
302 * Items in the system namespace are surely in the path and so we
303 * needn't even do oidMember() for them.
305 relnamespace = relform->relnamespace;
306 if (relnamespace != PG_CATALOG_NAMESPACE &&
307 !oidMember(relnamespace, namespaceSearchPath))
312 * If it is in the path, it might still not be visible; it could
313 * be hidden by another relation of the same name earlier in the
314 * path. So we must do a slow check to see if this rel would be
315 * found by RelnameGetRelid.
317 char *relname = NameStr(relform->relname);
319 visible = (RelnameGetRelid(relname) == relid);
322 ReleaseSysCache(reltup);
330 * Try to resolve an unqualified datatype name.
331 * Returns OID if type found in search path, else InvalidOid.
333 * This is essentially the same as RelnameGetRelid.
336 TypenameGetTypid(const char *typname)
341 recomputeNamespacePath();
343 foreach(lptr, namespaceSearchPath)
345 Oid namespaceId = lfirsto(lptr);
347 typid = GetSysCacheOid(TYPENAMENSP,
348 PointerGetDatum(typname),
349 ObjectIdGetDatum(namespaceId),
351 if (OidIsValid(typid))
355 /* Not found in path */
361 * Determine whether a type (identified by OID) is visible in the
362 * current search path. Visible means "would be found by searching
363 * for the unqualified type name".
366 TypeIsVisible(Oid typid)
369 Form_pg_type typform;
373 typtup = SearchSysCache(TYPEOID,
374 ObjectIdGetDatum(typid),
376 if (!HeapTupleIsValid(typtup))
377 elog(ERROR, "Cache lookup failed for type %u", typid);
378 typform = (Form_pg_type) GETSTRUCT(typtup);
380 recomputeNamespacePath();
383 * Quick check: if it ain't in the path at all, it ain't visible.
384 * Items in the system namespace are surely in the path and so we
385 * needn't even do oidMember() for them.
387 typnamespace = typform->typnamespace;
388 if (typnamespace != PG_CATALOG_NAMESPACE &&
389 !oidMember(typnamespace, namespaceSearchPath))
394 * If it is in the path, it might still not be visible; it could
395 * be hidden by another type of the same name earlier in the path.
396 * So we must do a slow check to see if this type would be found
397 * by TypenameGetTypid.
399 char *typname = NameStr(typform->typname);
401 visible = (TypenameGetTypid(typname) == typid);
404 ReleaseSysCache(typtup);
411 * FuncnameGetCandidates
412 * Given a possibly-qualified function name and argument count,
413 * retrieve a list of the possible matches.
415 * If nargs is -1, we return all functions matching the given name,
416 * regardless of argument count.
418 * We search a single namespace if the function name is qualified, else
419 * all namespaces in the search path. The return list will never contain
420 * multiple entries with identical argument lists --- in the multiple-
421 * namespace case, we arrange for entries in earlier namespaces to mask
422 * identical entries in later namespaces.
425 FuncnameGetCandidates(List *names, int nargs)
427 FuncCandidateList resultList = NULL;
434 /* deconstruct the name list */
435 DeconstructQualifiedName(names, &schemaname, &funcname);
439 /* use exact schema given */
440 namespaceId = LookupExplicitNamespace(schemaname);
444 /* flag to indicate we need namespace search */
445 namespaceId = InvalidOid;
446 recomputeNamespacePath();
449 /* Search syscache by name and (optionally) nargs only */
451 catlist = SearchSysCacheList(PROCNAMENSP, 2,
452 CStringGetDatum(funcname),
453 Int16GetDatum(nargs),
456 catlist = SearchSysCacheList(PROCNAMENSP, 1,
457 CStringGetDatum(funcname),
460 for (i = 0; i < catlist->n_members; i++)
462 HeapTuple proctup = &catlist->members[i]->tuple;
463 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
465 FuncCandidateList newResult;
467 nargs = procform->pronargs;
469 if (OidIsValid(namespaceId))
471 /* Consider only procs in specified namespace */
472 if (procform->pronamespace != namespaceId)
474 /* No need to check args, they must all be different */
478 /* Consider only procs that are in the search path */
481 foreach(nsp, namespaceSearchPath)
483 if (procform->pronamespace == lfirsto(nsp))
488 continue; /* proc is not in search path */
491 * Okay, it's in the search path, but does it have the same
492 * arguments as something we already accepted? If so, keep
493 * only the one that appears earlier in the search path.
495 * If we have an ordered list from SearchSysCacheList (the normal
496 * case), then any conflicting proc must immediately adjoin
497 * this one in the list, so we only need to look at the newest
498 * result item. If we have an unordered list, we have to scan
499 * the whole result list.
503 FuncCandidateList prevResult;
505 if (catlist->ordered)
507 if (nargs == resultList->nargs &&
508 memcmp(procform->proargtypes, resultList->args,
509 nargs * sizeof(Oid)) == 0)
510 prevResult = resultList;
516 for (prevResult = resultList;
518 prevResult = prevResult->next)
520 if (nargs == prevResult->nargs &&
521 memcmp(procform->proargtypes, prevResult->args,
522 nargs * sizeof(Oid)) == 0)
528 /* We have a match with a previous result */
529 Assert(pathpos != prevResult->pathpos);
530 if (pathpos > prevResult->pathpos)
531 continue; /* keep previous result */
532 /* replace previous result */
533 prevResult->pathpos = pathpos;
534 prevResult->oid = HeapTupleGetOid(proctup);
535 continue; /* args are same, of course */
541 * Okay to add it to result list
543 newResult = (FuncCandidateList)
544 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
545 + nargs * sizeof(Oid));
546 newResult->pathpos = pathpos;
547 newResult->oid = HeapTupleGetOid(proctup);
548 newResult->nargs = nargs;
549 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
551 newResult->next = resultList;
552 resultList = newResult;
555 ReleaseSysCacheList(catlist);
562 * Determine whether a function (identified by OID) is visible in the
563 * current search path. Visible means "would be found by searching
564 * for the unqualified function name with exact argument matches".
567 FunctionIsVisible(Oid funcid)
570 Form_pg_proc procform;
574 proctup = SearchSysCache(PROCOID,
575 ObjectIdGetDatum(funcid),
577 if (!HeapTupleIsValid(proctup))
578 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
579 procform = (Form_pg_proc) GETSTRUCT(proctup);
581 recomputeNamespacePath();
584 * Quick check: if it ain't in the path at all, it ain't visible.
585 * Items in the system namespace are surely in the path and so we
586 * needn't even do oidMember() for them.
588 pronamespace = procform->pronamespace;
589 if (pronamespace != PG_CATALOG_NAMESPACE &&
590 !oidMember(pronamespace, namespaceSearchPath))
595 * If it is in the path, it might still not be visible; it could
596 * be hidden by another proc of the same name and arguments
597 * earlier in the path. So we must do a slow check to see if this
598 * is the same proc that would be found by FuncnameGetCandidates.
600 char *proname = NameStr(procform->proname);
601 int nargs = procform->pronargs;
602 FuncCandidateList clist;
606 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
608 for (; clist; clist = clist->next)
610 if (memcmp(clist->args, procform->proargtypes,
611 nargs * sizeof(Oid)) == 0)
613 /* Found the expected entry; is it the right proc? */
614 visible = (clist->oid == funcid);
620 ReleaseSysCache(proctup);
627 * OpernameGetCandidates
628 * Given a possibly-qualified operator name and operator kind,
629 * retrieve a list of the possible matches.
631 * If oprkind is '\0', we return all operators matching the given name,
632 * regardless of arguments.
634 * We search a single namespace if the operator name is qualified, else
635 * all namespaces in the search path. The return list will never contain
636 * multiple entries with identical argument lists --- in the multiple-
637 * namespace case, we arrange for entries in earlier namespaces to mask
638 * identical entries in later namespaces.
640 * The returned items always have two args[] entries --- one or the other
641 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
644 OpernameGetCandidates(List *names, char oprkind)
646 FuncCandidateList resultList = NULL;
653 /* deconstruct the name list */
654 DeconstructQualifiedName(names, &schemaname, &opername);
658 /* use exact schema given */
659 namespaceId = LookupExplicitNamespace(schemaname);
663 /* flag to indicate we need namespace search */
664 namespaceId = InvalidOid;
665 recomputeNamespacePath();
668 /* Search syscache by name only */
669 catlist = SearchSysCacheList(OPERNAMENSP, 1,
670 CStringGetDatum(opername),
673 for (i = 0; i < catlist->n_members; i++)
675 HeapTuple opertup = &catlist->members[i]->tuple;
676 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
678 FuncCandidateList newResult;
680 /* Ignore operators of wrong kind, if specific kind requested */
681 if (oprkind && operform->oprkind != oprkind)
684 if (OidIsValid(namespaceId))
686 /* Consider only opers in specified namespace */
687 if (operform->oprnamespace != namespaceId)
689 /* No need to check args, they must all be different */
693 /* Consider only opers that are in the search path */
696 foreach(nsp, namespaceSearchPath)
698 if (operform->oprnamespace == lfirsto(nsp))
703 continue; /* oper is not in search path */
706 * Okay, it's in the search path, but does it have the same
707 * arguments as something we already accepted? If so, keep
708 * only the one that appears earlier in the search path.
710 * If we have an ordered list from SearchSysCacheList (the normal
711 * case), then any conflicting oper must immediately adjoin
712 * this one in the list, so we only need to look at the newest
713 * result item. If we have an unordered list, we have to scan
714 * the whole result list.
718 FuncCandidateList prevResult;
720 if (catlist->ordered)
722 if (operform->oprleft == resultList->args[0] &&
723 operform->oprright == resultList->args[1])
724 prevResult = resultList;
730 for (prevResult = resultList;
732 prevResult = prevResult->next)
734 if (operform->oprleft == prevResult->args[0] &&
735 operform->oprright == prevResult->args[1])
741 /* We have a match with a previous result */
742 Assert(pathpos != prevResult->pathpos);
743 if (pathpos > prevResult->pathpos)
744 continue; /* keep previous result */
745 /* replace previous result */
746 prevResult->pathpos = pathpos;
747 prevResult->oid = HeapTupleGetOid(opertup);
748 continue; /* args are same, of course */
754 * Okay to add it to result list
756 newResult = (FuncCandidateList)
757 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
758 newResult->pathpos = pathpos;
759 newResult->oid = HeapTupleGetOid(opertup);
760 newResult->nargs = 2;
761 newResult->args[0] = operform->oprleft;
762 newResult->args[1] = operform->oprright;
763 newResult->next = resultList;
764 resultList = newResult;
767 ReleaseSysCacheList(catlist);
774 * Determine whether an operator (identified by OID) is visible in the
775 * current search path. Visible means "would be found by searching
776 * for the unqualified operator name with exact argument matches".
779 OperatorIsVisible(Oid oprid)
782 Form_pg_operator oprform;
786 oprtup = SearchSysCache(OPEROID,
787 ObjectIdGetDatum(oprid),
789 if (!HeapTupleIsValid(oprtup))
790 elog(ERROR, "Cache lookup failed for operator %u", oprid);
791 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
793 recomputeNamespacePath();
796 * Quick check: if it ain't in the path at all, it ain't visible.
797 * Items in the system namespace are surely in the path and so we
798 * needn't even do oidMember() for them.
800 oprnamespace = oprform->oprnamespace;
801 if (oprnamespace != PG_CATALOG_NAMESPACE &&
802 !oidMember(oprnamespace, namespaceSearchPath))
807 * If it is in the path, it might still not be visible; it could
808 * be hidden by another operator of the same name and arguments
809 * earlier in the path. So we must do a slow check to see if this
810 * is the same operator that would be found by
811 * OpernameGetCandidates.
813 char *oprname = NameStr(oprform->oprname);
814 FuncCandidateList clist;
818 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
821 for (; clist; clist = clist->next)
823 if (clist->args[0] == oprform->oprleft &&
824 clist->args[1] == oprform->oprright)
826 /* Found the expected entry; is it the right op? */
827 visible = (clist->oid == oprid);
833 ReleaseSysCache(oprtup);
840 * OpclassGetCandidates
841 * Given an index access method OID, retrieve a list of all the
842 * opclasses for that AM that are visible in the search path.
844 * NOTE: the opcname_tmp field in the returned structs should not be used
845 * by callers, because it points at syscache entries that we release at
846 * the end of this routine. If any callers needed the name information,
847 * we could pstrdup() the names ... but at present it'd be wasteful.
850 OpclassGetCandidates(Oid amid)
852 OpclassCandidateList resultList = NULL;
856 /* Search syscache by AM OID only */
857 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
858 ObjectIdGetDatum(amid),
861 recomputeNamespacePath();
863 for (i = 0; i < catlist->n_members; i++)
865 HeapTuple opctup = &catlist->members[i]->tuple;
866 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
868 OpclassCandidateList newResult;
871 /* Consider only opclasses that are in the search path */
872 foreach(nsp, namespaceSearchPath)
874 if (opcform->opcnamespace == lfirsto(nsp))
879 continue; /* opclass is not in search path */
882 * Okay, it's in the search path, but does it have the same name
883 * as something we already accepted? If so, keep only the one
884 * that appears earlier in the search path.
886 * If we have an ordered list from SearchSysCacheList (the normal
887 * case), then any conflicting opclass must immediately adjoin
888 * this one in the list, so we only need to look at the newest
889 * result item. If we have an unordered list, we have to scan the
894 OpclassCandidateList prevResult;
896 if (catlist->ordered)
898 if (strcmp(NameStr(opcform->opcname),
899 resultList->opcname_tmp) == 0)
900 prevResult = resultList;
906 for (prevResult = resultList;
908 prevResult = prevResult->next)
910 if (strcmp(NameStr(opcform->opcname),
911 prevResult->opcname_tmp) == 0)
917 /* We have a match with a previous result */
918 Assert(pathpos != prevResult->pathpos);
919 if (pathpos > prevResult->pathpos)
920 continue; /* keep previous result */
921 /* replace previous result */
922 prevResult->opcname_tmp = NameStr(opcform->opcname);
923 prevResult->pathpos = pathpos;
924 prevResult->oid = HeapTupleGetOid(opctup);
925 prevResult->opcintype = opcform->opcintype;
926 prevResult->opcdefault = opcform->opcdefault;
927 prevResult->opckeytype = opcform->opckeytype;
933 * Okay to add it to result list
935 newResult = (OpclassCandidateList)
936 palloc(sizeof(struct _OpclassCandidateList));
937 newResult->opcname_tmp = NameStr(opcform->opcname);
938 newResult->pathpos = pathpos;
939 newResult->oid = HeapTupleGetOid(opctup);
940 newResult->opcintype = opcform->opcintype;
941 newResult->opcdefault = opcform->opcdefault;
942 newResult->opckeytype = opcform->opckeytype;
943 newResult->next = resultList;
944 resultList = newResult;
947 ReleaseSysCacheList(catlist);
953 * OpclassnameGetOpcid
954 * Try to resolve an unqualified index opclass name.
955 * Returns OID if opclass found in search path, else InvalidOid.
957 * This is essentially the same as TypenameGetTypid, but we have to have
958 * an extra argument for the index AM OID.
961 OpclassnameGetOpcid(Oid amid, const char *opcname)
966 recomputeNamespacePath();
968 foreach(lptr, namespaceSearchPath)
970 Oid namespaceId = lfirsto(lptr);
972 opcid = GetSysCacheOid(CLAAMNAMENSP,
973 ObjectIdGetDatum(amid),
974 PointerGetDatum(opcname),
975 ObjectIdGetDatum(namespaceId),
977 if (OidIsValid(opcid))
981 /* Not found in path */
987 * Determine whether an opclass (identified by OID) is visible in the
988 * current search path. Visible means "would be found by searching
989 * for the unqualified opclass name".
992 OpclassIsVisible(Oid opcid)
995 Form_pg_opclass opcform;
999 opctup = SearchSysCache(CLAOID,
1000 ObjectIdGetDatum(opcid),
1002 if (!HeapTupleIsValid(opctup))
1003 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1004 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1006 recomputeNamespacePath();
1009 * Quick check: if it ain't in the path at all, it ain't visible.
1010 * Items in the system namespace are surely in the path and so we
1011 * needn't even do oidMember() for them.
1013 opcnamespace = opcform->opcnamespace;
1014 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1015 !oidMember(opcnamespace, namespaceSearchPath))
1020 * If it is in the path, it might still not be visible; it could
1021 * be hidden by another opclass of the same name earlier in the
1022 * path. So we must do a slow check to see if this opclass would
1023 * be found by OpclassnameGetOpcid.
1025 char *opcname = NameStr(opcform->opcname);
1027 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1030 ReleaseSysCache(opctup);
1036 * ConversionGetConid
1037 * Try to resolve an unqualified conversion name.
1038 * Returns OID if conversion found in search path, else InvalidOid.
1040 * This is essentially the same as RelnameGetRelid.
1043 ConversionGetConid(const char *conname)
1048 recomputeNamespacePath();
1050 foreach(lptr, namespaceSearchPath)
1052 Oid namespaceId = lfirsto(lptr);
1054 conid = GetSysCacheOid(CONNAMENSP,
1055 PointerGetDatum(conname),
1056 ObjectIdGetDatum(namespaceId),
1058 if (OidIsValid(conid))
1062 /* Not found in path */
1067 * ConversionIsVisible
1068 * Determine whether a conversion (identified by OID) is visible in the
1069 * current search path. Visible means "would be found by searching
1070 * for the unqualified conversion name".
1073 ConversionIsVisible(Oid conid)
1076 Form_pg_conversion conform;
1080 contup = SearchSysCache(CONOID,
1081 ObjectIdGetDatum(conid),
1083 if (!HeapTupleIsValid(contup))
1084 elog(ERROR, "Cache lookup failed for conversion %u", conid);
1085 conform = (Form_pg_conversion) GETSTRUCT(contup);
1087 recomputeNamespacePath();
1090 * Quick check: if it ain't in the path at all, it ain't visible.
1091 * Items in the system namespace are surely in the path and so we
1092 * needn't even do oidMember() for them.
1094 connamespace = conform->connamespace;
1095 if (connamespace != PG_CATALOG_NAMESPACE &&
1096 !oidMember(connamespace, namespaceSearchPath))
1101 * If it is in the path, it might still not be visible; it could
1102 * be hidden by another conversion of the same name earlier in the
1103 * path. So we must do a slow check to see if this conversion would
1104 * be found by ConversionGetConid.
1106 char *conname = NameStr(conform->conname);
1108 visible = (ConversionGetConid(conname) == conid);
1111 ReleaseSysCache(contup);
1117 * DeconstructQualifiedName
1118 * Given a possibly-qualified name expressed as a list of String nodes,
1119 * extract the schema name and object name.
1121 * *nspname_p is set to NULL if there is no explicit schema name.
1124 DeconstructQualifiedName(List *names,
1129 char *schemaname = NULL;
1130 char *objname = NULL;
1132 switch (length(names))
1135 objname = strVal(lfirst(names));
1138 schemaname = strVal(lfirst(names));
1139 objname = strVal(lsecond(names));
1142 catalogname = strVal(lfirst(names));
1143 schemaname = strVal(lsecond(names));
1144 objname = strVal(lthird(names));
1147 * We check the catalog name and then ignore it.
1149 if (strcmp(catalogname, DatabaseName) != 0)
1150 elog(ERROR, "Cross-database references are not implemented");
1153 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1154 NameListToString(names));
1158 *nspname_p = schemaname;
1159 *objname_p = objname;
1163 * LookupExplicitNamespace
1164 * Process an explicitly-specified schema name: look up the schema
1165 * and verify we have USAGE (lookup) rights in it.
1167 * Returns the namespace OID. Raises elog if any problem.
1170 LookupExplicitNamespace(const char *nspname)
1173 AclResult aclresult;
1175 namespaceId = GetSysCacheOid(NAMESPACENAME,
1176 CStringGetDatum(nspname),
1178 if (!OidIsValid(namespaceId))
1179 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1181 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1182 if (aclresult != ACLCHECK_OK)
1183 aclcheck_error(aclresult, nspname);
1189 * QualifiedNameGetCreationNamespace
1190 * Given a possibly-qualified name for an object (in List-of-Values
1191 * format), determine what namespace the object should be created in.
1192 * Also extract and return the object name (last component of list).
1194 * This is *not* used for tables. Hence, the TEMP table namespace is
1195 * never selected as the creation target.
1198 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1204 /* deconstruct the name list */
1205 DeconstructQualifiedName(names, &schemaname, &objname);
1209 /* use exact schema given */
1210 namespaceId = GetSysCacheOid(NAMESPACENAME,
1211 CStringGetDatum(schemaname),
1213 if (!OidIsValid(namespaceId))
1214 elog(ERROR, "Namespace \"%s\" does not exist",
1216 /* we do not check for USAGE rights here! */
1220 /* use the default creation namespace */
1221 recomputeNamespacePath();
1222 namespaceId = defaultCreationNamespace;
1223 if (!OidIsValid(namespaceId))
1224 elog(ERROR, "No namespace has been selected to create in");
1227 /* Note: callers will check for CREATE rights when appropriate */
1229 *objname_p = objname;
1234 * makeRangeVarFromNameList
1235 * Utility routine to convert a qualified-name list into RangeVar form.
1238 makeRangeVarFromNameList(List *names)
1240 RangeVar *rel = makeRangeVar(NULL, NULL);
1242 switch (length(names))
1245 rel->relname = strVal(lfirst(names));
1248 rel->schemaname = strVal(lfirst(names));
1249 rel->relname = strVal(lsecond(names));
1252 rel->catalogname = strVal(lfirst(names));
1253 rel->schemaname = strVal(lsecond(names));
1254 rel->relname = strVal(lthird(names));
1257 elog(ERROR, "Improper relation name (too many dotted names)");
1266 * Utility routine to convert a qualified-name list into a string.
1268 * This is used primarily to form error messages, and so we do not quote
1269 * the list elements, for the sake of legibility.
1272 NameListToString(List *names)
1274 StringInfoData string;
1277 initStringInfo(&string);
1282 appendStringInfoChar(&string, '.');
1283 appendStringInfoString(&string, strVal(lfirst(l)));
1290 * NameListToQuotedString
1291 * Utility routine to convert a qualified-name list into a string.
1293 * Same as above except that names will be double-quoted where necessary,
1294 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1297 NameListToQuotedString(List *names)
1299 StringInfoData string;
1302 initStringInfo(&string);
1307 appendStringInfoChar(&string, '.');
1308 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1315 * isTempNamespace - is the given namespace my temporary-table namespace?
1318 isTempNamespace(Oid namespaceId)
1320 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1326 * isOtherTempNamespace - is the given namespace some other backend's
1327 * temporary-table namespace?
1330 isOtherTempNamespace(Oid namespaceId)
1335 /* If it's my own temp namespace, say "false" */
1336 if (isTempNamespace(namespaceId))
1338 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1339 nspname = get_namespace_name(namespaceId);
1341 return false; /* no such namespace? */
1342 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1348 * PushSpecialNamespace - push a "special" namespace onto the front of the
1351 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1352 * Although the API is defined to allow a stack of pushed namespaces, we
1353 * presently only support one at a time.
1355 * The pushed namespace will be removed from the search path at end of
1356 * transaction, whether commit or abort.
1359 PushSpecialNamespace(Oid namespaceId)
1361 Assert(!OidIsValid(mySpecialNamespace));
1362 mySpecialNamespace = namespaceId;
1363 namespaceSearchPathValid = false;
1367 * PopSpecialNamespace - remove previously pushed special namespace.
1370 PopSpecialNamespace(Oid namespaceId)
1372 Assert(mySpecialNamespace == namespaceId);
1373 mySpecialNamespace = InvalidOid;
1374 namespaceSearchPathValid = false;
1378 * FindConversionByName - find a conversion by possibly qualified name
1381 FindConversionByName(List *name)
1384 char *conversion_name;
1389 /* deconstruct the name list */
1390 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1394 /* use exact schema given */
1395 namespaceId = LookupExplicitNamespace(schemaname);
1396 return FindConversion(conversion_name, namespaceId);
1400 /* search for it in search path */
1401 recomputeNamespacePath();
1403 foreach(lptr, namespaceSearchPath)
1405 namespaceId = lfirsto(lptr);
1406 conoid = FindConversion(conversion_name, namespaceId);
1407 if (OidIsValid(conoid))
1412 /* Not found in path */
1417 * FindDefaultConversionProc - find default encoding conversion proc
1420 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1425 recomputeNamespacePath();
1427 foreach(lptr, namespaceSearchPath)
1429 Oid namespaceId = lfirsto(lptr);
1431 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1432 if (OidIsValid(proc))
1436 /* Not found in path */
1441 * recomputeNamespacePath - recompute path derived variables if needed.
1444 recomputeNamespacePath(void)
1446 AclId userId = GetUserId();
1453 MemoryContext oldcxt;
1456 * Do nothing if path is already valid.
1458 if (namespaceSearchPathValid && namespaceUser == userId)
1461 /* Need a modifiable copy of namespace_search_path string */
1462 rawname = pstrdup(namespace_search_path);
1464 /* Parse string into list of identifiers */
1465 if (!SplitIdentifierString(rawname, ',', &namelist))
1467 /* syntax error in name list */
1468 /* this should not happen if GUC checked check_search_path */
1469 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1473 * Convert the list of names to a list of OIDs. If any names are not
1474 * recognizable or we don't have read access, just leave them out of
1475 * the list. (We can't raise an error, since the search_path setting
1476 * has already been accepted.) Don't make duplicate entries, either.
1479 foreach(l, namelist)
1481 char *curname = (char *) lfirst(l);
1484 if (strcmp(curname, "$user") == 0)
1486 /* $user --- substitute namespace matching user name, if any */
1489 tuple = SearchSysCache(SHADOWSYSID,
1490 ObjectIdGetDatum(userId),
1492 if (HeapTupleIsValid(tuple))
1496 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1497 namespaceId = GetSysCacheOid(NAMESPACENAME,
1498 CStringGetDatum(uname),
1500 ReleaseSysCache(tuple);
1501 if (OidIsValid(namespaceId) &&
1502 !oidMember(namespaceId, oidlist) &&
1503 pg_namespace_aclcheck(namespaceId, userId,
1504 ACL_USAGE) == ACLCHECK_OK)
1505 oidlist = lappendo(oidlist, namespaceId);
1510 /* normal namespace reference */
1511 namespaceId = GetSysCacheOid(NAMESPACENAME,
1512 CStringGetDatum(curname),
1514 if (OidIsValid(namespaceId) &&
1515 !oidMember(namespaceId, oidlist) &&
1516 pg_namespace_aclcheck(namespaceId, userId,
1517 ACL_USAGE) == ACLCHECK_OK)
1518 oidlist = lappendo(oidlist, namespaceId);
1523 * Remember the first member of the explicit list.
1526 firstNS = InvalidOid;
1528 firstNS = lfirsto(oidlist);
1531 * Add any implicitly-searched namespaces to the list. Note these go
1532 * on the front, not the back; also notice that we do not check USAGE
1533 * permissions for these.
1535 if (!oidMember(PG_CATALOG_NAMESPACE, oidlist))
1536 oidlist = lconso(PG_CATALOG_NAMESPACE, oidlist);
1538 if (OidIsValid(myTempNamespace) &&
1539 !oidMember(myTempNamespace, oidlist))
1540 oidlist = lconso(myTempNamespace, oidlist);
1542 if (OidIsValid(mySpecialNamespace) &&
1543 !oidMember(mySpecialNamespace, oidlist))
1544 oidlist = lconso(mySpecialNamespace, oidlist);
1547 * Now that we've successfully built the new list of namespace OIDs,
1548 * save it in permanent storage.
1550 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1551 newpath = listCopy(oidlist);
1552 MemoryContextSwitchTo(oldcxt);
1554 /* Now safe to assign to state variable. */
1555 freeList(namespaceSearchPath);
1556 namespaceSearchPath = newpath;
1559 * Update info derived from search path.
1561 firstExplicitNamespace = firstNS;
1562 if (OidIsValid(mySpecialNamespace))
1563 defaultCreationNamespace = mySpecialNamespace;
1565 defaultCreationNamespace = firstNS;
1567 /* Mark the path valid. */
1568 namespaceSearchPathValid = true;
1569 namespaceUser = userId;
1578 * InitTempTableNamespace
1579 * Initialize temp table namespace on first use in a particular backend
1582 InitTempTableNamespace(void)
1584 char namespaceName[NAMEDATALEN];
1588 * First, do permission check to see if we are authorized to make temp
1589 * tables. We use a nonstandard error message here since
1590 * "databasename: permission denied" might be a tad cryptic.
1592 * Note we apply the check to the session user, not the currently active
1593 * userid, since we are not going to change our minds about temp table
1594 * availability during the session.
1596 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1597 ACL_CREATE_TEMP) != ACLCHECK_OK)
1598 elog(ERROR, "%s: not authorized to create temp tables",
1601 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1603 namespaceId = GetSysCacheOid(NAMESPACENAME,
1604 CStringGetDatum(namespaceName),
1606 if (!OidIsValid(namespaceId))
1609 * First use of this temp namespace in this database; create it.
1610 * The temp namespaces are always owned by the superuser. We
1611 * leave their permissions at default --- i.e., no access except
1612 * to superuser --- to ensure that unprivileged users can't peek
1613 * at other backends' temp tables. This works because the places
1614 * that access the temp namespace for my own backend skip
1615 * permissions checks on it.
1617 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1618 /* Advance command counter to make namespace visible */
1619 CommandCounterIncrement();
1624 * If the namespace already exists, clean it out (in case the
1625 * former owner crashed without doing so).
1627 RemoveTempRelations(namespaceId);
1631 * Okay, we've prepared the temp namespace ... but it's not committed
1632 * yet, so all our work could be undone by transaction rollback. Set
1633 * flag for AtEOXact_Namespace to know what to do.
1635 myTempNamespace = namespaceId;
1637 firstTempTransaction = true;
1639 namespaceSearchPathValid = false; /* need to rebuild list */
1643 * End-of-transaction cleanup for namespaces.
1646 AtEOXact_Namespace(bool isCommit)
1649 * If we abort the transaction in which a temp namespace was selected,
1650 * we'll have to do any creation or cleanout work over again. So,
1651 * just forget the namespace entirely until next time. On the other
1652 * hand, if we commit then register an exit callback to clean out the
1653 * temp tables at backend shutdown. (We only want to register the
1654 * callback once per session, so this is a good place to do it.)
1656 if (firstTempTransaction)
1659 on_shmem_exit(RemoveTempRelationsCallback, 0);
1662 myTempNamespace = InvalidOid;
1663 namespaceSearchPathValid = false; /* need to rebuild list */
1665 firstTempTransaction = false;
1669 * Clean up if someone failed to do PopSpecialNamespace
1671 if (OidIsValid(mySpecialNamespace))
1673 mySpecialNamespace = InvalidOid;
1674 namespaceSearchPathValid = false; /* need to rebuild list */
1679 * Remove all relations in the specified temp namespace.
1681 * This is called at backend shutdown (if we made any temp relations).
1682 * It is also called when we begin using a pre-existing temp namespace,
1683 * in order to clean out any relations that might have been created by
1684 * a crashed backend.
1687 RemoveTempRelations(Oid tempNamespaceId)
1689 ObjectAddress object;
1692 * We want to get rid of everything in the target namespace, but not
1693 * the namespace itself (deleting it only to recreate it later would be
1694 * a waste of cycles). We do this by finding everything that has a
1695 * dependency on the namespace.
1697 object.classId = get_system_catalog_relid(NamespaceRelationName);
1698 object.objectId = tempNamespaceId;
1699 object.objectSubId = 0;
1701 deleteWhatDependsOn(&object, false);
1705 * Callback to remove temp relations at backend exit.
1708 RemoveTempRelationsCallback(void)
1710 if (OidIsValid(myTempNamespace)) /* should always be true */
1712 /* Need to ensure we have a usable transaction. */
1713 AbortOutOfAnyTransaction();
1714 StartTransactionCommand(true);
1716 RemoveTempRelations(myTempNamespace);
1718 CommitTransactionCommand(true);
1724 * Routines for handling the GUC variable 'search_path'.
1727 /* assign_hook: validate new search_path, do extra actions as needed */
1729 assign_search_path(const char *newval, bool doit, bool interactive)
1735 /* Need a modifiable copy of string */
1736 rawname = pstrdup(newval);
1738 /* Parse string into list of identifiers */
1739 if (!SplitIdentifierString(rawname, ',', &namelist))
1741 /* syntax error in name list */
1748 * If we aren't inside a transaction, we cannot do database access so
1749 * cannot verify the individual names. Must accept the list on faith.
1751 if (interactive && IsTransactionState())
1754 * Verify that all the names are either valid namespace names or
1755 * "$user". We do not require $user to correspond to a valid
1756 * namespace. We do not check for USAGE rights, either; should
1759 foreach(l, namelist)
1761 char *curname = (char *) lfirst(l);
1763 if (strcmp(curname, "$user") == 0)
1765 if (!SearchSysCacheExists(NAMESPACENAME,
1766 CStringGetDatum(curname),
1768 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1776 * We mark the path as needing recomputation, but don't do anything
1777 * until it's needed. This avoids trying to do database access during
1778 * GUC initialization.
1781 namespaceSearchPathValid = false;
1787 * InitializeSearchPath: initialize module during InitPostgres.
1789 * This is called after we are up enough to be able to do catalog lookups.
1792 InitializeSearchPath(void)
1794 if (IsBootstrapProcessingMode())
1797 * In bootstrap mode, the search path must be 'pg_catalog' so that
1798 * tables are created in the proper namespace; ignore the GUC
1801 MemoryContext oldcxt;
1803 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1804 namespaceSearchPath = makeListo1(PG_CATALOG_NAMESPACE);
1805 MemoryContextSwitchTo(oldcxt);
1806 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1807 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1808 namespaceSearchPathValid = true;
1809 namespaceUser = GetUserId();
1814 * In normal mode, arrange for a callback on any syscache
1815 * invalidation of pg_namespace rows.
1817 CacheRegisterSyscacheCallback(NAMESPACEOID,
1820 /* Force search path to be recomputed on next use */
1821 namespaceSearchPathValid = false;
1827 * Syscache inval callback function
1830 NamespaceCallback(Datum arg, Oid relid)
1832 /* Force search path to be recomputed on next use */
1833 namespaceSearchPathValid = false;
1837 * Fetch the active search path, expressed as a List of OIDs.
1839 * The returned list includes the implicitly-prepended namespaces only if
1840 * includeImplicit is true.
1842 * NB: caller must treat the list as read-only!
1845 fetch_search_path(bool includeImplicit)
1849 recomputeNamespacePath();
1851 result = namespaceSearchPath;
1852 if (!includeImplicit)
1854 while (result && lfirsto(result) != firstExplicitNamespace)
1855 result = lnext(result);
1862 * Export the FooIsVisible functions as SQL-callable functions.
1866 pg_table_is_visible(PG_FUNCTION_ARGS)
1868 Oid oid = PG_GETARG_OID(0);
1870 PG_RETURN_BOOL(RelationIsVisible(oid));
1874 pg_type_is_visible(PG_FUNCTION_ARGS)
1876 Oid oid = PG_GETARG_OID(0);
1878 PG_RETURN_BOOL(TypeIsVisible(oid));
1882 pg_function_is_visible(PG_FUNCTION_ARGS)
1884 Oid oid = PG_GETARG_OID(0);
1886 PG_RETURN_BOOL(FunctionIsVisible(oid));
1890 pg_operator_is_visible(PG_FUNCTION_ARGS)
1892 Oid oid = PG_GETARG_OID(0);
1894 PG_RETURN_BOOL(OperatorIsVisible(oid));
1898 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1900 Oid oid = PG_GETARG_OID(0);
1902 PG_RETURN_BOOL(OpclassIsVisible(oid));
1906 pg_conversion_is_visible(PG_FUNCTION_ARGS)
1908 Oid oid = PG_GETARG_OID(0);
1910 PG_RETURN_BOOL(ConversionIsVisible(oid));