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-2001, 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.11 2002/04/17 20:57:56 tgl Exp $
18 *-------------------------------------------------------------------------
22 #include "access/heapam.h"
23 #include "access/xact.h"
24 #include "catalog/catalog.h"
25 #include "catalog/catname.h"
26 #include "catalog/heap.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_inherits.h"
29 #include "catalog/pg_namespace.h"
30 #include "catalog/pg_opclass.h"
31 #include "catalog/pg_operator.h"
32 #include "catalog/pg_proc.h"
33 #include "catalog/pg_shadow.h"
34 #include "lib/stringinfo.h"
35 #include "miscadmin.h"
36 #include "nodes/makefuncs.h"
37 #include "storage/backendid.h"
38 #include "utils/builtins.h"
39 #include "utils/fmgroids.h"
40 #include "utils/guc.h"
41 #include "utils/catcache.h"
42 #include "utils/lsyscache.h"
43 #include "utils/syscache.h"
47 * The namespace search path is a possibly-empty list of namespace OIDs.
48 * In addition to the explicit list, the TEMP table namespace is always
49 * implicitly searched first (if it's been initialized). Also, the system
50 * catalog namespace is always searched. If the system namespace is
51 * explicitly present in the path then it will be searched in the specified
52 * order; otherwise it will be searched after TEMP tables and *before* the
53 * explicit list. (It might seem that the system namespace should be
54 * implicitly last, but this behavior appears to be required by SQL99.
55 * Also, this provides a way to search the system namespace first without
56 * thereby making it the default creation target namespace.)
58 * The default creation target namespace is kept equal to the first element
59 * of the (explicit) list. If the list is empty, there is no default target.
61 * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
62 * the system namespace is the only one searched or inserted into.
63 * The initdb script is also careful to set search_path to 'pg_catalog' for
64 * its post-bootstrap standalone backend runs. Otherwise the default search
65 * path is determined by GUC. The factory default path contains the PUBLIC
66 * namespace (if it exists), preceded by the user's personal namespace
70 static List *namespaceSearchPath = NIL;
72 /* this flag must be updated correctly when namespaceSearchPath is changed */
73 static bool pathContainsSystemNamespace = false;
75 /* default place to create stuff; if InvalidOid, no default */
76 static Oid defaultCreationNamespace = InvalidOid;
79 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
80 * in a particular backend session (this happens when a CREATE TEMP TABLE
81 * command is first executed). Thereafter it's the OID of the temp namespace.
83 static Oid myTempNamespace = InvalidOid;
86 * This is the text equivalent of the search path --- it's the value
87 * of the GUC variable 'search_path'.
89 char *namespace_search_path = NULL;
93 * Deletion ordering constraint item.
95 typedef struct DelConstraint
97 Oid referencer; /* table to delete first */
98 Oid referencee; /* table to delete second */
99 int pred; /* workspace for TopoSortRels */
100 struct DelConstraint *link; /* workspace for TopoSortRels */
104 /* Local functions */
105 static Oid GetTempTableNamespace(void);
106 static void RemoveTempRelations(Oid tempNamespaceId);
107 static List *FindTempRelations(Oid tempNamespaceId);
108 static List *FindDeletionConstraints(List *relOids);
109 static List *TopoSortRels(List *relOids, List *constraintList);
110 static void RemoveTempRelationsCallback(void);
115 * Given a RangeVar describing an existing relation,
116 * select the proper namespace and look up the relation OID.
118 * If the relation is not found, return InvalidOid if failOK = true,
119 * otherwise raise an error.
122 RangeVarGetRelid(const RangeVar *relation, bool failOK)
128 * We check the catalog name and then ignore it.
130 if (relation->catalogname)
132 if (strcmp(relation->catalogname, DatabaseName) != 0)
133 elog(ERROR, "Cross-database references are not implemented");
136 if (relation->schemaname)
138 /* use exact schema given */
139 namespaceId = GetSysCacheOid(NAMESPACENAME,
140 CStringGetDatum(relation->schemaname),
142 if (!OidIsValid(namespaceId))
143 elog(ERROR, "Namespace \"%s\" does not exist",
144 relation->schemaname);
145 relId = get_relname_relid(relation->relname, namespaceId);
149 /* search the namespace path */
150 relId = RelnameGetRelid(relation->relname);
153 if (!OidIsValid(relId) && !failOK)
155 if (relation->schemaname)
156 elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
157 relation->schemaname, relation->relname);
159 elog(ERROR, "Relation \"%s\" does not exist",
166 * RangeVarGetCreationNamespace
167 * Given a RangeVar describing a to-be-created relation,
168 * choose which namespace to create it in.
170 * Note: calling this may result in a CommandCounterIncrement operation.
171 * That will happen on the first request for a temp table in any particular
172 * backend run; we will need to either create or clean out the temp schema.
175 RangeVarGetCreationNamespace(const RangeVar *newRelation)
180 * We check the catalog name and then ignore it.
182 if (newRelation->catalogname)
184 if (strcmp(newRelation->catalogname, DatabaseName) != 0)
185 elog(ERROR, "Cross-database references are not implemented");
188 if (newRelation->istemp)
190 /* TEMP tables are created in our backend-local temp namespace */
191 if (newRelation->schemaname)
192 elog(ERROR, "TEMP tables may not specify a namespace");
193 /* Initialize temp namespace if first time through */
194 if (!OidIsValid(myTempNamespace))
195 myTempNamespace = GetTempTableNamespace();
196 return myTempNamespace;
199 if (newRelation->schemaname)
201 /* use exact schema given */
202 namespaceId = GetSysCacheOid(NAMESPACENAME,
203 CStringGetDatum(newRelation->schemaname),
205 if (!OidIsValid(namespaceId))
206 elog(ERROR, "Namespace \"%s\" does not exist",
207 newRelation->schemaname);
211 /* use the default creation namespace */
212 namespaceId = defaultCreationNamespace;
213 if (!OidIsValid(namespaceId))
214 elog(ERROR, "No namespace has been selected to create in");
222 * Try to resolve an unqualified relation name.
223 * Returns OID if relation found in search path, else InvalidOid.
226 RelnameGetRelid(const char *relname)
232 * If a TEMP-table namespace has been set up, it is implicitly first
233 * in the search path.
235 if (OidIsValid(myTempNamespace))
237 relid = get_relname_relid(relname, myTempNamespace);
238 if (OidIsValid(relid))
243 * If system namespace is not in path, implicitly search it before path
245 if (!pathContainsSystemNamespace)
247 relid = get_relname_relid(relname, PG_CATALOG_NAMESPACE);
248 if (OidIsValid(relid))
253 * Else search the path
255 foreach(lptr, namespaceSearchPath)
257 Oid namespaceId = (Oid) lfirsti(lptr);
259 relid = get_relname_relid(relname, namespaceId);
260 if (OidIsValid(relid))
264 /* Not found in path */
270 * Try to resolve an unqualified datatype name.
271 * Returns OID if type found in search path, else InvalidOid.
273 * This is essentially the same as RelnameGetRelid, but we never search
274 * the TEMP table namespace --- there is no reason to refer to the types
275 * of temp tables, AFAICS.
278 TypenameGetTypid(const char *typname)
284 * If system namespace is not in path, implicitly search it before path
286 if (!pathContainsSystemNamespace)
288 typid = GetSysCacheOid(TYPENAMENSP,
289 PointerGetDatum(typname),
290 ObjectIdGetDatum(PG_CATALOG_NAMESPACE),
292 if (OidIsValid(typid))
297 * Else search the path
299 foreach(lptr, namespaceSearchPath)
301 Oid namespaceId = (Oid) lfirsti(lptr);
303 typid = GetSysCacheOid(TYPENAMENSP,
304 PointerGetDatum(typname),
305 ObjectIdGetDatum(namespaceId),
307 if (OidIsValid(typid))
311 /* Not found in path */
316 * OpclassnameGetOpcid
317 * Try to resolve an unqualified index opclass name.
318 * Returns OID if opclass found in search path, else InvalidOid.
320 * This is essentially the same as TypenameGetTypid, but we have to have
321 * an extra argument for the index AM OID.
324 OpclassnameGetOpcid(Oid amid, const char *opcname)
330 * If system namespace is not in path, implicitly search it before path
332 if (!pathContainsSystemNamespace)
334 opcid = GetSysCacheOid(CLAAMNAMENSP,
335 ObjectIdGetDatum(amid),
336 PointerGetDatum(opcname),
337 ObjectIdGetDatum(PG_CATALOG_NAMESPACE),
339 if (OidIsValid(opcid))
344 * Else search the path
346 foreach(lptr, namespaceSearchPath)
348 Oid namespaceId = (Oid) lfirsti(lptr);
350 opcid = GetSysCacheOid(CLAAMNAMENSP,
351 ObjectIdGetDatum(amid),
352 PointerGetDatum(opcname),
353 ObjectIdGetDatum(namespaceId),
355 if (OidIsValid(opcid))
359 /* Not found in path */
364 * FuncnameGetCandidates
365 * Given a possibly-qualified function name and argument count,
366 * retrieve a list of the possible matches.
368 * We search a single namespace if the function name is qualified, else
369 * all namespaces in the search path. The return list will never contain
370 * multiple entries with identical argument types --- in the multiple-
371 * namespace case, we arrange for entries in earlier namespaces to mask
372 * identical entries in later namespaces.
375 FuncnameGetCandidates(List *names, int nargs)
377 FuncCandidateList resultList = NULL;
379 char *schemaname = NULL;
380 char *funcname = NULL;
385 /* deconstruct the name list */
386 switch (length(names))
389 funcname = strVal(lfirst(names));
392 schemaname = strVal(lfirst(names));
393 funcname = strVal(lsecond(names));
396 catalogname = strVal(lfirst(names));
397 schemaname = strVal(lsecond(names));
398 funcname = strVal(lfirst(lnext(lnext(names))));
400 * We check the catalog name and then ignore it.
402 if (strcmp(catalogname, DatabaseName) != 0)
403 elog(ERROR, "Cross-database references are not implemented");
406 elog(ERROR, "Improper qualified name (too many dotted names)");
412 /* use exact schema given */
413 namespaceId = GetSysCacheOid(NAMESPACENAME,
414 CStringGetDatum(schemaname),
416 if (!OidIsValid(namespaceId))
417 elog(ERROR, "Namespace \"%s\" does not exist",
422 /* flag to indicate we need namespace search */
423 namespaceId = InvalidOid;
426 /* Search syscache by name and nargs only */
427 catlist = SearchSysCacheList(PROCNAMENSP, 2,
428 CStringGetDatum(funcname),
429 Int16GetDatum(nargs),
432 for (i = 0; i < catlist->n_members; i++)
434 HeapTuple proctup = &catlist->members[i]->tuple;
435 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
437 FuncCandidateList newResult;
439 if (OidIsValid(namespaceId))
441 /* Consider only procs in specified namespace */
442 if (procform->pronamespace != namespaceId)
444 /* No need to check args, they must all be different */
448 /* Consider only procs that are in the search path */
449 if (pathContainsSystemNamespace ||
450 !IsSystemNamespace(procform->pronamespace))
454 foreach(nsp, namespaceSearchPath)
457 if (procform->pronamespace == (Oid) lfirsti(nsp))
461 continue; /* proc is not in search path */
465 * Okay, it's in the search path, but does it have the same
466 * arguments as something we already accepted? If so, keep
467 * only the one that appears earlier in the search path.
469 * If we have an ordered list from SearchSysCacheList (the
470 * normal case), then any conflicting proc must immediately
471 * adjoin this one in the list, so we only need to look at
472 * the newest result item. If we have an unordered list,
473 * we have to scan the whole result list.
477 FuncCandidateList prevResult;
479 if (catlist->ordered)
481 if (memcmp(procform->proargtypes, resultList->args,
482 nargs * sizeof(Oid)) == 0)
483 prevResult = resultList;
489 for (prevResult = resultList;
491 prevResult = prevResult->next)
493 if (memcmp(procform->proargtypes, prevResult->args,
494 nargs * sizeof(Oid)) == 0)
500 /* We have a match with a previous result */
501 Assert(pathpos != prevResult->pathpos);
502 if (pathpos > prevResult->pathpos)
503 continue; /* keep previous result */
504 /* replace previous result */
505 prevResult->pathpos = pathpos;
506 prevResult->oid = proctup->t_data->t_oid;
507 continue; /* args are same, of course */
513 * Okay to add it to result list
515 newResult = (FuncCandidateList)
516 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
517 + nargs * sizeof(Oid));
518 newResult->pathpos = pathpos;
519 newResult->oid = proctup->t_data->t_oid;
520 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
522 newResult->next = resultList;
523 resultList = newResult;
526 ReleaseSysCacheList(catlist);
532 * OpernameGetCandidates
533 * Given a possibly-qualified operator name and operator kind,
534 * retrieve a list of the possible matches.
536 * We search a single namespace if the operator name is qualified, else
537 * all namespaces in the search path. The return list will never contain
538 * multiple entries with identical argument types --- in the multiple-
539 * namespace case, we arrange for entries in earlier namespaces to mask
540 * identical entries in later namespaces.
542 * The returned items always have two args[] entries --- one or the other
543 * will be InvalidOid for a prefix or postfix oprkind.
546 OpernameGetCandidates(List *names, char oprkind)
548 FuncCandidateList resultList = NULL;
550 char *schemaname = NULL;
551 char *opername = NULL;
556 /* deconstruct the name list */
557 switch (length(names))
560 opername = strVal(lfirst(names));
563 schemaname = strVal(lfirst(names));
564 opername = strVal(lsecond(names));
567 catalogname = strVal(lfirst(names));
568 schemaname = strVal(lsecond(names));
569 opername = strVal(lfirst(lnext(lnext(names))));
571 * We check the catalog name and then ignore it.
573 if (strcmp(catalogname, DatabaseName) != 0)
574 elog(ERROR, "Cross-database references are not implemented");
577 elog(ERROR, "Improper qualified name (too many dotted names)");
583 /* use exact schema given */
584 namespaceId = GetSysCacheOid(NAMESPACENAME,
585 CStringGetDatum(schemaname),
587 if (!OidIsValid(namespaceId))
588 elog(ERROR, "Namespace \"%s\" does not exist",
593 /* flag to indicate we need namespace search */
594 namespaceId = InvalidOid;
597 /* Search syscache by name only */
598 catlist = SearchSysCacheList(OPERNAMENSP, 1,
599 CStringGetDatum(opername),
602 for (i = 0; i < catlist->n_members; i++)
604 HeapTuple opertup = &catlist->members[i]->tuple;
605 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
607 FuncCandidateList newResult;
609 /* Ignore operators of wrong kind */
610 if (operform->oprkind != oprkind)
613 if (OidIsValid(namespaceId))
615 /* Consider only opers in specified namespace */
616 if (operform->oprnamespace != namespaceId)
618 /* No need to check args, they must all be different */
622 /* Consider only opers that are in the search path */
623 if (pathContainsSystemNamespace ||
624 !IsSystemNamespace(operform->oprnamespace))
628 foreach(nsp, namespaceSearchPath)
631 if (operform->oprnamespace == (Oid) lfirsti(nsp))
635 continue; /* oper is not in search path */
639 * Okay, it's in the search path, but does it have the same
640 * arguments as something we already accepted? If so, keep
641 * only the one that appears earlier in the search path.
643 * If we have an ordered list from SearchSysCacheList (the
644 * normal case), then any conflicting oper must immediately
645 * adjoin this one in the list, so we only need to look at
646 * the newest result item. If we have an unordered list,
647 * we have to scan the whole result list.
651 FuncCandidateList prevResult;
653 if (catlist->ordered)
655 if (operform->oprleft == resultList->args[0] &&
656 operform->oprright == resultList->args[1])
657 prevResult = resultList;
663 for (prevResult = resultList;
665 prevResult = prevResult->next)
667 if (operform->oprleft == prevResult->args[0] &&
668 operform->oprright == prevResult->args[1])
674 /* We have a match with a previous result */
675 Assert(pathpos != prevResult->pathpos);
676 if (pathpos > prevResult->pathpos)
677 continue; /* keep previous result */
678 /* replace previous result */
679 prevResult->pathpos = pathpos;
680 prevResult->oid = opertup->t_data->t_oid;
681 continue; /* args are same, of course */
687 * Okay to add it to result list
689 newResult = (FuncCandidateList)
690 palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
691 newResult->pathpos = pathpos;
692 newResult->oid = opertup->t_data->t_oid;
693 newResult->args[0] = operform->oprleft;
694 newResult->args[1] = operform->oprright;
695 newResult->next = resultList;
696 resultList = newResult;
699 ReleaseSysCacheList(catlist);
705 * OpclassGetCandidates
706 * Given an index access method OID, retrieve a list of all the
707 * opclasses for that AM that are visible in the search path.
709 * NOTE: the opcname_tmp field in the returned structs should not be used
710 * by callers, because it points at syscache entries that we release at
711 * the end of this routine. If any callers needed the name information,
712 * we could pstrdup() the names ... but at present it'd be wasteful.
715 OpclassGetCandidates(Oid amid)
717 OpclassCandidateList resultList = NULL;
721 /* Search syscache by AM OID only */
722 catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
723 ObjectIdGetDatum(amid),
726 for (i = 0; i < catlist->n_members; i++)
728 HeapTuple opctup = &catlist->members[i]->tuple;
729 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
731 OpclassCandidateList newResult;
733 /* Consider only opclasses that are in the search path */
734 if (pathContainsSystemNamespace ||
735 !IsSystemNamespace(opcform->opcnamespace))
739 foreach(nsp, namespaceSearchPath)
742 if (opcform->opcnamespace == (Oid) lfirsti(nsp))
746 continue; /* opclass is not in search path */
750 * Okay, it's in the search path, but does it have the same name
751 * as something we already accepted? If so, keep
752 * only the one that appears earlier in the search path.
754 * If we have an ordered list from SearchSysCacheList (the
755 * normal case), then any conflicting opclass must immediately
756 * adjoin this one in the list, so we only need to look at
757 * the newest result item. If we have an unordered list,
758 * we have to scan the whole result list.
762 OpclassCandidateList prevResult;
764 if (catlist->ordered)
766 if (strcmp(NameStr(opcform->opcname),
767 resultList->opcname_tmp) == 0)
768 prevResult = resultList;
774 for (prevResult = resultList;
776 prevResult = prevResult->next)
778 if (strcmp(NameStr(opcform->opcname),
779 prevResult->opcname_tmp) == 0)
785 /* We have a match with a previous result */
786 Assert(pathpos != prevResult->pathpos);
787 if (pathpos > prevResult->pathpos)
788 continue; /* keep previous result */
789 /* replace previous result */
790 prevResult->opcname_tmp = NameStr(opcform->opcname);
791 prevResult->pathpos = pathpos;
792 prevResult->oid = opctup->t_data->t_oid;
793 prevResult->opcintype = opcform->opcintype;
794 prevResult->opcdefault = opcform->opcdefault;
795 prevResult->opckeytype = opcform->opckeytype;
801 * Okay to add it to result list
803 newResult = (OpclassCandidateList)
804 palloc(sizeof(struct _OpclassCandidateList));
805 newResult->opcname_tmp = NameStr(opcform->opcname);
806 newResult->pathpos = pathpos;
807 newResult->oid = opctup->t_data->t_oid;
808 newResult->opcintype = opcform->opcintype;
809 newResult->opcdefault = opcform->opcdefault;
810 newResult->opckeytype = opcform->opckeytype;
811 newResult->next = resultList;
812 resultList = newResult;
815 ReleaseSysCacheList(catlist);
822 * QualifiedNameGetCreationNamespace
823 * Given a possibly-qualified name for an object (in List-of-Values
824 * format), determine what namespace the object should be created in.
825 * Also extract and return the object name (last component of list).
827 * This is *not* used for tables. Hence, the TEMP table namespace is
828 * never selected as the creation target.
831 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
834 char *schemaname = NULL;
835 char *objname = NULL;
838 /* deconstruct the name list */
839 switch (length(names))
842 objname = strVal(lfirst(names));
845 schemaname = strVal(lfirst(names));
846 objname = strVal(lsecond(names));
849 catalogname = strVal(lfirst(names));
850 schemaname = strVal(lsecond(names));
851 objname = strVal(lfirst(lnext(lnext(names))));
853 * We check the catalog name and then ignore it.
855 if (strcmp(catalogname, DatabaseName) != 0)
856 elog(ERROR, "Cross-database references are not implemented");
859 elog(ERROR, "Improper qualified name (too many dotted names)");
865 /* use exact schema given */
866 namespaceId = GetSysCacheOid(NAMESPACENAME,
867 CStringGetDatum(schemaname),
869 if (!OidIsValid(namespaceId))
870 elog(ERROR, "Namespace \"%s\" does not exist",
875 /* use the default creation namespace */
876 namespaceId = defaultCreationNamespace;
877 if (!OidIsValid(namespaceId))
878 elog(ERROR, "No namespace has been selected to create in");
881 *objname_p = objname;
886 * makeRangeVarFromNameList
887 * Utility routine to convert a qualified-name list into RangeVar form.
890 makeRangeVarFromNameList(List *names)
892 RangeVar *rel = makeRangeVar(NULL, NULL);
894 switch (length(names))
897 rel->relname = strVal(lfirst(names));
900 rel->schemaname = strVal(lfirst(names));
901 rel->relname = strVal(lsecond(names));
904 rel->catalogname = strVal(lfirst(names));
905 rel->schemaname = strVal(lsecond(names));
906 rel->relname = strVal(lfirst(lnext(lnext(names))));
909 elog(ERROR, "Improper relation name (too many dotted names)");
918 * Utility routine to convert a qualified-name list into a string.
919 * Used primarily to form error messages.
922 NameListToString(List *names)
924 StringInfoData string;
927 initStringInfo(&string);
932 appendStringInfoChar(&string, '.');
933 appendStringInfo(&string, "%s", strVal(lfirst(l)));
940 * isTempNamespace - is the given namespace my temporary-table namespace?
943 isTempNamespace(Oid namespaceId)
945 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
951 * GetTempTableNamespace
952 * Initialize temp table namespace on first use in a particular backend
955 GetTempTableNamespace(void)
957 char namespaceName[NAMEDATALEN];
960 snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
962 namespaceId = GetSysCacheOid(NAMESPACENAME,
963 CStringGetDatum(namespaceName),
965 if (!OidIsValid(namespaceId))
968 * First use of this temp namespace in this database; create it.
969 * The temp namespaces are always owned by the superuser.
971 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
972 /* Advance command counter to make namespace visible */
973 CommandCounterIncrement();
978 * If the namespace already exists, clean it out (in case the
979 * former owner crashed without doing so).
981 RemoveTempRelations(namespaceId);
985 * Register exit callback to clean out temp tables at backend shutdown.
987 on_shmem_exit(RemoveTempRelationsCallback, 0);
993 * Remove all relations in the specified temp namespace.
995 * This is called at backend shutdown (if we made any temp relations).
996 * It is also called when we begin using a pre-existing temp namespace,
997 * in order to clean out any relations that might have been created by
1001 RemoveTempRelations(Oid tempNamespaceId)
1004 List *constraintList;
1007 /* Get a list of relations to delete */
1008 tempRelList = FindTempRelations(tempNamespaceId);
1010 if (tempRelList == NIL)
1011 return; /* nothing to do */
1013 /* If more than one, sort them to respect any deletion-order constraints */
1014 if (length(tempRelList) > 1)
1016 constraintList = FindDeletionConstraints(tempRelList);
1017 if (constraintList != NIL)
1018 tempRelList = TopoSortRels(tempRelList, constraintList);
1021 /* Scan the list and delete all entries */
1022 foreach(lptr, tempRelList)
1024 Oid reloid = (Oid) lfirsti(lptr);
1026 heap_drop_with_catalog(reloid, true);
1028 * Advance cmd counter to make catalog changes visible, in case
1029 * a later entry depends on this one.
1031 CommandCounterIncrement();
1036 * Find all relations in the specified temp namespace.
1038 * Returns a list of relation OIDs.
1041 FindTempRelations(Oid tempNamespaceId)
1043 List *tempRelList = NIL;
1050 * Scan pg_class to find all the relations in the target namespace.
1051 * Ignore indexes, though, on the assumption that they'll go away
1052 * when their tables are deleted.
1054 ScanKeyEntryInitialize(&key, 0x0,
1055 Anum_pg_class_relnamespace,
1057 ObjectIdGetDatum(tempNamespaceId));
1059 pgclass = heap_openr(RelationRelationName, AccessShareLock);
1060 scan = heap_beginscan(pgclass, false, SnapshotNow, 1, &key);
1062 while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
1064 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1066 case RELKIND_RELATION:
1067 case RELKIND_SEQUENCE:
1069 tempRelList = lconsi(tuple->t_data->t_oid, tempRelList);
1077 heap_close(pgclass, AccessShareLock);
1083 * Find deletion-order constraints involving the given relation OIDs.
1085 * Returns a list of DelConstraint objects.
1088 FindDeletionConstraints(List *relOids)
1090 List *constraintList = NIL;
1091 Relation inheritsrel;
1096 * Scan pg_inherits to find parents and children that are in the list.
1098 inheritsrel = heap_openr(InheritsRelationName, AccessShareLock);
1099 scan = heap_beginscan(inheritsrel, 0, SnapshotNow, 0, NULL);
1101 while (HeapTupleIsValid(tuple = heap_getnext(scan, 0)))
1103 Oid inhrelid = ((Form_pg_inherits) GETSTRUCT(tuple))->inhrelid;
1104 Oid inhparent = ((Form_pg_inherits) GETSTRUCT(tuple))->inhparent;
1106 if (intMember(inhrelid, relOids) && intMember(inhparent, relOids))
1108 DelConstraint *item;
1110 item = (DelConstraint *) palloc(sizeof(DelConstraint));
1111 item->referencer = inhrelid;
1112 item->referencee = inhparent;
1113 constraintList = lcons(item, constraintList);
1118 heap_close(inheritsrel, AccessShareLock);
1120 return constraintList;
1124 * TopoSortRels -- topological sort of a list of rels to delete
1126 * This is a lot simpler and slower than, for example, the topological sort
1127 * algorithm shown in Knuth's Volume 1. However, we are not likely to be
1128 * working with more than a few constraints, so the apparent slowness of the
1129 * algorithm won't really matter.
1132 TopoSortRels(List *relOids, List *constraintList)
1134 int queue_size = length(relOids);
1136 int *beforeConstraints;
1137 DelConstraint **afterConstraints;
1138 List *resultList = NIL;
1145 /* Allocate workspace */
1146 rels = (Oid *) palloc(queue_size * sizeof(Oid));
1147 beforeConstraints = (int *) palloc(queue_size * sizeof(int));
1148 afterConstraints = (DelConstraint **)
1149 palloc(queue_size * sizeof(DelConstraint*));
1151 /* Build an array of the target relation OIDs */
1153 foreach(lptr, relOids)
1155 rels[i++] = (Oid) lfirsti(lptr);
1159 * Scan the constraints, and for each rel in the array, generate a
1160 * count of the number of constraints that say it must be before
1161 * something else, plus a list of the constraints that say it must be
1162 * after something else. The count for the j'th rel is stored in
1163 * beforeConstraints[j], and the head of its list in
1164 * afterConstraints[j]. Each constraint stores its list link in
1165 * its link field (note any constraint will be in just one list).
1166 * The array index for the before-rel of each constraint is
1167 * remembered in the constraint's pred field.
1169 MemSet(beforeConstraints, 0, queue_size * sizeof(int));
1170 MemSet(afterConstraints, 0, queue_size * sizeof(DelConstraint*));
1171 foreach(lptr, constraintList)
1173 DelConstraint *constraint = (DelConstraint *) lfirst(lptr);
1176 /* Find the referencer rel in the array */
1177 rel = constraint->referencer;
1178 for (j = queue_size; --j >= 0;)
1183 Assert(j >= 0); /* should have found a match */
1184 /* Find the referencee rel in the array */
1185 rel = constraint->referencee;
1186 for (k = queue_size; --k >= 0;)
1191 Assert(k >= 0); /* should have found a match */
1192 beforeConstraints[j]++; /* referencer must come before */
1193 /* add this constraint to list of after-constraints for referencee */
1194 constraint->pred = j;
1195 constraint->link = afterConstraints[k];
1196 afterConstraints[k] = constraint;
1198 /*--------------------
1199 * Now scan the rels array backwards. At each step, output the
1200 * last rel that has no remaining before-constraints, and decrease
1201 * the beforeConstraints count of each of the rels it was constrained
1202 * against. (This is the right order since we are building the result
1203 * list back-to-front.)
1204 * i = counter for number of rels left to output
1205 * j = search index for rels[]
1206 * dc = temp for scanning constraint list for rel j
1207 * last = last valid index in rels (avoid redundant searches)
1208 *--------------------
1210 last = queue_size - 1;
1211 for (i = queue_size; --i >= 0;)
1215 /* Find next candidate to output */
1216 while (rels[last] == InvalidOid)
1218 for (j = last; j >= 0; j--)
1220 if (rels[j] != InvalidOid && beforeConstraints[j] == 0)
1223 /* If no available candidate, topological sort fails */
1225 elog(ERROR, "TopoSortRels: failed to find a workable deletion ordering");
1226 /* Output candidate, and mark it done by zeroing rels[] entry */
1227 resultList = lconsi(rels[j], resultList);
1228 rels[j] = InvalidOid;
1229 /* Update beforeConstraints counts of its predecessors */
1230 for (dc = afterConstraints[j]; dc; dc = dc->link)
1231 beforeConstraints[dc->pred]--;
1239 * Callback to remove temp relations at backend exit.
1242 RemoveTempRelationsCallback(void)
1244 if (OidIsValid(myTempNamespace)) /* should always be true */
1246 /* Need to ensure we have a usable transaction. */
1247 AbortOutOfAnyTransaction();
1248 StartTransactionCommand();
1250 RemoveTempRelations(myTempNamespace);
1252 CommitTransactionCommand();
1257 * Routines for handling the GUC variable 'search_path'.
1260 /* parse_hook: is proposed value valid? */
1262 check_search_path(const char *proposed)
1268 /* Need a modifiable copy of string */
1269 rawname = pstrdup(proposed);
1271 /* Parse string into list of identifiers */
1272 if (!SplitIdentifierString(rawname, ',', &namelist))
1274 /* syntax error in name list */
1281 * If we aren't inside a transaction, we cannot do database access so
1282 * cannot verify the individual names. Must accept the list on faith.
1283 * (This case can happen, for example, when the postmaster reads a
1284 * search_path setting from postgresql.conf.)
1286 if (!IsTransactionState())
1294 * Verify that all the names are either valid namespace names or "$user".
1295 * (We do not require $user to correspond to a valid namespace; should we?)
1297 foreach(l, namelist)
1299 char *curname = (char *) lfirst(l);
1301 if (strcmp(curname, "$user") == 0)
1303 if (!SearchSysCacheExists(NAMESPACENAME,
1304 CStringGetDatum(curname),
1319 /* assign_hook: do extra actions needed when assigning to search_path */
1321 assign_search_path(const char *newval)
1328 MemoryContext oldcxt;
1331 * If we aren't inside a transaction, we cannot do database access so
1332 * cannot look up the names. In this case, do nothing; the internal
1333 * search path will be fixed later by InitializeSearchPath. (We assume
1334 * this situation can only happen in the postmaster or early in backend
1337 if (!IsTransactionState())
1340 /* Need a modifiable copy of string */
1341 rawname = pstrdup(newval);
1343 /* Parse string into list of identifiers */
1344 if (!SplitIdentifierString(rawname, ',', &namelist))
1346 /* syntax error in name list */
1347 /* this should not happen if GUC checked check_search_path */
1348 elog(ERROR, "assign_search_path: invalid list syntax");
1352 * Convert the list of names to a list of OIDs. If any names are not
1353 * recognizable, just leave them out of the list. (This is our only
1354 * reasonable recourse when the already-accepted default is bogus.)
1357 foreach(l, namelist)
1359 char *curname = (char *) lfirst(l);
1362 if (strcmp(curname, "$user") == 0)
1364 /* $user --- substitute namespace matching user name, if any */
1367 tuple = SearchSysCache(SHADOWSYSID,
1368 ObjectIdGetDatum(GetSessionUserId()),
1370 if (HeapTupleIsValid(tuple))
1374 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1375 namespaceId = GetSysCacheOid(NAMESPACENAME,
1376 CStringGetDatum(uname),
1378 if (OidIsValid(namespaceId))
1379 oidlist = lappendi(oidlist, namespaceId);
1380 ReleaseSysCache(tuple);
1385 /* normal namespace reference */
1386 namespaceId = GetSysCacheOid(NAMESPACENAME,
1387 CStringGetDatum(curname),
1389 if (OidIsValid(namespaceId))
1390 oidlist = lappendi(oidlist, namespaceId);
1395 * Now that we've successfully built the new list of namespace OIDs,
1396 * save it in permanent storage.
1398 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1399 newpath = listCopy(oidlist);
1400 MemoryContextSwitchTo(oldcxt);
1402 /* Now safe to assign to state variable. */
1403 freeList(namespaceSearchPath);
1404 namespaceSearchPath = newpath;
1407 * Update info derived from search path.
1409 pathContainsSystemNamespace = intMember(PG_CATALOG_NAMESPACE,
1410 namespaceSearchPath);
1412 if (namespaceSearchPath == NIL)
1413 defaultCreationNamespace = InvalidOid;
1415 defaultCreationNamespace = (Oid) lfirsti(namespaceSearchPath);
1424 * InitializeSearchPath: initialize module during InitPostgres.
1426 * This is called after we are up enough to be able to do catalog lookups.
1429 InitializeSearchPath(void)
1431 if (IsBootstrapProcessingMode())
1434 * In bootstrap mode, the search path must be 'pg_catalog' so that
1435 * tables are created in the proper namespace; ignore the GUC setting.
1437 MemoryContext oldcxt;
1439 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1440 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1441 MemoryContextSwitchTo(oldcxt);
1442 pathContainsSystemNamespace = true;
1443 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1448 * If a search path setting was provided before we were able to
1449 * execute lookups, establish the internal search path now.
1451 if (namespace_search_path && *namespace_search_path &&
1452 namespaceSearchPath == NIL)
1453 assign_search_path(namespace_search_path);