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.53 2003/06/27 17:03:29 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 "commands/dbcommands.h"
34 #include "lib/stringinfo.h"
35 #include "miscadmin.h"
36 #include "nodes/makefuncs.h"
37 #include "storage/backendid.h"
38 #include "storage/ipc.h"
39 #include "utils/acl.h"
40 #include "utils/builtins.h"
41 #include "utils/catcache.h"
42 #include "utils/inval.h"
43 #include "utils/lsyscache.h"
44 #include "utils/memutils.h"
45 #include "utils/syscache.h"
49 * The namespace search path is a possibly-empty list of namespace OIDs.
50 * In addition to the explicit list, several implicitly-searched namespaces
53 * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
54 * always searched first. (This is a hack for CREATE SCHEMA.)
56 * 2. If a TEMP table namespace has been initialized in this session, it
57 * is always searched just after any special namespace.
59 * 3. The system catalog namespace is always searched. If the system
60 * namespace is present in the explicit path then it will be searched in
61 * the specified order; otherwise it will be searched after TEMP tables and
62 * *before* the explicit list. (It might seem that the system namespace
63 * should be implicitly last, but this behavior appears to be required by
64 * SQL99. Also, this provides a way to search the system namespace first
65 * without thereby making it the default creation target namespace.)
67 * The default creation target namespace is normally equal to the first
68 * element of the explicit list, but is the "special" namespace when one
69 * has been set. If the explicit list is empty and there is no special
70 * namespace, there is no default target.
72 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
73 * the system namespace is the only one searched or inserted into.
74 * The initdb script is also careful to set search_path to 'pg_catalog' for
75 * its post-bootstrap standalone backend runs. Otherwise the default search
76 * path is determined by GUC. The factory default path contains the PUBLIC
77 * namespace (if it exists), preceded by the user's personal namespace
80 * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
81 * derived variables) need to be recomputed from namespace_search_path.
82 * We mark it invalid upon an assignment to namespace_search_path or receipt
83 * of a syscache invalidation event for pg_namespace. The recomputation
84 * is done during the next lookup attempt.
86 * Any namespaces mentioned in namespace_search_path that are not readable
87 * by the current user ID are simply left out of namespaceSearchPath; so
88 * we have to be willing to recompute the path when current userid changes.
89 * namespaceUser is the userid the path has been computed for.
92 static List *namespaceSearchPath = NIL;
94 static Oid namespaceUser = InvalidOid;
96 /* default place to create stuff; if InvalidOid, no default */
97 static Oid defaultCreationNamespace = InvalidOid;
99 /* first explicit member of list; usually same as defaultCreationNamespace */
100 static Oid firstExplicitNamespace = InvalidOid;
102 /* The above four values are valid only if namespaceSearchPathValid */
103 static bool namespaceSearchPathValid = true;
106 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
107 * in a particular backend session (this happens when a CREATE TEMP TABLE
108 * command is first executed). Thereafter it's the OID of the temp namespace.
109 * firstTempTransaction flags whether we've committed creation of the TEMP
112 static Oid myTempNamespace = InvalidOid;
114 static bool firstTempTransaction = false;
117 * "Special" namespace for CREATE SCHEMA. If set, it's the first search
118 * path element, and also the default creation namespace.
120 static Oid mySpecialNamespace = InvalidOid;
123 * This is the text equivalent of the search path --- it's the value
124 * of the GUC variable 'search_path'.
126 char *namespace_search_path = NULL;
129 /* Local functions */
130 static void recomputeNamespacePath(void);
131 static void InitTempTableNamespace(void);
132 static void RemoveTempRelations(Oid tempNamespaceId);
133 static void RemoveTempRelationsCallback(void);
134 static void NamespaceCallback(Datum arg, Oid relid);
136 /* These don't really need to appear in any header file */
137 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
138 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
139 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
140 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
141 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
142 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
147 * Given a RangeVar describing an existing relation,
148 * select the proper namespace and look up the relation OID.
150 * If the relation is not found, return InvalidOid if failOK = true,
151 * otherwise raise an error.
154 RangeVarGetRelid(const RangeVar *relation, bool failOK)
160 * We check the catalog name and then ignore it.
162 if (relation->catalogname)
164 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
165 elog(ERROR, "Cross-database references are not implemented");
168 if (relation->schemaname)
170 /* use exact schema given */
171 namespaceId = LookupExplicitNamespace(relation->schemaname);
172 relId = get_relname_relid(relation->relname, namespaceId);
176 /* search the namespace path */
177 relId = RelnameGetRelid(relation->relname);
180 if (!OidIsValid(relId) && !failOK)
182 if (relation->schemaname)
183 elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
184 relation->schemaname, relation->relname);
186 elog(ERROR, "Relation \"%s\" does not exist",
193 * RangeVarGetCreationNamespace
194 * Given a RangeVar describing a to-be-created relation,
195 * choose which namespace to create it in.
197 * Note: calling this may result in a CommandCounterIncrement operation.
198 * That will happen on the first request for a temp table in any particular
199 * backend run; we will need to either create or clean out the temp schema.
202 RangeVarGetCreationNamespace(const RangeVar *newRelation)
207 * We check the catalog name and then ignore it.
209 if (newRelation->catalogname)
211 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
212 elog(ERROR, "Cross-database references are not implemented");
215 if (newRelation->istemp)
217 /* TEMP tables are created in our backend-local temp namespace */
218 if (newRelation->schemaname)
219 elog(ERROR, "TEMP tables may not specify a namespace");
220 /* Initialize temp namespace if first time through */
221 if (!OidIsValid(myTempNamespace))
222 InitTempTableNamespace();
223 return myTempNamespace;
226 if (newRelation->schemaname)
228 /* use exact schema given */
229 namespaceId = GetSysCacheOid(NAMESPACENAME,
230 CStringGetDatum(newRelation->schemaname),
232 if (!OidIsValid(namespaceId))
233 elog(ERROR, "Namespace \"%s\" does not exist",
234 newRelation->schemaname);
235 /* we do not check for USAGE rights here! */
239 /* use the default creation namespace */
240 recomputeNamespacePath();
241 namespaceId = defaultCreationNamespace;
242 if (!OidIsValid(namespaceId))
243 elog(ERROR, "No namespace has been selected to create in");
246 /* Note: callers will check for CREATE rights when appropriate */
253 * Try to resolve an unqualified relation name.
254 * Returns OID if relation found in search path, else InvalidOid.
257 RelnameGetRelid(const char *relname)
262 recomputeNamespacePath();
264 foreach(lptr, namespaceSearchPath)
266 Oid namespaceId = lfirsto(lptr);
268 relid = get_relname_relid(relname, namespaceId);
269 if (OidIsValid(relid))
273 /* Not found in path */
280 * Determine whether a relation (identified by OID) is visible in the
281 * current search path. Visible means "would be found by searching
282 * for the unqualified relation name".
285 RelationIsVisible(Oid relid)
288 Form_pg_class relform;
292 reltup = SearchSysCache(RELOID,
293 ObjectIdGetDatum(relid),
295 if (!HeapTupleIsValid(reltup))
296 elog(ERROR, "Cache lookup failed for relation %u", relid);
297 relform = (Form_pg_class) GETSTRUCT(reltup);
299 recomputeNamespacePath();
302 * Quick check: if it ain't in the path at all, it ain't visible.
303 * Items in the system namespace are surely in the path and so we
304 * needn't even do oidMember() for them.
306 relnamespace = relform->relnamespace;
307 if (relnamespace != PG_CATALOG_NAMESPACE &&
308 !oidMember(relnamespace, namespaceSearchPath))
313 * If it is in the path, it might still not be visible; it could
314 * be hidden by another relation of the same name earlier in the
315 * path. So we must do a slow check to see if this rel would be
316 * found by RelnameGetRelid.
318 char *relname = NameStr(relform->relname);
320 visible = (RelnameGetRelid(relname) == relid);
323 ReleaseSysCache(reltup);
331 * Try to resolve an unqualified datatype name.
332 * Returns OID if type found in search path, else InvalidOid.
334 * This is essentially the same as RelnameGetRelid.
337 TypenameGetTypid(const char *typname)
342 recomputeNamespacePath();
344 foreach(lptr, namespaceSearchPath)
346 Oid namespaceId = lfirsto(lptr);
348 typid = GetSysCacheOid(TYPENAMENSP,
349 PointerGetDatum(typname),
350 ObjectIdGetDatum(namespaceId),
352 if (OidIsValid(typid))
356 /* Not found in path */
362 * Determine whether a type (identified by OID) is visible in the
363 * current search path. Visible means "would be found by searching
364 * for the unqualified type name".
367 TypeIsVisible(Oid typid)
370 Form_pg_type typform;
374 typtup = SearchSysCache(TYPEOID,
375 ObjectIdGetDatum(typid),
377 if (!HeapTupleIsValid(typtup))
378 elog(ERROR, "Cache lookup failed for type %u", typid);
379 typform = (Form_pg_type) GETSTRUCT(typtup);
381 recomputeNamespacePath();
384 * Quick check: if it ain't in the path at all, it ain't visible.
385 * Items in the system namespace are surely in the path and so we
386 * needn't even do oidMember() for them.
388 typnamespace = typform->typnamespace;
389 if (typnamespace != PG_CATALOG_NAMESPACE &&
390 !oidMember(typnamespace, namespaceSearchPath))
395 * If it is in the path, it might still not be visible; it could
396 * be hidden by another type of the same name earlier in the path.
397 * So we must do a slow check to see if this type would be found
398 * by TypenameGetTypid.
400 char *typname = NameStr(typform->typname);
402 visible = (TypenameGetTypid(typname) == typid);
405 ReleaseSysCache(typtup);
412 * FuncnameGetCandidates
413 * Given a possibly-qualified function name and argument count,
414 * retrieve a list of the possible matches.
416 * If nargs is -1, we return all functions matching the given name,
417 * regardless of argument count.
419 * We search a single namespace if the function name is qualified, else
420 * all namespaces in the search path. The return list will never contain
421 * multiple entries with identical argument lists --- in the multiple-
422 * namespace case, we arrange for entries in earlier namespaces to mask
423 * identical entries in later namespaces.
426 FuncnameGetCandidates(List *names, int nargs)
428 FuncCandidateList resultList = NULL;
435 /* deconstruct the name list */
436 DeconstructQualifiedName(names, &schemaname, &funcname);
440 /* use exact schema given */
441 namespaceId = LookupExplicitNamespace(schemaname);
445 /* flag to indicate we need namespace search */
446 namespaceId = InvalidOid;
447 recomputeNamespacePath();
450 /* Search syscache by name and (optionally) nargs only */
452 catlist = SearchSysCacheList(PROCNAMENSP, 2,
453 CStringGetDatum(funcname),
454 Int16GetDatum(nargs),
457 catlist = SearchSysCacheList(PROCNAMENSP, 1,
458 CStringGetDatum(funcname),
461 for (i = 0; i < catlist->n_members; i++)
463 HeapTuple proctup = &catlist->members[i]->tuple;
464 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
466 FuncCandidateList newResult;
468 nargs = procform->pronargs;
470 if (OidIsValid(namespaceId))
472 /* Consider only procs in specified namespace */
473 if (procform->pronamespace != namespaceId)
475 /* No need to check args, they must all be different */
479 /* Consider only procs that are in the search path */
482 foreach(nsp, namespaceSearchPath)
484 if (procform->pronamespace == lfirsto(nsp))
489 continue; /* proc is not in search path */
492 * Okay, it's in the search path, but does it have the same
493 * arguments as something we already accepted? If so, keep
494 * only the one that appears earlier in the search path.
496 * If we have an ordered list from SearchSysCacheList (the normal
497 * case), then any conflicting proc must immediately adjoin
498 * this one in the list, so we only need to look at the newest
499 * result item. If we have an unordered list, we have to scan
500 * the whole result list.
504 FuncCandidateList prevResult;
506 if (catlist->ordered)
508 if (nargs == resultList->nargs &&
509 memcmp(procform->proargtypes, resultList->args,
510 nargs * sizeof(Oid)) == 0)
511 prevResult = resultList;
517 for (prevResult = resultList;
519 prevResult = prevResult->next)
521 if (nargs == prevResult->nargs &&
522 memcmp(procform->proargtypes, prevResult->args,
523 nargs * sizeof(Oid)) == 0)
529 /* We have a match with a previous result */
530 Assert(pathpos != prevResult->pathpos);
531 if (pathpos > prevResult->pathpos)
532 continue; /* keep previous result */
533 /* replace previous result */
534 prevResult->pathpos = pathpos;
535 prevResult->oid = HeapTupleGetOid(proctup);
536 continue; /* args are same, of course */
542 * Okay to add it to result list
544 newResult = (FuncCandidateList)
545 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
546 + nargs * sizeof(Oid));
547 newResult->pathpos = pathpos;
548 newResult->oid = HeapTupleGetOid(proctup);
549 newResult->nargs = nargs;
550 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
552 newResult->next = resultList;
553 resultList = newResult;
556 ReleaseSysCacheList(catlist);
563 * Determine whether a function (identified by OID) is visible in the
564 * current search path. Visible means "would be found by searching
565 * for the unqualified function name with exact argument matches".
568 FunctionIsVisible(Oid funcid)
571 Form_pg_proc procform;
575 proctup = SearchSysCache(PROCOID,
576 ObjectIdGetDatum(funcid),
578 if (!HeapTupleIsValid(proctup))
579 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
580 procform = (Form_pg_proc) GETSTRUCT(proctup);
582 recomputeNamespacePath();
585 * Quick check: if it ain't in the path at all, it ain't visible.
586 * Items in the system namespace are surely in the path and so we
587 * needn't even do oidMember() for them.
589 pronamespace = procform->pronamespace;
590 if (pronamespace != PG_CATALOG_NAMESPACE &&
591 !oidMember(pronamespace, namespaceSearchPath))
596 * If it is in the path, it might still not be visible; it could
597 * be hidden by another proc of the same name and arguments
598 * earlier in the path. So we must do a slow check to see if this
599 * is the same proc that would be found by FuncnameGetCandidates.
601 char *proname = NameStr(procform->proname);
602 int nargs = procform->pronargs;
603 FuncCandidateList clist;
607 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
609 for (; clist; clist = clist->next)
611 if (memcmp(clist->args, procform->proargtypes,
612 nargs * sizeof(Oid)) == 0)
614 /* Found the expected entry; is it the right proc? */
615 visible = (clist->oid == funcid);
621 ReleaseSysCache(proctup);
628 * OpernameGetCandidates
629 * Given a possibly-qualified operator name and operator kind,
630 * retrieve a list of the possible matches.
632 * If oprkind is '\0', we return all operators matching the given name,
633 * regardless of arguments.
635 * We search a single namespace if the operator name is qualified, else
636 * all namespaces in the search path. The return list will never contain
637 * multiple entries with identical argument lists --- in the multiple-
638 * namespace case, we arrange for entries in earlier namespaces to mask
639 * identical entries in later namespaces.
641 * The returned items always have two args[] entries --- one or the other
642 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
645 OpernameGetCandidates(List *names, char oprkind)
647 FuncCandidateList resultList = NULL;
654 /* deconstruct the name list */
655 DeconstructQualifiedName(names, &schemaname, &opername);
659 /* use exact schema given */
660 namespaceId = LookupExplicitNamespace(schemaname);
664 /* flag to indicate we need namespace search */
665 namespaceId = InvalidOid;
666 recomputeNamespacePath();
669 /* Search syscache by name only */
670 catlist = SearchSysCacheList(OPERNAMENSP, 1,
671 CStringGetDatum(opername),
674 for (i = 0; i < catlist->n_members; i++)
676 HeapTuple opertup = &catlist->members[i]->tuple;
677 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
679 FuncCandidateList newResult;
681 /* Ignore operators of wrong kind, if specific kind requested */
682 if (oprkind && operform->oprkind != oprkind)
685 if (OidIsValid(namespaceId))
687 /* Consider only opers in specified namespace */
688 if (operform->oprnamespace != namespaceId)
690 /* No need to check args, they must all be different */
694 /* Consider only opers that are in the search path */
697 foreach(nsp, namespaceSearchPath)
699 if (operform->oprnamespace == lfirsto(nsp))
704 continue; /* oper is not in search path */
707 * Okay, it's in the search path, but does it have the same
708 * arguments as something we already accepted? If so, keep
709 * only the one that appears earlier in the search path.
711 * If we have an ordered list from SearchSysCacheList (the normal
712 * case), then any conflicting oper must immediately adjoin
713 * this one in the list, so we only need to look at the newest
714 * result item. If we have an unordered list, we have to scan
715 * the whole result list.
719 FuncCandidateList prevResult;
721 if (catlist->ordered)
723 if (operform->oprleft == resultList->args[0] &&
724 operform->oprright == resultList->args[1])
725 prevResult = resultList;
731 for (prevResult = resultList;
733 prevResult = prevResult->next)
735 if (operform->oprleft == prevResult->args[0] &&
736 operform->oprright == prevResult->args[1])
742 /* We have a match with a previous result */
743 Assert(pathpos != prevResult->pathpos);
744 if (pathpos > prevResult->pathpos)
745 continue; /* keep previous result */
746 /* replace previous result */
747 prevResult->pathpos = pathpos;
748 prevResult->oid = HeapTupleGetOid(opertup);
749 continue; /* args are same, of course */
755 * Okay to add it to result list
757 newResult = (FuncCandidateList)
758 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
759 newResult->pathpos = pathpos;
760 newResult->oid = HeapTupleGetOid(opertup);
761 newResult->nargs = 2;
762 newResult->args[0] = operform->oprleft;
763 newResult->args[1] = operform->oprright;
764 newResult->next = resultList;
765 resultList = newResult;
768 ReleaseSysCacheList(catlist);
775 * Determine whether an operator (identified by OID) is visible in the
776 * current search path. Visible means "would be found by searching
777 * for the unqualified operator name with exact argument matches".
780 OperatorIsVisible(Oid oprid)
783 Form_pg_operator oprform;
787 oprtup = SearchSysCache(OPEROID,
788 ObjectIdGetDatum(oprid),
790 if (!HeapTupleIsValid(oprtup))
791 elog(ERROR, "Cache lookup failed for operator %u", oprid);
792 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
794 recomputeNamespacePath();
797 * Quick check: if it ain't in the path at all, it ain't visible.
798 * Items in the system namespace are surely in the path and so we
799 * needn't even do oidMember() for them.
801 oprnamespace = oprform->oprnamespace;
802 if (oprnamespace != PG_CATALOG_NAMESPACE &&
803 !oidMember(oprnamespace, namespaceSearchPath))
808 * If it is in the path, it might still not be visible; it could
809 * be hidden by another operator of the same name and arguments
810 * earlier in the path. So we must do a slow check to see if this
811 * is the same operator that would be found by
812 * OpernameGetCandidates.
814 char *oprname = NameStr(oprform->oprname);
815 FuncCandidateList clist;
819 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
822 for (; clist; clist = clist->next)
824 if (clist->args[0] == oprform->oprleft &&
825 clist->args[1] == oprform->oprright)
827 /* Found the expected entry; is it the right op? */
828 visible = (clist->oid == oprid);
834 ReleaseSysCache(oprtup);
841 * OpclassGetCandidates
842 * Given an index access method OID, retrieve a list of all the
843 * opclasses for that AM that are visible in the search path.
845 * NOTE: the opcname_tmp field in the returned structs should not be used
846 * by callers, because it points at syscache entries that we release at
847 * the end of this routine. If any callers needed the name information,
848 * we could pstrdup() the names ... but at present it'd be wasteful.
851 OpclassGetCandidates(Oid amid)
853 OpclassCandidateList resultList = NULL;
857 /* Search syscache by AM OID only */
858 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
859 ObjectIdGetDatum(amid),
862 recomputeNamespacePath();
864 for (i = 0; i < catlist->n_members; i++)
866 HeapTuple opctup = &catlist->members[i]->tuple;
867 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
869 OpclassCandidateList newResult;
872 /* Consider only opclasses that are in the search path */
873 foreach(nsp, namespaceSearchPath)
875 if (opcform->opcnamespace == lfirsto(nsp))
880 continue; /* opclass is not in search path */
883 * Okay, it's in the search path, but does it have the same name
884 * as something we already accepted? If so, keep only the one
885 * that appears earlier in the search path.
887 * If we have an ordered list from SearchSysCacheList (the normal
888 * case), then any conflicting opclass must immediately adjoin
889 * this one in the list, so we only need to look at the newest
890 * result item. If we have an unordered list, we have to scan the
895 OpclassCandidateList prevResult;
897 if (catlist->ordered)
899 if (strcmp(NameStr(opcform->opcname),
900 resultList->opcname_tmp) == 0)
901 prevResult = resultList;
907 for (prevResult = resultList;
909 prevResult = prevResult->next)
911 if (strcmp(NameStr(opcform->opcname),
912 prevResult->opcname_tmp) == 0)
918 /* We have a match with a previous result */
919 Assert(pathpos != prevResult->pathpos);
920 if (pathpos > prevResult->pathpos)
921 continue; /* keep previous result */
922 /* replace previous result */
923 prevResult->opcname_tmp = NameStr(opcform->opcname);
924 prevResult->pathpos = pathpos;
925 prevResult->oid = HeapTupleGetOid(opctup);
926 prevResult->opcintype = opcform->opcintype;
927 prevResult->opcdefault = opcform->opcdefault;
928 prevResult->opckeytype = opcform->opckeytype;
934 * Okay to add it to result list
936 newResult = (OpclassCandidateList)
937 palloc(sizeof(struct _OpclassCandidateList));
938 newResult->opcname_tmp = NameStr(opcform->opcname);
939 newResult->pathpos = pathpos;
940 newResult->oid = HeapTupleGetOid(opctup);
941 newResult->opcintype = opcform->opcintype;
942 newResult->opcdefault = opcform->opcdefault;
943 newResult->opckeytype = opcform->opckeytype;
944 newResult->next = resultList;
945 resultList = newResult;
948 ReleaseSysCacheList(catlist);
954 * OpclassnameGetOpcid
955 * Try to resolve an unqualified index opclass name.
956 * Returns OID if opclass found in search path, else InvalidOid.
958 * This is essentially the same as TypenameGetTypid, but we have to have
959 * an extra argument for the index AM OID.
962 OpclassnameGetOpcid(Oid amid, const char *opcname)
967 recomputeNamespacePath();
969 foreach(lptr, namespaceSearchPath)
971 Oid namespaceId = lfirsto(lptr);
973 opcid = GetSysCacheOid(CLAAMNAMENSP,
974 ObjectIdGetDatum(amid),
975 PointerGetDatum(opcname),
976 ObjectIdGetDatum(namespaceId),
978 if (OidIsValid(opcid))
982 /* Not found in path */
988 * Determine whether an opclass (identified by OID) is visible in the
989 * current search path. Visible means "would be found by searching
990 * for the unqualified opclass name".
993 OpclassIsVisible(Oid opcid)
996 Form_pg_opclass opcform;
1000 opctup = SearchSysCache(CLAOID,
1001 ObjectIdGetDatum(opcid),
1003 if (!HeapTupleIsValid(opctup))
1004 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1005 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1007 recomputeNamespacePath();
1010 * Quick check: if it ain't in the path at all, it ain't visible.
1011 * Items in the system namespace are surely in the path and so we
1012 * needn't even do oidMember() for them.
1014 opcnamespace = opcform->opcnamespace;
1015 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1016 !oidMember(opcnamespace, namespaceSearchPath))
1021 * If it is in the path, it might still not be visible; it could
1022 * be hidden by another opclass of the same name earlier in the
1023 * path. So we must do a slow check to see if this opclass would
1024 * be found by OpclassnameGetOpcid.
1026 char *opcname = NameStr(opcform->opcname);
1028 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1031 ReleaseSysCache(opctup);
1037 * ConversionGetConid
1038 * Try to resolve an unqualified conversion name.
1039 * Returns OID if conversion found in search path, else InvalidOid.
1041 * This is essentially the same as RelnameGetRelid.
1044 ConversionGetConid(const char *conname)
1049 recomputeNamespacePath();
1051 foreach(lptr, namespaceSearchPath)
1053 Oid namespaceId = lfirsto(lptr);
1055 conid = GetSysCacheOid(CONNAMENSP,
1056 PointerGetDatum(conname),
1057 ObjectIdGetDatum(namespaceId),
1059 if (OidIsValid(conid))
1063 /* Not found in path */
1068 * ConversionIsVisible
1069 * Determine whether a conversion (identified by OID) is visible in the
1070 * current search path. Visible means "would be found by searching
1071 * for the unqualified conversion name".
1074 ConversionIsVisible(Oid conid)
1077 Form_pg_conversion conform;
1081 contup = SearchSysCache(CONOID,
1082 ObjectIdGetDatum(conid),
1084 if (!HeapTupleIsValid(contup))
1085 elog(ERROR, "Cache lookup failed for conversion %u", conid);
1086 conform = (Form_pg_conversion) GETSTRUCT(contup);
1088 recomputeNamespacePath();
1091 * Quick check: if it ain't in the path at all, it ain't visible.
1092 * Items in the system namespace are surely in the path and so we
1093 * needn't even do oidMember() for them.
1095 connamespace = conform->connamespace;
1096 if (connamespace != PG_CATALOG_NAMESPACE &&
1097 !oidMember(connamespace, namespaceSearchPath))
1102 * If it is in the path, it might still not be visible; it could
1103 * be hidden by another conversion of the same name earlier in the
1104 * path. So we must do a slow check to see if this conversion would
1105 * be found by ConversionGetConid.
1107 char *conname = NameStr(conform->conname);
1109 visible = (ConversionGetConid(conname) == conid);
1112 ReleaseSysCache(contup);
1118 * DeconstructQualifiedName
1119 * Given a possibly-qualified name expressed as a list of String nodes,
1120 * extract the schema name and object name.
1122 * *nspname_p is set to NULL if there is no explicit schema name.
1125 DeconstructQualifiedName(List *names,
1130 char *schemaname = NULL;
1131 char *objname = NULL;
1133 switch (length(names))
1136 objname = strVal(lfirst(names));
1139 schemaname = strVal(lfirst(names));
1140 objname = strVal(lsecond(names));
1143 catalogname = strVal(lfirst(names));
1144 schemaname = strVal(lsecond(names));
1145 objname = strVal(lthird(names));
1148 * We check the catalog name and then ignore it.
1150 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
1151 elog(ERROR, "Cross-database references are not implemented");
1154 elog(ERROR, "Improper qualified name (too many dotted names): %s",
1155 NameListToString(names));
1159 *nspname_p = schemaname;
1160 *objname_p = objname;
1164 * LookupExplicitNamespace
1165 * Process an explicitly-specified schema name: look up the schema
1166 * and verify we have USAGE (lookup) rights in it.
1168 * Returns the namespace OID. Raises elog if any problem.
1171 LookupExplicitNamespace(const char *nspname)
1174 AclResult aclresult;
1176 namespaceId = GetSysCacheOid(NAMESPACENAME,
1177 CStringGetDatum(nspname),
1179 if (!OidIsValid(namespaceId))
1180 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1182 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1183 if (aclresult != ACLCHECK_OK)
1184 aclcheck_error(aclresult, nspname);
1190 * QualifiedNameGetCreationNamespace
1191 * Given a possibly-qualified name for an object (in List-of-Values
1192 * format), determine what namespace the object should be created in.
1193 * Also extract and return the object name (last component of list).
1195 * This is *not* used for tables. Hence, the TEMP table namespace is
1196 * never selected as the creation target.
1199 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1205 /* deconstruct the name list */
1206 DeconstructQualifiedName(names, &schemaname, &objname);
1210 /* use exact schema given */
1211 namespaceId = GetSysCacheOid(NAMESPACENAME,
1212 CStringGetDatum(schemaname),
1214 if (!OidIsValid(namespaceId))
1215 elog(ERROR, "Namespace \"%s\" does not exist",
1217 /* we do not check for USAGE rights here! */
1221 /* use the default creation namespace */
1222 recomputeNamespacePath();
1223 namespaceId = defaultCreationNamespace;
1224 if (!OidIsValid(namespaceId))
1225 elog(ERROR, "No namespace has been selected to create in");
1228 /* Note: callers will check for CREATE rights when appropriate */
1230 *objname_p = objname;
1235 * makeRangeVarFromNameList
1236 * Utility routine to convert a qualified-name list into RangeVar form.
1239 makeRangeVarFromNameList(List *names)
1241 RangeVar *rel = makeRangeVar(NULL, NULL);
1243 switch (length(names))
1246 rel->relname = strVal(lfirst(names));
1249 rel->schemaname = strVal(lfirst(names));
1250 rel->relname = strVal(lsecond(names));
1253 rel->catalogname = strVal(lfirst(names));
1254 rel->schemaname = strVal(lsecond(names));
1255 rel->relname = strVal(lthird(names));
1258 elog(ERROR, "Improper relation name (too many dotted names)");
1267 * Utility routine to convert a qualified-name list into a string.
1269 * This is used primarily to form error messages, and so we do not quote
1270 * the list elements, for the sake of legibility.
1273 NameListToString(List *names)
1275 StringInfoData string;
1278 initStringInfo(&string);
1283 appendStringInfoChar(&string, '.');
1284 appendStringInfoString(&string, strVal(lfirst(l)));
1291 * NameListToQuotedString
1292 * Utility routine to convert a qualified-name list into a string.
1294 * Same as above except that names will be double-quoted where necessary,
1295 * so the string could be re-parsed (eg, by textToQualifiedNameList).
1298 NameListToQuotedString(List *names)
1300 StringInfoData string;
1303 initStringInfo(&string);
1308 appendStringInfoChar(&string, '.');
1309 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1316 * isTempNamespace - is the given namespace my temporary-table namespace?
1319 isTempNamespace(Oid namespaceId)
1321 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1327 * isOtherTempNamespace - is the given namespace some other backend's
1328 * temporary-table namespace?
1331 isOtherTempNamespace(Oid namespaceId)
1336 /* If it's my own temp namespace, say "false" */
1337 if (isTempNamespace(namespaceId))
1339 /* Else, if the namespace name starts with "pg_temp_", say "true" */
1340 nspname = get_namespace_name(namespaceId);
1342 return false; /* no such namespace? */
1343 result = (strncmp(nspname, "pg_temp_", 8) == 0);
1349 * PushSpecialNamespace - push a "special" namespace onto the front of the
1352 * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1353 * Although the API is defined to allow a stack of pushed namespaces, we
1354 * presently only support one at a time.
1356 * The pushed namespace will be removed from the search path at end of
1357 * transaction, whether commit or abort.
1360 PushSpecialNamespace(Oid namespaceId)
1362 Assert(!OidIsValid(mySpecialNamespace));
1363 mySpecialNamespace = namespaceId;
1364 namespaceSearchPathValid = false;
1368 * PopSpecialNamespace - remove previously pushed special namespace.
1371 PopSpecialNamespace(Oid namespaceId)
1373 Assert(mySpecialNamespace == namespaceId);
1374 mySpecialNamespace = InvalidOid;
1375 namespaceSearchPathValid = false;
1379 * FindConversionByName - find a conversion by possibly qualified name
1382 FindConversionByName(List *name)
1385 char *conversion_name;
1390 /* deconstruct the name list */
1391 DeconstructQualifiedName(name, &schemaname, &conversion_name);
1395 /* use exact schema given */
1396 namespaceId = LookupExplicitNamespace(schemaname);
1397 return FindConversion(conversion_name, namespaceId);
1401 /* search for it in search path */
1402 recomputeNamespacePath();
1404 foreach(lptr, namespaceSearchPath)
1406 namespaceId = lfirsto(lptr);
1407 conoid = FindConversion(conversion_name, namespaceId);
1408 if (OidIsValid(conoid))
1413 /* Not found in path */
1418 * FindDefaultConversionProc - find default encoding conversion proc
1421 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1426 recomputeNamespacePath();
1428 foreach(lptr, namespaceSearchPath)
1430 Oid namespaceId = lfirsto(lptr);
1432 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1433 if (OidIsValid(proc))
1437 /* Not found in path */
1442 * recomputeNamespacePath - recompute path derived variables if needed.
1445 recomputeNamespacePath(void)
1447 AclId userId = GetUserId();
1454 MemoryContext oldcxt;
1457 * Do nothing if path is already valid.
1459 if (namespaceSearchPathValid && namespaceUser == userId)
1462 /* Need a modifiable copy of namespace_search_path string */
1463 rawname = pstrdup(namespace_search_path);
1465 /* Parse string into list of identifiers */
1466 if (!SplitIdentifierString(rawname, ',', &namelist))
1468 /* syntax error in name list */
1469 /* this should not happen if GUC checked check_search_path */
1470 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1474 * Convert the list of names to a list of OIDs. If any names are not
1475 * recognizable or we don't have read access, just leave them out of
1476 * the list. (We can't raise an error, since the search_path setting
1477 * has already been accepted.) Don't make duplicate entries, either.
1480 foreach(l, namelist)
1482 char *curname = (char *) lfirst(l);
1485 if (strcmp(curname, "$user") == 0)
1487 /* $user --- substitute namespace matching user name, if any */
1490 tuple = SearchSysCache(SHADOWSYSID,
1491 ObjectIdGetDatum(userId),
1493 if (HeapTupleIsValid(tuple))
1497 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1498 namespaceId = GetSysCacheOid(NAMESPACENAME,
1499 CStringGetDatum(uname),
1501 ReleaseSysCache(tuple);
1502 if (OidIsValid(namespaceId) &&
1503 !oidMember(namespaceId, oidlist) &&
1504 pg_namespace_aclcheck(namespaceId, userId,
1505 ACL_USAGE) == ACLCHECK_OK)
1506 oidlist = lappendo(oidlist, namespaceId);
1511 /* normal namespace reference */
1512 namespaceId = GetSysCacheOid(NAMESPACENAME,
1513 CStringGetDatum(curname),
1515 if (OidIsValid(namespaceId) &&
1516 !oidMember(namespaceId, oidlist) &&
1517 pg_namespace_aclcheck(namespaceId, userId,
1518 ACL_USAGE) == ACLCHECK_OK)
1519 oidlist = lappendo(oidlist, namespaceId);
1524 * Remember the first member of the explicit list.
1527 firstNS = InvalidOid;
1529 firstNS = lfirsto(oidlist);
1532 * Add any implicitly-searched namespaces to the list. Note these go
1533 * on the front, not the back; also notice that we do not check USAGE
1534 * permissions for these.
1536 if (!oidMember(PG_CATALOG_NAMESPACE, oidlist))
1537 oidlist = lconso(PG_CATALOG_NAMESPACE, oidlist);
1539 if (OidIsValid(myTempNamespace) &&
1540 !oidMember(myTempNamespace, oidlist))
1541 oidlist = lconso(myTempNamespace, oidlist);
1543 if (OidIsValid(mySpecialNamespace) &&
1544 !oidMember(mySpecialNamespace, oidlist))
1545 oidlist = lconso(mySpecialNamespace, oidlist);
1548 * Now that we've successfully built the new list of namespace OIDs,
1549 * save it in permanent storage.
1551 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1552 newpath = listCopy(oidlist);
1553 MemoryContextSwitchTo(oldcxt);
1555 /* Now safe to assign to state variable. */
1556 freeList(namespaceSearchPath);
1557 namespaceSearchPath = newpath;
1560 * Update info derived from search path.
1562 firstExplicitNamespace = firstNS;
1563 if (OidIsValid(mySpecialNamespace))
1564 defaultCreationNamespace = mySpecialNamespace;
1566 defaultCreationNamespace = firstNS;
1568 /* Mark the path valid. */
1569 namespaceSearchPathValid = true;
1570 namespaceUser = userId;
1579 * InitTempTableNamespace
1580 * Initialize temp table namespace on first use in a particular backend
1583 InitTempTableNamespace(void)
1585 char namespaceName[NAMEDATALEN];
1589 * First, do permission check to see if we are authorized to make temp
1590 * tables. We use a nonstandard error message here since
1591 * "databasename: permission denied" might be a tad cryptic.
1593 * Note we apply the check to the session user, not the currently active
1594 * userid, since we are not going to change our minds about temp table
1595 * availability during the session.
1597 if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1598 ACL_CREATE_TEMP) != ACLCHECK_OK)
1599 elog(ERROR, "%s: not authorized to create temp tables",
1600 get_database_name(MyDatabaseId));
1602 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1604 namespaceId = GetSysCacheOid(NAMESPACENAME,
1605 CStringGetDatum(namespaceName),
1607 if (!OidIsValid(namespaceId))
1610 * First use of this temp namespace in this database; create it.
1611 * The temp namespaces are always owned by the superuser. We
1612 * leave their permissions at default --- i.e., no access except
1613 * to superuser --- to ensure that unprivileged users can't peek
1614 * at other backends' temp tables. This works because the places
1615 * that access the temp namespace for my own backend skip
1616 * permissions checks on it.
1618 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1619 /* Advance command counter to make namespace visible */
1620 CommandCounterIncrement();
1625 * If the namespace already exists, clean it out (in case the
1626 * former owner crashed without doing so).
1628 RemoveTempRelations(namespaceId);
1632 * Okay, we've prepared the temp namespace ... but it's not committed
1633 * yet, so all our work could be undone by transaction rollback. Set
1634 * flag for AtEOXact_Namespace to know what to do.
1636 myTempNamespace = namespaceId;
1638 firstTempTransaction = true;
1640 namespaceSearchPathValid = false; /* need to rebuild list */
1644 * End-of-transaction cleanup for namespaces.
1647 AtEOXact_Namespace(bool isCommit)
1650 * If we abort the transaction in which a temp namespace was selected,
1651 * we'll have to do any creation or cleanout work over again. So,
1652 * just forget the namespace entirely until next time. On the other
1653 * hand, if we commit then register an exit callback to clean out the
1654 * temp tables at backend shutdown. (We only want to register the
1655 * callback once per session, so this is a good place to do it.)
1657 if (firstTempTransaction)
1660 on_shmem_exit(RemoveTempRelationsCallback, 0);
1663 myTempNamespace = InvalidOid;
1664 namespaceSearchPathValid = false; /* need to rebuild list */
1666 firstTempTransaction = false;
1670 * Clean up if someone failed to do PopSpecialNamespace
1672 if (OidIsValid(mySpecialNamespace))
1674 mySpecialNamespace = InvalidOid;
1675 namespaceSearchPathValid = false; /* need to rebuild list */
1680 * Remove all relations in the specified temp namespace.
1682 * This is called at backend shutdown (if we made any temp relations).
1683 * It is also called when we begin using a pre-existing temp namespace,
1684 * in order to clean out any relations that might have been created by
1685 * a crashed backend.
1688 RemoveTempRelations(Oid tempNamespaceId)
1690 ObjectAddress object;
1693 * We want to get rid of everything in the target namespace, but not
1694 * the namespace itself (deleting it only to recreate it later would be
1695 * a waste of cycles). We do this by finding everything that has a
1696 * dependency on the namespace.
1698 object.classId = get_system_catalog_relid(NamespaceRelationName);
1699 object.objectId = tempNamespaceId;
1700 object.objectSubId = 0;
1702 deleteWhatDependsOn(&object, false);
1706 * Callback to remove temp relations at backend exit.
1709 RemoveTempRelationsCallback(void)
1711 if (OidIsValid(myTempNamespace)) /* should always be true */
1713 /* Need to ensure we have a usable transaction. */
1714 AbortOutOfAnyTransaction();
1715 StartTransactionCommand();
1717 RemoveTempRelations(myTempNamespace);
1719 CommitTransactionCommand();
1725 * Routines for handling the GUC variable 'search_path'.
1728 /* assign_hook: validate new search_path, do extra actions as needed */
1730 assign_search_path(const char *newval, bool doit, bool interactive)
1736 /* Need a modifiable copy of string */
1737 rawname = pstrdup(newval);
1739 /* Parse string into list of identifiers */
1740 if (!SplitIdentifierString(rawname, ',', &namelist))
1742 /* syntax error in name list */
1749 * If we aren't inside a transaction, we cannot do database access so
1750 * cannot verify the individual names. Must accept the list on faith.
1752 if (interactive && IsTransactionState())
1755 * Verify that all the names are either valid namespace names or
1756 * "$user". We do not require $user to correspond to a valid
1757 * namespace. We do not check for USAGE rights, either; should
1760 foreach(l, namelist)
1762 char *curname = (char *) lfirst(l);
1764 if (strcmp(curname, "$user") == 0)
1766 if (!SearchSysCacheExists(NAMESPACENAME,
1767 CStringGetDatum(curname),
1769 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1777 * We mark the path as needing recomputation, but don't do anything
1778 * until it's needed. This avoids trying to do database access during
1779 * GUC initialization.
1782 namespaceSearchPathValid = false;
1788 * InitializeSearchPath: initialize module during InitPostgres.
1790 * This is called after we are up enough to be able to do catalog lookups.
1793 InitializeSearchPath(void)
1795 if (IsBootstrapProcessingMode())
1798 * In bootstrap mode, the search path must be 'pg_catalog' so that
1799 * tables are created in the proper namespace; ignore the GUC
1802 MemoryContext oldcxt;
1804 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1805 namespaceSearchPath = makeListo1(PG_CATALOG_NAMESPACE);
1806 MemoryContextSwitchTo(oldcxt);
1807 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1808 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1809 namespaceSearchPathValid = true;
1810 namespaceUser = GetUserId();
1815 * In normal mode, arrange for a callback on any syscache
1816 * invalidation of pg_namespace rows.
1818 CacheRegisterSyscacheCallback(NAMESPACEOID,
1821 /* Force search path to be recomputed on next use */
1822 namespaceSearchPathValid = false;
1828 * Syscache inval callback function
1831 NamespaceCallback(Datum arg, Oid relid)
1833 /* Force search path to be recomputed on next use */
1834 namespaceSearchPathValid = false;
1838 * Fetch the active search path, expressed as a List of OIDs.
1840 * The returned list includes the implicitly-prepended namespaces only if
1841 * includeImplicit is true.
1843 * NB: caller must treat the list as read-only!
1846 fetch_search_path(bool includeImplicit)
1850 recomputeNamespacePath();
1852 result = namespaceSearchPath;
1853 if (!includeImplicit)
1855 while (result && lfirsto(result) != firstExplicitNamespace)
1856 result = lnext(result);
1863 * Export the FooIsVisible functions as SQL-callable functions.
1867 pg_table_is_visible(PG_FUNCTION_ARGS)
1869 Oid oid = PG_GETARG_OID(0);
1871 PG_RETURN_BOOL(RelationIsVisible(oid));
1875 pg_type_is_visible(PG_FUNCTION_ARGS)
1877 Oid oid = PG_GETARG_OID(0);
1879 PG_RETURN_BOOL(TypeIsVisible(oid));
1883 pg_function_is_visible(PG_FUNCTION_ARGS)
1885 Oid oid = PG_GETARG_OID(0);
1887 PG_RETURN_BOOL(FunctionIsVisible(oid));
1891 pg_operator_is_visible(PG_FUNCTION_ARGS)
1893 Oid oid = PG_GETARG_OID(0);
1895 PG_RETURN_BOOL(OperatorIsVisible(oid));
1899 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1901 Oid oid = PG_GETARG_OID(0);
1903 PG_RETURN_BOOL(OpclassIsVisible(oid));
1907 pg_conversion_is_visible(PG_FUNCTION_ARGS)
1909 Oid oid = PG_GETARG_OID(0);
1911 PG_RETURN_BOOL(ConversionIsVisible(oid));