]> granicus.if.org Git - postgresql/blob - src/backend/catalog/namespace.c
Apply the proper version of Christopher Kings-Lynne's describe patch
[postgresql] / src / backend / catalog / namespace.c
1 /*-------------------------------------------------------------------------
2  *
3  * namespace.c
4  *        code to support accessing and searching namespaces
5  *
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.
10  *
11  *
12  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  * IDENTIFICATION
16  *        $Header: /cvsroot/pgsql/src/backend/catalog/namespace.c,v 1.43 2003/01/07 20:56:06 tgl Exp $
17  *
18  *-------------------------------------------------------------------------
19  */
20 #include "postgres.h"
21
22 #include "access/heapam.h"
23 #include "access/xact.h"
24 #include "catalog/catalog.h"
25 #include "catalog/catname.h"
26 #include "catalog/dependency.h"
27 #include "catalog/heap.h"
28 #include "catalog/namespace.h"
29 #include "catalog/pg_conversion.h"
30 #include "catalog/pg_inherits.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_operator.h"
34 #include "catalog/pg_proc.h"
35 #include "catalog/pg_shadow.h"
36 #include "catalog/pg_type.h"
37 #include "lib/stringinfo.h"
38 #include "miscadmin.h"
39 #include "nodes/makefuncs.h"
40 #include "storage/backendid.h"
41 #include "storage/ipc.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/catcache.h"
45 #include "utils/fmgroids.h"
46 #include "utils/guc.h"
47 #include "utils/inval.h"
48 #include "utils/lsyscache.h"
49 #include "utils/syscache.h"
50
51
52 /*
53  * The namespace search path is a possibly-empty list of namespace OIDs.
54  * In addition to the explicit list, several implicitly-searched namespaces
55  * may be included:
56  *
57  * 1. If a "special" namespace has been set by PushSpecialNamespace, it is
58  * always searched first.  (This is a hack for CREATE SCHEMA.)
59  *
60  * 2. If a TEMP table namespace has been initialized in this session, it
61  * is always searched just after any special namespace.
62  *
63  * 3. The system catalog namespace is always searched.  If the system
64  * namespace is present in the explicit path then it will be searched in
65  * the specified order; otherwise it will be searched after TEMP tables and
66  * *before* the explicit list.  (It might seem that the system namespace
67  * should be implicitly last, but this behavior appears to be required by
68  * SQL99.  Also, this provides a way to search the system namespace first
69  * without thereby making it the default creation target namespace.)
70  *
71  * The default creation target namespace is normally equal to the first
72  * element of the explicit list, but is the "special" namespace when one
73  * has been set.  If the explicit list is empty and there is no special
74  * namespace, there is no default target.
75  *
76  * In bootstrap mode, the search path is set equal to 'pg_catalog', so that
77  * the system namespace is the only one searched or inserted into.
78  * The initdb script is also careful to set search_path to 'pg_catalog' for
79  * its post-bootstrap standalone backend runs.  Otherwise the default search
80  * path is determined by GUC.  The factory default path contains the PUBLIC
81  * namespace (if it exists), preceded by the user's personal namespace
82  * (if one exists).
83  *
84  * If namespaceSearchPathValid is false, then namespaceSearchPath (and other
85  * derived variables) need to be recomputed from namespace_search_path.
86  * We mark it invalid upon an assignment to namespace_search_path or receipt
87  * of a syscache invalidation event for pg_namespace.  The recomputation
88  * is done during the next lookup attempt.
89  *
90  * Any namespaces mentioned in namespace_search_path that are not readable
91  * by the current user ID are simply left out of namespaceSearchPath; so
92  * we have to be willing to recompute the path when current userid changes.
93  * namespaceUser is the userid the path has been computed for.
94  */
95
96 static List *namespaceSearchPath = NIL;
97
98 static Oid      namespaceUser = InvalidOid;
99
100 /* default place to create stuff; if InvalidOid, no default */
101 static Oid      defaultCreationNamespace = InvalidOid;
102
103 /* first explicit member of list; usually same as defaultCreationNamespace */
104 static Oid      firstExplicitNamespace = InvalidOid;
105
106 /* The above four values are valid only if namespaceSearchPathValid */
107 static bool namespaceSearchPathValid = true;
108
109 /*
110  * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
111  * in a particular backend session (this happens when a CREATE TEMP TABLE
112  * command is first executed).  Thereafter it's the OID of the temp namespace.
113  * firstTempTransaction flags whether we've committed creation of the TEMP
114  * namespace or not.
115  */
116 static Oid      myTempNamespace = InvalidOid;
117
118 static bool firstTempTransaction = false;
119
120 /*
121  * "Special" namespace for CREATE SCHEMA.  If set, it's the first search
122  * path element, and also the default creation namespace.
123  */
124 static Oid      mySpecialNamespace = InvalidOid;
125
126 /*
127  * This is the text equivalent of the search path --- it's the value
128  * of the GUC variable 'search_path'.
129  */
130 char       *namespace_search_path = NULL;
131
132
133 /* Local functions */
134 static void recomputeNamespacePath(void);
135 static void InitTempTableNamespace(void);
136 static void RemoveTempRelations(Oid tempNamespaceId);
137 static void RemoveTempRelationsCallback(void);
138 static void NamespaceCallback(Datum arg, Oid relid);
139
140 /* These don't really need to appear in any header file */
141 Datum           pg_table_is_visible(PG_FUNCTION_ARGS);
142 Datum           pg_type_is_visible(PG_FUNCTION_ARGS);
143 Datum           pg_function_is_visible(PG_FUNCTION_ARGS);
144 Datum           pg_operator_is_visible(PG_FUNCTION_ARGS);
145 Datum           pg_opclass_is_visible(PG_FUNCTION_ARGS);
146 Datum           pg_conversion_is_visible(PG_FUNCTION_ARGS);
147
148
149 /*
150  * RangeVarGetRelid
151  *              Given a RangeVar describing an existing relation,
152  *              select the proper namespace and look up the relation OID.
153  *
154  * If the relation is not found, return InvalidOid if failOK = true,
155  * otherwise raise an error.
156  */
157 Oid
158 RangeVarGetRelid(const RangeVar *relation, bool failOK)
159 {
160         Oid                     namespaceId;
161         Oid                     relId;
162
163         /*
164          * We check the catalog name and then ignore it.
165          */
166         if (relation->catalogname)
167         {
168                 if (strcmp(relation->catalogname, DatabaseName) != 0)
169                         elog(ERROR, "Cross-database references are not implemented");
170         }
171
172         if (relation->schemaname)
173         {
174                 /* use exact schema given */
175                 namespaceId = LookupExplicitNamespace(relation->schemaname);
176                 relId = get_relname_relid(relation->relname, namespaceId);
177         }
178         else
179         {
180                 /* search the namespace path */
181                 relId = RelnameGetRelid(relation->relname);
182         }
183
184         if (!OidIsValid(relId) && !failOK)
185         {
186                 if (relation->schemaname)
187                         elog(ERROR, "Relation \"%s\".\"%s\" does not exist",
188                                  relation->schemaname, relation->relname);
189                 else
190                         elog(ERROR, "Relation \"%s\" does not exist",
191                                  relation->relname);
192         }
193         return relId;
194 }
195
196 /*
197  * RangeVarGetCreationNamespace
198  *              Given a RangeVar describing a to-be-created relation,
199  *              choose which namespace to create it in.
200  *
201  * Note: calling this may result in a CommandCounterIncrement operation.
202  * That will happen on the first request for a temp table in any particular
203  * backend run; we will need to either create or clean out the temp schema.
204  */
205 Oid
206 RangeVarGetCreationNamespace(const RangeVar *newRelation)
207 {
208         Oid                     namespaceId;
209
210         /*
211          * We check the catalog name and then ignore it.
212          */
213         if (newRelation->catalogname)
214         {
215                 if (strcmp(newRelation->catalogname, DatabaseName) != 0)
216                         elog(ERROR, "Cross-database references are not implemented");
217         }
218
219         if (newRelation->istemp)
220         {
221                 /* TEMP tables are created in our backend-local temp namespace */
222                 if (newRelation->schemaname)
223                         elog(ERROR, "TEMP tables may not specify a namespace");
224                 /* Initialize temp namespace if first time through */
225                 if (!OidIsValid(myTempNamespace))
226                         InitTempTableNamespace();
227                 return myTempNamespace;
228         }
229
230         if (newRelation->schemaname)
231         {
232                 /* use exact schema given */
233                 namespaceId = GetSysCacheOid(NAMESPACENAME,
234                                                                 CStringGetDatum(newRelation->schemaname),
235                                                                          0, 0, 0);
236                 if (!OidIsValid(namespaceId))
237                         elog(ERROR, "Namespace \"%s\" does not exist",
238                                  newRelation->schemaname);
239                 /* we do not check for USAGE rights here! */
240         }
241         else
242         {
243                 /* use the default creation namespace */
244                 recomputeNamespacePath();
245                 namespaceId = defaultCreationNamespace;
246                 if (!OidIsValid(namespaceId))
247                         elog(ERROR, "No namespace has been selected to create in");
248         }
249
250         /* Note: callers will check for CREATE rights when appropriate */
251
252         return namespaceId;
253 }
254
255 /*
256  * RelnameGetRelid
257  *              Try to resolve an unqualified relation name.
258  *              Returns OID if relation found in search path, else InvalidOid.
259  */
260 Oid
261 RelnameGetRelid(const char *relname)
262 {
263         Oid                     relid;
264         List       *lptr;
265
266         recomputeNamespacePath();
267
268         foreach(lptr, namespaceSearchPath)
269         {
270                 Oid                     namespaceId = (Oid) lfirsti(lptr);
271
272                 relid = get_relname_relid(relname, namespaceId);
273                 if (OidIsValid(relid))
274                         return relid;
275         }
276
277         /* Not found in path */
278         return InvalidOid;
279 }
280
281 /*
282  * RelationIsVisible
283  *              Determine whether a relation (identified by OID) is visible in the
284  *              current search path.  Visible means "would be found by searching
285  *              for the unqualified relation name".
286  */
287 bool
288 RelationIsVisible(Oid relid)
289 {
290         HeapTuple       reltup;
291         Form_pg_class relform;
292         Oid                     relnamespace;
293         bool            visible;
294
295         reltup = SearchSysCache(RELOID,
296                                                         ObjectIdGetDatum(relid),
297                                                         0, 0, 0);
298         if (!HeapTupleIsValid(reltup))
299                 elog(ERROR, "Cache lookup failed for relation %u", relid);
300         relform = (Form_pg_class) GETSTRUCT(reltup);
301
302         recomputeNamespacePath();
303
304         /*
305          * Quick check: if it ain't in the path at all, it ain't visible.
306          * Items in the system namespace are surely in the path and so we
307          * needn't even do intMember() for them.
308          */
309         relnamespace = relform->relnamespace;
310         if (relnamespace != PG_CATALOG_NAMESPACE &&
311                 !intMember(relnamespace, namespaceSearchPath))
312                 visible = false;
313         else
314         {
315                 /*
316                  * If it is in the path, it might still not be visible; it could
317                  * be hidden by another relation of the same name earlier in the
318                  * path. So we must do a slow check to see if this rel would be
319                  * found by RelnameGetRelid.
320                  */
321                 char       *relname = NameStr(relform->relname);
322
323                 visible = (RelnameGetRelid(relname) == relid);
324         }
325
326         ReleaseSysCache(reltup);
327
328         return visible;
329 }
330
331
332 /*
333  * TypenameGetTypid
334  *              Try to resolve an unqualified datatype name.
335  *              Returns OID if type found in search path, else InvalidOid.
336  *
337  * This is essentially the same as RelnameGetRelid.
338  */
339 Oid
340 TypenameGetTypid(const char *typname)
341 {
342         Oid                     typid;
343         List       *lptr;
344
345         recomputeNamespacePath();
346
347         foreach(lptr, namespaceSearchPath)
348         {
349                 Oid                     namespaceId = (Oid) lfirsti(lptr);
350
351                 typid = GetSysCacheOid(TYPENAMENSP,
352                                                            PointerGetDatum(typname),
353                                                            ObjectIdGetDatum(namespaceId),
354                                                            0, 0);
355                 if (OidIsValid(typid))
356                         return typid;
357         }
358
359         /* Not found in path */
360         return InvalidOid;
361 }
362
363 /*
364  * TypeIsVisible
365  *              Determine whether a type (identified by OID) is visible in the
366  *              current search path.  Visible means "would be found by searching
367  *              for the unqualified type name".
368  */
369 bool
370 TypeIsVisible(Oid typid)
371 {
372         HeapTuple       typtup;
373         Form_pg_type typform;
374         Oid                     typnamespace;
375         bool            visible;
376
377         typtup = SearchSysCache(TYPEOID,
378                                                         ObjectIdGetDatum(typid),
379                                                         0, 0, 0);
380         if (!HeapTupleIsValid(typtup))
381                 elog(ERROR, "Cache lookup failed for type %u", typid);
382         typform = (Form_pg_type) GETSTRUCT(typtup);
383
384         recomputeNamespacePath();
385
386         /*
387          * Quick check: if it ain't in the path at all, it ain't visible.
388          * Items in the system namespace are surely in the path and so we
389          * needn't even do intMember() for them.
390          */
391         typnamespace = typform->typnamespace;
392         if (typnamespace != PG_CATALOG_NAMESPACE &&
393                 !intMember(typnamespace, namespaceSearchPath))
394                 visible = false;
395         else
396         {
397                 /*
398                  * If it is in the path, it might still not be visible; it could
399                  * be hidden by another type of the same name earlier in the path.
400                  * So we must do a slow check to see if this type would be found
401                  * by TypenameGetTypid.
402                  */
403                 char       *typname = NameStr(typform->typname);
404
405                 visible = (TypenameGetTypid(typname) == typid);
406         }
407
408         ReleaseSysCache(typtup);
409
410         return visible;
411 }
412
413
414 /*
415  * FuncnameGetCandidates
416  *              Given a possibly-qualified function name and argument count,
417  *              retrieve a list of the possible matches.
418  *
419  * If nargs is -1, we return all functions matching the given name,
420  * regardless of argument count.
421  *
422  * We search a single namespace if the function name is qualified, else
423  * all namespaces in the search path.  The return list will never contain
424  * multiple entries with identical argument lists --- in the multiple-
425  * namespace case, we arrange for entries in earlier namespaces to mask
426  * identical entries in later namespaces.
427  */
428 FuncCandidateList
429 FuncnameGetCandidates(List *names, int nargs)
430 {
431         FuncCandidateList resultList = NULL;
432         char       *schemaname;
433         char       *funcname;
434         Oid                     namespaceId;
435         CatCList   *catlist;
436         int                     i;
437
438         /* deconstruct the name list */
439         DeconstructQualifiedName(names, &schemaname, &funcname);
440
441         if (schemaname)
442         {
443                 /* use exact schema given */
444                 namespaceId = LookupExplicitNamespace(schemaname);
445         }
446         else
447         {
448                 /* flag to indicate we need namespace search */
449                 namespaceId = InvalidOid;
450                 recomputeNamespacePath();
451         }
452
453         /* Search syscache by name and (optionally) nargs only */
454         if (nargs >= 0)
455                 catlist = SearchSysCacheList(PROCNAMENSP, 2,
456                                                                          CStringGetDatum(funcname),
457                                                                          Int16GetDatum(nargs),
458                                                                          0, 0);
459         else
460                 catlist = SearchSysCacheList(PROCNAMENSP, 1,
461                                                                          CStringGetDatum(funcname),
462                                                                          0, 0, 0);
463
464         for (i = 0; i < catlist->n_members; i++)
465         {
466                 HeapTuple       proctup = &catlist->members[i]->tuple;
467                 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
468                 int                     pathpos = 0;
469                 FuncCandidateList newResult;
470
471                 nargs = procform->pronargs;
472
473                 if (OidIsValid(namespaceId))
474                 {
475                         /* Consider only procs in specified namespace */
476                         if (procform->pronamespace != namespaceId)
477                                 continue;
478                         /* No need to check args, they must all be different */
479                 }
480                 else
481                 {
482                         /* Consider only procs that are in the search path */
483                         List       *nsp;
484
485                         foreach(nsp, namespaceSearchPath)
486                         {
487                                 if (procform->pronamespace == (Oid) lfirsti(nsp))
488                                         break;
489                                 pathpos++;
490                         }
491                         if (nsp == NIL)
492                                 continue;               /* proc is not in search path */
493
494                         /*
495                          * Okay, it's in the search path, but does it have the same
496                          * arguments as something we already accepted?  If so, keep
497                          * only the one that appears earlier in the search path.
498                          *
499                          * If we have an ordered list from SearchSysCacheList (the normal
500                          * case), then any conflicting proc must immediately adjoin
501                          * this one in the list, so we only need to look at the newest
502                          * result item.  If we have an unordered list, we have to scan
503                          * the whole result list.
504                          */
505                         if (resultList)
506                         {
507                                 FuncCandidateList prevResult;
508
509                                 if (catlist->ordered)
510                                 {
511                                         if (nargs == resultList->nargs &&
512                                                 memcmp(procform->proargtypes, resultList->args,
513                                                            nargs * sizeof(Oid)) == 0)
514                                                 prevResult = resultList;
515                                         else
516                                                 prevResult = NULL;
517                                 }
518                                 else
519                                 {
520                                         for (prevResult = resultList;
521                                                  prevResult;
522                                                  prevResult = prevResult->next)
523                                         {
524                                                 if (nargs == prevResult->nargs &&
525                                                   memcmp(procform->proargtypes, prevResult->args,
526                                                                  nargs * sizeof(Oid)) == 0)
527                                                         break;
528                                         }
529                                 }
530                                 if (prevResult)
531                                 {
532                                         /* We have a match with a previous result */
533                                         Assert(pathpos != prevResult->pathpos);
534                                         if (pathpos > prevResult->pathpos)
535                                                 continue;               /* keep previous result */
536                                         /* replace previous result */
537                                         prevResult->pathpos = pathpos;
538                                         prevResult->oid = HeapTupleGetOid(proctup);
539                                         continue;       /* args are same, of course */
540                                 }
541                         }
542                 }
543
544                 /*
545                  * Okay to add it to result list
546                  */
547                 newResult = (FuncCandidateList)
548                         palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
549                                    + nargs * sizeof(Oid));
550                 newResult->pathpos = pathpos;
551                 newResult->oid = HeapTupleGetOid(proctup);
552                 newResult->nargs = nargs;
553                 memcpy(newResult->args, procform->proargtypes, nargs * sizeof(Oid));
554
555                 newResult->next = resultList;
556                 resultList = newResult;
557         }
558
559         ReleaseSysCacheList(catlist);
560
561         return resultList;
562 }
563
564 /*
565  * FunctionIsVisible
566  *              Determine whether a function (identified by OID) is visible in the
567  *              current search path.  Visible means "would be found by searching
568  *              for the unqualified function name with exact argument matches".
569  */
570 bool
571 FunctionIsVisible(Oid funcid)
572 {
573         HeapTuple       proctup;
574         Form_pg_proc procform;
575         Oid                     pronamespace;
576         bool            visible;
577
578         proctup = SearchSysCache(PROCOID,
579                                                          ObjectIdGetDatum(funcid),
580                                                          0, 0, 0);
581         if (!HeapTupleIsValid(proctup))
582                 elog(ERROR, "Cache lookup failed for procedure %u", funcid);
583         procform = (Form_pg_proc) GETSTRUCT(proctup);
584
585         recomputeNamespacePath();
586
587         /*
588          * Quick check: if it ain't in the path at all, it ain't visible.
589          * Items in the system namespace are surely in the path and so we
590          * needn't even do intMember() for them.
591          */
592         pronamespace = procform->pronamespace;
593         if (pronamespace != PG_CATALOG_NAMESPACE &&
594                 !intMember(pronamespace, namespaceSearchPath))
595                 visible = false;
596         else
597         {
598                 /*
599                  * If it is in the path, it might still not be visible; it could
600                  * be hidden by another proc of the same name and arguments
601                  * earlier in the path.  So we must do a slow check to see if this
602                  * is the same proc that would be found by FuncnameGetCandidates.
603                  */
604                 char       *proname = NameStr(procform->proname);
605                 int                     nargs = procform->pronargs;
606                 FuncCandidateList clist;
607
608                 visible = false;
609
610                 clist = FuncnameGetCandidates(makeList1(makeString(proname)), nargs);
611
612                 for (; clist; clist = clist->next)
613                 {
614                         if (memcmp(clist->args, procform->proargtypes,
615                                            nargs * sizeof(Oid)) == 0)
616                         {
617                                 /* Found the expected entry; is it the right proc? */
618                                 visible = (clist->oid == funcid);
619                                 break;
620                         }
621                 }
622         }
623
624         ReleaseSysCache(proctup);
625
626         return visible;
627 }
628
629
630 /*
631  * OpernameGetCandidates
632  *              Given a possibly-qualified operator name and operator kind,
633  *              retrieve a list of the possible matches.
634  *
635  * If oprkind is '\0', we return all operators matching the given name,
636  * regardless of arguments.
637  *
638  * We search a single namespace if the operator name is qualified, else
639  * all namespaces in the search path.  The return list will never contain
640  * multiple entries with identical argument lists --- in the multiple-
641  * namespace case, we arrange for entries in earlier namespaces to mask
642  * identical entries in later namespaces.
643  *
644  * The returned items always have two args[] entries --- one or the other
645  * will be InvalidOid for a prefix or postfix oprkind.  nargs is 2, too.
646  */
647 FuncCandidateList
648 OpernameGetCandidates(List *names, char oprkind)
649 {
650         FuncCandidateList resultList = NULL;
651         char       *schemaname;
652         char       *opername;
653         Oid                     namespaceId;
654         CatCList   *catlist;
655         int                     i;
656
657         /* deconstruct the name list */
658         DeconstructQualifiedName(names, &schemaname, &opername);
659
660         if (schemaname)
661         {
662                 /* use exact schema given */
663                 namespaceId = LookupExplicitNamespace(schemaname);
664         }
665         else
666         {
667                 /* flag to indicate we need namespace search */
668                 namespaceId = InvalidOid;
669                 recomputeNamespacePath();
670         }
671
672         /* Search syscache by name only */
673         catlist = SearchSysCacheList(OPERNAMENSP, 1,
674                                                                  CStringGetDatum(opername),
675                                                                  0, 0, 0);
676
677         for (i = 0; i < catlist->n_members; i++)
678         {
679                 HeapTuple       opertup = &catlist->members[i]->tuple;
680                 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
681                 int                     pathpos = 0;
682                 FuncCandidateList newResult;
683
684                 /* Ignore operators of wrong kind, if specific kind requested */
685                 if (oprkind && operform->oprkind != oprkind)
686                         continue;
687
688                 if (OidIsValid(namespaceId))
689                 {
690                         /* Consider only opers in specified namespace */
691                         if (operform->oprnamespace != namespaceId)
692                                 continue;
693                         /* No need to check args, they must all be different */
694                 }
695                 else
696                 {
697                         /* Consider only opers that are in the search path */
698                         List       *nsp;
699
700                         foreach(nsp, namespaceSearchPath)
701                         {
702                                 if (operform->oprnamespace == (Oid) lfirsti(nsp))
703                                         break;
704                                 pathpos++;
705                         }
706                         if (nsp == NIL)
707                                 continue;               /* oper is not in search path */
708
709                         /*
710                          * Okay, it's in the search path, but does it have the same
711                          * arguments as something we already accepted?  If so, keep
712                          * only the one that appears earlier in the search path.
713                          *
714                          * If we have an ordered list from SearchSysCacheList (the normal
715                          * case), then any conflicting oper must immediately adjoin
716                          * this one in the list, so we only need to look at the newest
717                          * result item.  If we have an unordered list, we have to scan
718                          * the whole result list.
719                          */
720                         if (resultList)
721                         {
722                                 FuncCandidateList prevResult;
723
724                                 if (catlist->ordered)
725                                 {
726                                         if (operform->oprleft == resultList->args[0] &&
727                                                 operform->oprright == resultList->args[1])
728                                                 prevResult = resultList;
729                                         else
730                                                 prevResult = NULL;
731                                 }
732                                 else
733                                 {
734                                         for (prevResult = resultList;
735                                                  prevResult;
736                                                  prevResult = prevResult->next)
737                                         {
738                                                 if (operform->oprleft == prevResult->args[0] &&
739                                                         operform->oprright == prevResult->args[1])
740                                                         break;
741                                         }
742                                 }
743                                 if (prevResult)
744                                 {
745                                         /* We have a match with a previous result */
746                                         Assert(pathpos != prevResult->pathpos);
747                                         if (pathpos > prevResult->pathpos)
748                                                 continue;               /* keep previous result */
749                                         /* replace previous result */
750                                         prevResult->pathpos = pathpos;
751                                         prevResult->oid = HeapTupleGetOid(opertup);
752                                         continue;       /* args are same, of course */
753                                 }
754                         }
755                 }
756
757                 /*
758                  * Okay to add it to result list
759                  */
760                 newResult = (FuncCandidateList)
761                         palloc(sizeof(struct _FuncCandidateList) + sizeof(Oid));
762                 newResult->pathpos = pathpos;
763                 newResult->oid = HeapTupleGetOid(opertup);
764                 newResult->nargs = 2;
765                 newResult->args[0] = operform->oprleft;
766                 newResult->args[1] = operform->oprright;
767                 newResult->next = resultList;
768                 resultList = newResult;
769         }
770
771         ReleaseSysCacheList(catlist);
772
773         return resultList;
774 }
775
776 /*
777  * OperatorIsVisible
778  *              Determine whether an operator (identified by OID) is visible in the
779  *              current search path.  Visible means "would be found by searching
780  *              for the unqualified operator name with exact argument matches".
781  */
782 bool
783 OperatorIsVisible(Oid oprid)
784 {
785         HeapTuple       oprtup;
786         Form_pg_operator oprform;
787         Oid                     oprnamespace;
788         bool            visible;
789
790         oprtup = SearchSysCache(OPEROID,
791                                                         ObjectIdGetDatum(oprid),
792                                                         0, 0, 0);
793         if (!HeapTupleIsValid(oprtup))
794                 elog(ERROR, "Cache lookup failed for operator %u", oprid);
795         oprform = (Form_pg_operator) GETSTRUCT(oprtup);
796
797         recomputeNamespacePath();
798
799         /*
800          * Quick check: if it ain't in the path at all, it ain't visible.
801          * Items in the system namespace are surely in the path and so we
802          * needn't even do intMember() for them.
803          */
804         oprnamespace = oprform->oprnamespace;
805         if (oprnamespace != PG_CATALOG_NAMESPACE &&
806                 !intMember(oprnamespace, namespaceSearchPath))
807                 visible = false;
808         else
809         {
810                 /*
811                  * If it is in the path, it might still not be visible; it could
812                  * be hidden by another operator of the same name and arguments
813                  * earlier in the path.  So we must do a slow check to see if this
814                  * is the same operator that would be found by
815                  * OpernameGetCandidates.
816                  */
817                 char       *oprname = NameStr(oprform->oprname);
818                 FuncCandidateList clist;
819
820                 visible = false;
821
822                 clist = OpernameGetCandidates(makeList1(makeString(oprname)),
823                                                                           oprform->oprkind);
824
825                 for (; clist; clist = clist->next)
826                 {
827                         if (clist->args[0] == oprform->oprleft &&
828                                 clist->args[1] == oprform->oprright)
829                         {
830                                 /* Found the expected entry; is it the right op? */
831                                 visible = (clist->oid == oprid);
832                                 break;
833                         }
834                 }
835         }
836
837         ReleaseSysCache(oprtup);
838
839         return visible;
840 }
841
842
843 /*
844  * OpclassGetCandidates
845  *              Given an index access method OID, retrieve a list of all the
846  *              opclasses for that AM that are visible in the search path.
847  *
848  * NOTE: the opcname_tmp field in the returned structs should not be used
849  * by callers, because it points at syscache entries that we release at
850  * the end of this routine.  If any callers needed the name information,
851  * we could pstrdup() the names ... but at present it'd be wasteful.
852  */
853 OpclassCandidateList
854 OpclassGetCandidates(Oid amid)
855 {
856         OpclassCandidateList resultList = NULL;
857         CatCList   *catlist;
858         int                     i;
859
860         /* Search syscache by AM OID only */
861         catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
862                                                                  ObjectIdGetDatum(amid),
863                                                                  0, 0, 0);
864
865         recomputeNamespacePath();
866
867         for (i = 0; i < catlist->n_members; i++)
868         {
869                 HeapTuple       opctup = &catlist->members[i]->tuple;
870                 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
871                 int                     pathpos = 0;
872                 OpclassCandidateList newResult;
873                 List       *nsp;
874
875                 /* Consider only opclasses that are in the search path */
876                 foreach(nsp, namespaceSearchPath)
877                 {
878                         if (opcform->opcnamespace == (Oid) lfirsti(nsp))
879                                 break;
880                         pathpos++;
881                 }
882                 if (nsp == NIL)
883                         continue;                       /* opclass is not in search path */
884
885                 /*
886                  * Okay, it's in the search path, but does it have the same name
887                  * as something we already accepted?  If so, keep only the one
888                  * that appears earlier in the search path.
889                  *
890                  * If we have an ordered list from SearchSysCacheList (the normal
891                  * case), then any conflicting opclass must immediately adjoin
892                  * this one in the list, so we only need to look at the newest
893                  * result item.  If we have an unordered list, we have to scan the
894                  * whole result list.
895                  */
896                 if (resultList)
897                 {
898                         OpclassCandidateList prevResult;
899
900                         if (catlist->ordered)
901                         {
902                                 if (strcmp(NameStr(opcform->opcname),
903                                                    resultList->opcname_tmp) == 0)
904                                         prevResult = resultList;
905                                 else
906                                         prevResult = NULL;
907                         }
908                         else
909                         {
910                                 for (prevResult = resultList;
911                                          prevResult;
912                                          prevResult = prevResult->next)
913                                 {
914                                         if (strcmp(NameStr(opcform->opcname),
915                                                            prevResult->opcname_tmp) == 0)
916                                                 break;
917                                 }
918                         }
919                         if (prevResult)
920                         {
921                                 /* We have a match with a previous result */
922                                 Assert(pathpos != prevResult->pathpos);
923                                 if (pathpos > prevResult->pathpos)
924                                         continue;       /* keep previous result */
925                                 /* replace previous result */
926                                 prevResult->opcname_tmp = NameStr(opcform->opcname);
927                                 prevResult->pathpos = pathpos;
928                                 prevResult->oid = HeapTupleGetOid(opctup);
929                                 prevResult->opcintype = opcform->opcintype;
930                                 prevResult->opcdefault = opcform->opcdefault;
931                                 prevResult->opckeytype = opcform->opckeytype;
932                                 continue;
933                         }
934                 }
935
936                 /*
937                  * Okay to add it to result list
938                  */
939                 newResult = (OpclassCandidateList)
940                         palloc(sizeof(struct _OpclassCandidateList));
941                 newResult->opcname_tmp = NameStr(opcform->opcname);
942                 newResult->pathpos = pathpos;
943                 newResult->oid = HeapTupleGetOid(opctup);
944                 newResult->opcintype = opcform->opcintype;
945                 newResult->opcdefault = opcform->opcdefault;
946                 newResult->opckeytype = opcform->opckeytype;
947                 newResult->next = resultList;
948                 resultList = newResult;
949         }
950
951         ReleaseSysCacheList(catlist);
952
953         return resultList;
954 }
955
956 /*
957  * OpclassnameGetOpcid
958  *              Try to resolve an unqualified index opclass name.
959  *              Returns OID if opclass found in search path, else InvalidOid.
960  *
961  * This is essentially the same as TypenameGetTypid, but we have to have
962  * an extra argument for the index AM OID.
963  */
964 Oid
965 OpclassnameGetOpcid(Oid amid, const char *opcname)
966 {
967         Oid                     opcid;
968         List       *lptr;
969
970         recomputeNamespacePath();
971
972         foreach(lptr, namespaceSearchPath)
973         {
974                 Oid                     namespaceId = (Oid) lfirsti(lptr);
975
976                 opcid = GetSysCacheOid(CLAAMNAMENSP,
977                                                            ObjectIdGetDatum(amid),
978                                                            PointerGetDatum(opcname),
979                                                            ObjectIdGetDatum(namespaceId),
980                                                            0);
981                 if (OidIsValid(opcid))
982                         return opcid;
983         }
984
985         /* Not found in path */
986         return InvalidOid;
987 }
988
989 /*
990  * OpclassIsVisible
991  *              Determine whether an opclass (identified by OID) is visible in the
992  *              current search path.  Visible means "would be found by searching
993  *              for the unqualified opclass name".
994  */
995 bool
996 OpclassIsVisible(Oid opcid)
997 {
998         HeapTuple       opctup;
999         Form_pg_opclass opcform;
1000         Oid                     opcnamespace;
1001         bool            visible;
1002
1003         opctup = SearchSysCache(CLAOID,
1004                                                         ObjectIdGetDatum(opcid),
1005                                                         0, 0, 0);
1006         if (!HeapTupleIsValid(opctup))
1007                 elog(ERROR, "Cache lookup failed for opclass %u", opcid);
1008         opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1009
1010         recomputeNamespacePath();
1011
1012         /*
1013          * Quick check: if it ain't in the path at all, it ain't visible.
1014          * Items in the system namespace are surely in the path and so we
1015          * needn't even do intMember() for them.
1016          */
1017         opcnamespace = opcform->opcnamespace;
1018         if (opcnamespace != PG_CATALOG_NAMESPACE &&
1019                 !intMember(opcnamespace, namespaceSearchPath))
1020                 visible = false;
1021         else
1022         {
1023                 /*
1024                  * If it is in the path, it might still not be visible; it could
1025                  * be hidden by another opclass of the same name earlier in the
1026                  * path. So we must do a slow check to see if this opclass would
1027                  * be found by OpclassnameGetOpcid.
1028                  */
1029                 char       *opcname = NameStr(opcform->opcname);
1030
1031                 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1032         }
1033
1034         ReleaseSysCache(opctup);
1035
1036         return visible;
1037 }
1038
1039 /*
1040  * ConversionGetConid
1041  *              Try to resolve an unqualified conversion name.
1042  *              Returns OID if conversion found in search path, else InvalidOid.
1043  *
1044  * This is essentially the same as RelnameGetRelid.
1045  */
1046 Oid
1047 ConversionGetConid(const char *conname)
1048 {
1049         Oid             conid;
1050         List       *lptr;
1051
1052         recomputeNamespacePath();
1053
1054         foreach(lptr, namespaceSearchPath)
1055         {
1056                 Oid                     namespaceId = (Oid) lfirsti(lptr);
1057
1058                 conid = GetSysCacheOid(CONNAMENSP,
1059                                                            PointerGetDatum(conname),
1060                                                            ObjectIdGetDatum(namespaceId),
1061                                                            0, 0);
1062                 if (OidIsValid(conid))
1063                         return conid;
1064         }
1065
1066         /* Not found in path */
1067         return InvalidOid;
1068 }
1069
1070 /*
1071  * ConversionIsVisible
1072  *              Determine whether a conversion (identified by OID) is visible in the
1073  *              current search path.  Visible means "would be found by searching
1074  *              for the unqualified conversion name".
1075  */
1076 bool
1077 ConversionIsVisible(Oid conid)
1078 {
1079         HeapTuple       contup;
1080         Form_pg_conversion conform;
1081         Oid                     connamespace;
1082         bool            visible;
1083
1084         contup = SearchSysCache(CONOID,
1085                                                         ObjectIdGetDatum(conid),
1086                                                         0, 0, 0);
1087         if (!HeapTupleIsValid(contup))
1088                 elog(ERROR, "Cache lookup failed for conversion %u", conid);
1089         conform = (Form_pg_conversion) GETSTRUCT(contup);
1090
1091         recomputeNamespacePath();
1092
1093         /*
1094          * Quick check: if it ain't in the path at all, it ain't visible.
1095          * Items in the system namespace are surely in the path and so we
1096          * needn't even do intMember() for them.
1097          */
1098         connamespace = conform->connamespace;
1099         if (connamespace != PG_CATALOG_NAMESPACE &&
1100                 !intMember(connamespace, namespaceSearchPath))
1101                 visible = false;
1102         else
1103         {
1104                 /*
1105                  * If it is in the path, it might still not be visible; it could
1106                  * be hidden by another conversion of the same name earlier in the
1107                  * path. So we must do a slow check to see if this conversion would
1108                  * be found by ConversionGetConid.
1109                  */
1110                 char       *conname = NameStr(conform->conname);
1111                 
1112                 visible = (ConversionGetConid(conname) == conid);
1113         }
1114
1115         ReleaseSysCache(contup);
1116
1117         return visible;
1118 }
1119
1120 /*
1121  * DeconstructQualifiedName
1122  *              Given a possibly-qualified name expressed as a list of String nodes,
1123  *              extract the schema name and object name.
1124  *
1125  * *nspname_p is set to NULL if there is no explicit schema name.
1126  */
1127 void
1128 DeconstructQualifiedName(List *names,
1129                                                  char **nspname_p,
1130                                                  char **objname_p)
1131 {
1132         char       *catalogname;
1133         char       *schemaname = NULL;
1134         char       *objname = NULL;
1135
1136         switch (length(names))
1137         {
1138                 case 1:
1139                         objname = strVal(lfirst(names));
1140                         break;
1141                 case 2:
1142                         schemaname = strVal(lfirst(names));
1143                         objname = strVal(lsecond(names));
1144                         break;
1145                 case 3:
1146                         catalogname = strVal(lfirst(names));
1147                         schemaname = strVal(lsecond(names));
1148                         objname = strVal(lfirst(lnext(lnext(names))));
1149
1150                         /*
1151                          * We check the catalog name and then ignore it.
1152                          */
1153                         if (strcmp(catalogname, DatabaseName) != 0)
1154                                 elog(ERROR, "Cross-database references are not implemented");
1155                         break;
1156                 default:
1157                         elog(ERROR, "Improper qualified name (too many dotted names): %s",
1158                                  NameListToString(names));
1159                         break;
1160         }
1161
1162         *nspname_p = schemaname;
1163         *objname_p = objname;
1164 }
1165
1166 /*
1167  * LookupExplicitNamespace
1168  *              Process an explicitly-specified schema name: look up the schema
1169  *              and verify we have USAGE (lookup) rights in it.
1170  *
1171  * Returns the namespace OID.  Raises elog if any problem.
1172  */
1173 Oid
1174 LookupExplicitNamespace(const char *nspname)
1175 {
1176         Oid                     namespaceId;
1177         AclResult       aclresult;
1178
1179         namespaceId = GetSysCacheOid(NAMESPACENAME,
1180                                                                  CStringGetDatum(nspname),
1181                                                                  0, 0, 0);
1182         if (!OidIsValid(namespaceId))
1183                 elog(ERROR, "Namespace \"%s\" does not exist", nspname);
1184
1185         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1186         if (aclresult != ACLCHECK_OK)
1187                 aclcheck_error(aclresult, nspname);
1188
1189         return namespaceId;
1190 }
1191
1192 /*
1193  * QualifiedNameGetCreationNamespace
1194  *              Given a possibly-qualified name for an object (in List-of-Values
1195  *              format), determine what namespace the object should be created in.
1196  *              Also extract and return the object name (last component of list).
1197  *
1198  * This is *not* used for tables.  Hence, the TEMP table namespace is
1199  * never selected as the creation target.
1200  */
1201 Oid
1202 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1203 {
1204         char       *schemaname;
1205         char       *objname;
1206         Oid                     namespaceId;
1207
1208         /* deconstruct the name list */
1209         DeconstructQualifiedName(names, &schemaname, &objname);
1210
1211         if (schemaname)
1212         {
1213                 /* use exact schema given */
1214                 namespaceId = GetSysCacheOid(NAMESPACENAME,
1215                                                                          CStringGetDatum(schemaname),
1216                                                                          0, 0, 0);
1217                 if (!OidIsValid(namespaceId))
1218                         elog(ERROR, "Namespace \"%s\" does not exist",
1219                                  schemaname);
1220                 /* we do not check for USAGE rights here! */
1221         }
1222         else
1223         {
1224                 /* use the default creation namespace */
1225                 recomputeNamespacePath();
1226                 namespaceId = defaultCreationNamespace;
1227                 if (!OidIsValid(namespaceId))
1228                         elog(ERROR, "No namespace has been selected to create in");
1229         }
1230
1231         /* Note: callers will check for CREATE rights when appropriate */
1232
1233         *objname_p = objname;
1234         return namespaceId;
1235 }
1236
1237 /*
1238  * makeRangeVarFromNameList
1239  *              Utility routine to convert a qualified-name list into RangeVar form.
1240  */
1241 RangeVar *
1242 makeRangeVarFromNameList(List *names)
1243 {
1244         RangeVar   *rel = makeRangeVar(NULL, NULL);
1245
1246         switch (length(names))
1247         {
1248                 case 1:
1249                         rel->relname = strVal(lfirst(names));
1250                         break;
1251                 case 2:
1252                         rel->schemaname = strVal(lfirst(names));
1253                         rel->relname = strVal(lsecond(names));
1254                         break;
1255                 case 3:
1256                         rel->catalogname = strVal(lfirst(names));
1257                         rel->schemaname = strVal(lsecond(names));
1258                         rel->relname = strVal(lfirst(lnext(lnext(names))));
1259                         break;
1260                 default:
1261                         elog(ERROR, "Improper relation name (too many dotted names)");
1262                         break;
1263         }
1264
1265         return rel;
1266 }
1267
1268 /*
1269  * NameListToString
1270  *              Utility routine to convert a qualified-name list into a string.
1271  *
1272  * This is used primarily to form error messages, and so we do not quote
1273  * the list elements, for the sake of legibility.
1274  */
1275 char *
1276 NameListToString(List *names)
1277 {
1278         StringInfoData string;
1279         List       *l;
1280
1281         initStringInfo(&string);
1282
1283         foreach(l, names)
1284         {
1285                 if (l != names)
1286                         appendStringInfoChar(&string, '.');
1287                 appendStringInfo(&string, "%s", strVal(lfirst(l)));
1288         }
1289
1290         return string.data;
1291 }
1292
1293 /*
1294  * NameListToQuotedString
1295  *              Utility routine to convert a qualified-name list into a string.
1296  *
1297  * Same as above except that names will be double-quoted where necessary,
1298  * so the string could be re-parsed (eg, by textToQualifiedNameList).
1299  */
1300 char *
1301 NameListToQuotedString(List *names)
1302 {
1303         StringInfoData string;
1304         List       *l;
1305
1306         initStringInfo(&string);
1307
1308         foreach(l, names)
1309         {
1310                 if (l != names)
1311                         appendStringInfoChar(&string, '.');
1312                 appendStringInfo(&string, "%s", quote_identifier(strVal(lfirst(l))));
1313         }
1314
1315         return string.data;
1316 }
1317
1318 /*
1319  * isTempNamespace - is the given namespace my temporary-table namespace?
1320  */
1321 bool
1322 isTempNamespace(Oid namespaceId)
1323 {
1324         if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1325                 return true;
1326         return false;
1327 }
1328
1329 /*
1330  * isOtherTempNamespace - is the given namespace some other backend's
1331  * temporary-table namespace?
1332  */
1333 bool
1334 isOtherTempNamespace(Oid namespaceId)
1335 {
1336         bool            result;
1337         char       *nspname;
1338
1339         /* If it's my own temp namespace, say "false" */
1340         if (isTempNamespace(namespaceId))
1341                 return false;
1342         /* Else, if the namespace name starts with "pg_temp_", say "true" */
1343         nspname = get_namespace_name(namespaceId);
1344         if (!nspname)
1345                 return false;                   /* no such namespace? */
1346         result = (strncmp(nspname, "pg_temp_", 8) == 0);
1347         pfree(nspname);
1348         return result;
1349 }
1350
1351 /*
1352  * PushSpecialNamespace - push a "special" namespace onto the front of the
1353  * search path.
1354  *
1355  * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1356  * Although the API is defined to allow a stack of pushed namespaces, we
1357  * presently only support one at a time.
1358  *
1359  * The pushed namespace will be removed from the search path at end of
1360  * transaction, whether commit or abort.
1361  */
1362 void
1363 PushSpecialNamespace(Oid namespaceId)
1364 {
1365         Assert(!OidIsValid(mySpecialNamespace));
1366         mySpecialNamespace = namespaceId;
1367         namespaceSearchPathValid = false;
1368 }
1369
1370 /*
1371  * PopSpecialNamespace - remove previously pushed special namespace.
1372  */
1373 void
1374 PopSpecialNamespace(Oid namespaceId)
1375 {
1376         Assert(mySpecialNamespace == namespaceId);
1377         mySpecialNamespace = InvalidOid;
1378         namespaceSearchPathValid = false;
1379 }
1380
1381 /*
1382  * FindConversionByName - find a conversion by possibly qualified name
1383  */
1384 Oid
1385 FindConversionByName(List *name)
1386 {
1387         char       *schemaname;
1388         char       *conversion_name;
1389         Oid                     namespaceId;
1390         Oid                     conoid;
1391         List       *lptr;
1392
1393         /* deconstruct the name list */
1394         DeconstructQualifiedName(name, &schemaname, &conversion_name);
1395
1396         if (schemaname)
1397         {
1398                 /* use exact schema given */
1399                 namespaceId = LookupExplicitNamespace(schemaname);
1400                 return FindConversion(conversion_name, namespaceId);
1401         }
1402         else
1403         {
1404                 /* search for it in search path */
1405                 recomputeNamespacePath();
1406
1407                 foreach(lptr, namespaceSearchPath)
1408                 {
1409                         namespaceId = (Oid) lfirsti(lptr);
1410                         conoid = FindConversion(conversion_name, namespaceId);
1411                         if (OidIsValid(conoid))
1412                                 return conoid;
1413                 }
1414         }
1415
1416         /* Not found in path */
1417         return InvalidOid;
1418 }
1419
1420 /*
1421  * FindDefaultConversionProc - find default encoding conversion proc
1422  */
1423 Oid
1424 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1425 {
1426         Oid                     proc;
1427         List       *lptr;
1428
1429         recomputeNamespacePath();
1430
1431         foreach(lptr, namespaceSearchPath)
1432         {
1433                 Oid                     namespaceId = (Oid) lfirsti(lptr);
1434
1435                 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1436                 if (OidIsValid(proc))
1437                         return proc;
1438         }
1439
1440         /* Not found in path */
1441         return InvalidOid;
1442 }
1443
1444 /*
1445  * recomputeNamespacePath - recompute path derived variables if needed.
1446  */
1447 static void
1448 recomputeNamespacePath(void)
1449 {
1450         AclId           userId = GetUserId();
1451         char       *rawname;
1452         List       *namelist;
1453         List       *oidlist;
1454         List       *newpath;
1455         List       *l;
1456         Oid                     firstNS;
1457         MemoryContext oldcxt;
1458
1459         /*
1460          * Do nothing if path is already valid.
1461          */
1462         if (namespaceSearchPathValid && namespaceUser == userId)
1463                 return;
1464
1465         /* Need a modifiable copy of namespace_search_path string */
1466         rawname = pstrdup(namespace_search_path);
1467
1468         /* Parse string into list of identifiers */
1469         if (!SplitIdentifierString(rawname, ',', &namelist))
1470         {
1471                 /* syntax error in name list */
1472                 /* this should not happen if GUC checked check_search_path */
1473                 elog(ERROR, "recomputeNamespacePath: invalid list syntax");
1474         }
1475
1476         /*
1477          * Convert the list of names to a list of OIDs.  If any names are not
1478          * recognizable or we don't have read access, just leave them out of
1479          * the list.  (We can't raise an error, since the search_path setting
1480          * has already been accepted.)  Don't make duplicate entries, either.
1481          */
1482         oidlist = NIL;
1483         foreach(l, namelist)
1484         {
1485                 char       *curname = (char *) lfirst(l);
1486                 Oid                     namespaceId;
1487
1488                 if (strcmp(curname, "$user") == 0)
1489                 {
1490                         /* $user --- substitute namespace matching user name, if any */
1491                         HeapTuple       tuple;
1492
1493                         tuple = SearchSysCache(SHADOWSYSID,
1494                                                                    ObjectIdGetDatum(userId),
1495                                                                    0, 0, 0);
1496                         if (HeapTupleIsValid(tuple))
1497                         {
1498                                 char       *uname;
1499
1500                                 uname = NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename);
1501                                 namespaceId = GetSysCacheOid(NAMESPACENAME,
1502                                                                                          CStringGetDatum(uname),
1503                                                                                          0, 0, 0);
1504                                 ReleaseSysCache(tuple);
1505                                 if (OidIsValid(namespaceId) &&
1506                                         !intMember(namespaceId, oidlist) &&
1507                                         pg_namespace_aclcheck(namespaceId, userId,
1508                                                                                   ACL_USAGE) == ACLCHECK_OK)
1509                                         oidlist = lappendi(oidlist, namespaceId);
1510                         }
1511                 }
1512                 else
1513                 {
1514                         /* normal namespace reference */
1515                         namespaceId = GetSysCacheOid(NAMESPACENAME,
1516                                                                                  CStringGetDatum(curname),
1517                                                                                  0, 0, 0);
1518                         if (OidIsValid(namespaceId) &&
1519                                 !intMember(namespaceId, oidlist) &&
1520                                 pg_namespace_aclcheck(namespaceId, userId,
1521                                                                           ACL_USAGE) == ACLCHECK_OK)
1522                                 oidlist = lappendi(oidlist, namespaceId);
1523                 }
1524         }
1525
1526         /*
1527          * Remember the first member of the explicit list.
1528          */
1529         if (oidlist == NIL)
1530                 firstNS = InvalidOid;
1531         else
1532                 firstNS = (Oid) lfirsti(oidlist);
1533
1534         /*
1535          * Add any implicitly-searched namespaces to the list.  Note these go
1536          * on the front, not the back; also notice that we do not check USAGE
1537          * permissions for these.
1538          */
1539         if (!intMember(PG_CATALOG_NAMESPACE, oidlist))
1540                 oidlist = lconsi(PG_CATALOG_NAMESPACE, oidlist);
1541
1542         if (OidIsValid(myTempNamespace) &&
1543                 !intMember(myTempNamespace, oidlist))
1544                 oidlist = lconsi(myTempNamespace, oidlist);
1545
1546         if (OidIsValid(mySpecialNamespace) &&
1547                 !intMember(mySpecialNamespace, oidlist))
1548                 oidlist = lconsi(mySpecialNamespace, oidlist);
1549
1550         /*
1551          * Now that we've successfully built the new list of namespace OIDs,
1552          * save it in permanent storage.
1553          */
1554         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1555         newpath = listCopy(oidlist);
1556         MemoryContextSwitchTo(oldcxt);
1557
1558         /* Now safe to assign to state variable. */
1559         freeList(namespaceSearchPath);
1560         namespaceSearchPath = newpath;
1561
1562         /*
1563          * Update info derived from search path.
1564          */
1565         firstExplicitNamespace = firstNS;
1566         if (OidIsValid(mySpecialNamespace))
1567                 defaultCreationNamespace = mySpecialNamespace;
1568         else
1569                 defaultCreationNamespace = firstNS;
1570
1571         /* Mark the path valid. */
1572         namespaceSearchPathValid = true;
1573         namespaceUser = userId;
1574
1575         /* Clean up. */
1576         pfree(rawname);
1577         freeList(namelist);
1578         freeList(oidlist);
1579 }
1580
1581 /*
1582  * InitTempTableNamespace
1583  *              Initialize temp table namespace on first use in a particular backend
1584  */
1585 static void
1586 InitTempTableNamespace(void)
1587 {
1588         char            namespaceName[NAMEDATALEN];
1589         Oid                     namespaceId;
1590
1591         /*
1592          * First, do permission check to see if we are authorized to make temp
1593          * tables.      We use a nonstandard error message here since
1594          * "databasename: permission denied" might be a tad cryptic.
1595          *
1596          * Note we apply the check to the session user, not the currently active
1597          * userid, since we are not going to change our minds about temp table
1598          * availability during the session.
1599          */
1600         if (pg_database_aclcheck(MyDatabaseId, GetSessionUserId(),
1601                                                          ACL_CREATE_TEMP) != ACLCHECK_OK)
1602                 elog(ERROR, "%s: not authorized to create temp tables",
1603                          DatabaseName);
1604
1605         snprintf(namespaceName, NAMEDATALEN, "pg_temp_%d", MyBackendId);
1606
1607         namespaceId = GetSysCacheOid(NAMESPACENAME,
1608                                                                  CStringGetDatum(namespaceName),
1609                                                                  0, 0, 0);
1610         if (!OidIsValid(namespaceId))
1611         {
1612                 /*
1613                  * First use of this temp namespace in this database; create it.
1614                  * The temp namespaces are always owned by the superuser.  We
1615                  * leave their permissions at default --- i.e., no access except
1616                  * to superuser --- to ensure that unprivileged users can't peek
1617                  * at other backends' temp tables.  This works because the places
1618                  * that access the temp namespace for my own backend skip
1619                  * permissions checks on it.
1620                  */
1621                 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_USESYSID);
1622                 /* Advance command counter to make namespace visible */
1623                 CommandCounterIncrement();
1624         }
1625         else
1626         {
1627                 /*
1628                  * If the namespace already exists, clean it out (in case the
1629                  * former owner crashed without doing so).
1630                  */
1631                 RemoveTempRelations(namespaceId);
1632         }
1633
1634         /*
1635          * Okay, we've prepared the temp namespace ... but it's not committed
1636          * yet, so all our work could be undone by transaction rollback.  Set
1637          * flag for AtEOXact_Namespace to know what to do.
1638          */
1639         myTempNamespace = namespaceId;
1640
1641         firstTempTransaction = true;
1642
1643         namespaceSearchPathValid = false;       /* need to rebuild list */
1644 }
1645
1646 /*
1647  * End-of-transaction cleanup for namespaces.
1648  */
1649 void
1650 AtEOXact_Namespace(bool isCommit)
1651 {
1652         /*
1653          * If we abort the transaction in which a temp namespace was selected,
1654          * we'll have to do any creation or cleanout work over again.  So,
1655          * just forget the namespace entirely until next time.  On the other
1656          * hand, if we commit then register an exit callback to clean out the
1657          * temp tables at backend shutdown.  (We only want to register the
1658          * callback once per session, so this is a good place to do it.)
1659          */
1660         if (firstTempTransaction)
1661         {
1662                 if (isCommit)
1663                         on_shmem_exit(RemoveTempRelationsCallback, 0);
1664                 else
1665                 {
1666                         myTempNamespace = InvalidOid;
1667                         namespaceSearchPathValid = false;       /* need to rebuild list */
1668                 }
1669                 firstTempTransaction = false;
1670         }
1671
1672         /*
1673          * Clean up if someone failed to do PopSpecialNamespace
1674          */
1675         if (OidIsValid(mySpecialNamespace))
1676         {
1677                 mySpecialNamespace = InvalidOid;
1678                 namespaceSearchPathValid = false;               /* need to rebuild list */
1679         }
1680 }
1681
1682 /*
1683  * Remove all relations in the specified temp namespace.
1684  *
1685  * This is called at backend shutdown (if we made any temp relations).
1686  * It is also called when we begin using a pre-existing temp namespace,
1687  * in order to clean out any relations that might have been created by
1688  * a crashed backend.
1689  */
1690 static void
1691 RemoveTempRelations(Oid tempNamespaceId)
1692 {
1693         Relation        pgclass;
1694         HeapScanDesc scan;
1695         HeapTuple       tuple;
1696         ScanKeyData key;
1697         ObjectAddress object;
1698
1699         /*
1700          * Scan pg_class to find all the relations in the target namespace.
1701          * Ignore indexes, though, on the assumption that they'll go away when
1702          * their tables are deleted.
1703          *
1704          * NOTE: if there are deletion constraints between temp relations, then
1705          * our CASCADE delete call may cause as-yet-unvisited objects to go
1706          * away.  This is okay because we are using SnapshotNow; when the scan
1707          * does reach those pg_class tuples, they'll be ignored as already
1708          * deleted.
1709          */
1710         ScanKeyEntryInitialize(&key, 0x0,
1711                                                    Anum_pg_class_relnamespace,
1712                                                    F_OIDEQ,
1713                                                    ObjectIdGetDatum(tempNamespaceId));
1714
1715         pgclass = heap_openr(RelationRelationName, AccessShareLock);
1716         scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
1717
1718         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1719         {
1720                 switch (((Form_pg_class) GETSTRUCT(tuple))->relkind)
1721                 {
1722                         case RELKIND_RELATION:
1723                         case RELKIND_SEQUENCE:
1724                         case RELKIND_VIEW:
1725                                 object.classId = RelOid_pg_class;
1726                                 object.objectId = HeapTupleGetOid(tuple);
1727                                 object.objectSubId = 0;
1728                                 performDeletion(&object, DROP_CASCADE);
1729                                 break;
1730                         default:
1731                                 break;
1732                 }
1733         }
1734
1735         heap_endscan(scan);
1736         heap_close(pgclass, AccessShareLock);
1737 }
1738
1739 /*
1740  * Callback to remove temp relations at backend exit.
1741  */
1742 static void
1743 RemoveTempRelationsCallback(void)
1744 {
1745         if (OidIsValid(myTempNamespace))        /* should always be true */
1746         {
1747                 /* Need to ensure we have a usable transaction. */
1748                 AbortOutOfAnyTransaction();
1749                 StartTransactionCommand(true);
1750
1751                 RemoveTempRelations(myTempNamespace);
1752
1753                 CommitTransactionCommand(true);
1754         }
1755 }
1756
1757
1758 /*
1759  * Routines for handling the GUC variable 'search_path'.
1760  */
1761
1762 /* assign_hook: validate new search_path, do extra actions as needed */
1763 const char *
1764 assign_search_path(const char *newval, bool doit, bool interactive)
1765 {
1766         char       *rawname;
1767         List       *namelist;
1768         List       *l;
1769
1770         /* Need a modifiable copy of string */
1771         rawname = pstrdup(newval);
1772
1773         /* Parse string into list of identifiers */
1774         if (!SplitIdentifierString(rawname, ',', &namelist))
1775         {
1776                 /* syntax error in name list */
1777                 pfree(rawname);
1778                 freeList(namelist);
1779                 return NULL;
1780         }
1781
1782         /*
1783          * If we aren't inside a transaction, we cannot do database access so
1784          * cannot verify the individual names.  Must accept the list on faith.
1785          */
1786         if (interactive && IsTransactionState())
1787         {
1788                 /*
1789                  * Verify that all the names are either valid namespace names or
1790                  * "$user".  We do not require $user to correspond to a valid
1791                  * namespace.  We do not check for USAGE rights, either; should
1792                  * we?
1793                  */
1794                 foreach(l, namelist)
1795                 {
1796                         char       *curname = (char *) lfirst(l);
1797
1798                         if (strcmp(curname, "$user") == 0)
1799                                 continue;
1800                         if (!SearchSysCacheExists(NAMESPACENAME,
1801                                                                           CStringGetDatum(curname),
1802                                                                           0, 0, 0))
1803                                 elog(ERROR, "Namespace \"%s\" does not exist", curname);
1804                 }
1805         }
1806
1807         pfree(rawname);
1808         freeList(namelist);
1809
1810         /*
1811          * We mark the path as needing recomputation, but don't do anything
1812          * until it's needed.  This avoids trying to do database access during
1813          * GUC initialization.
1814          */
1815         if (doit)
1816                 namespaceSearchPathValid = false;
1817
1818         return newval;
1819 }
1820
1821 /*
1822  * InitializeSearchPath: initialize module during InitPostgres.
1823  *
1824  * This is called after we are up enough to be able to do catalog lookups.
1825  */
1826 void
1827 InitializeSearchPath(void)
1828 {
1829         if (IsBootstrapProcessingMode())
1830         {
1831                 /*
1832                  * In bootstrap mode, the search path must be 'pg_catalog' so that
1833                  * tables are created in the proper namespace; ignore the GUC
1834                  * setting.
1835                  */
1836                 MemoryContext oldcxt;
1837
1838                 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1839                 namespaceSearchPath = makeListi1(PG_CATALOG_NAMESPACE);
1840                 MemoryContextSwitchTo(oldcxt);
1841                 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1842                 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1843                 namespaceSearchPathValid = true;
1844                 namespaceUser = GetUserId();
1845         }
1846         else
1847         {
1848                 /*
1849                  * In normal mode, arrange for a callback on any syscache
1850                  * invalidation of pg_namespace rows.
1851                  */
1852                 CacheRegisterSyscacheCallback(NAMESPACEOID,
1853                                                                           NamespaceCallback,
1854                                                                           (Datum) 0);
1855                 /* Force search path to be recomputed on next use */
1856                 namespaceSearchPathValid = false;
1857         }
1858 }
1859
1860 /*
1861  * NamespaceCallback
1862  *              Syscache inval callback function
1863  */
1864 static void
1865 NamespaceCallback(Datum arg, Oid relid)
1866 {
1867         /* Force search path to be recomputed on next use */
1868         namespaceSearchPathValid = false;
1869 }
1870
1871 /*
1872  * Fetch the active search path, expressed as a List of OIDs.
1873  *
1874  * The returned list includes the implicitly-prepended namespaces only if
1875  * includeImplicit is true.
1876  *
1877  * NB: caller must treat the list as read-only!
1878  */
1879 List *
1880 fetch_search_path(bool includeImplicit)
1881 {
1882         List       *result;
1883
1884         recomputeNamespacePath();
1885
1886         result = namespaceSearchPath;
1887         if (!includeImplicit)
1888         {
1889                 while (result && (Oid) lfirsti(result) != firstExplicitNamespace)
1890                         result = lnext(result);
1891         }
1892
1893         return result;
1894 }
1895
1896 /*
1897  * Export the FooIsVisible functions as SQL-callable functions.
1898  */
1899
1900 Datum
1901 pg_table_is_visible(PG_FUNCTION_ARGS)
1902 {
1903         Oid                     oid = PG_GETARG_OID(0);
1904
1905         PG_RETURN_BOOL(RelationIsVisible(oid));
1906 }
1907
1908 Datum
1909 pg_type_is_visible(PG_FUNCTION_ARGS)
1910 {
1911         Oid                     oid = PG_GETARG_OID(0);
1912
1913         PG_RETURN_BOOL(TypeIsVisible(oid));
1914 }
1915
1916 Datum
1917 pg_function_is_visible(PG_FUNCTION_ARGS)
1918 {
1919         Oid                     oid = PG_GETARG_OID(0);
1920
1921         PG_RETURN_BOOL(FunctionIsVisible(oid));
1922 }
1923
1924 Datum
1925 pg_operator_is_visible(PG_FUNCTION_ARGS)
1926 {
1927         Oid                     oid = PG_GETARG_OID(0);
1928
1929         PG_RETURN_BOOL(OperatorIsVisible(oid));
1930 }
1931
1932 Datum
1933 pg_opclass_is_visible(PG_FUNCTION_ARGS)
1934 {
1935         Oid                     oid = PG_GETARG_OID(0);
1936
1937         PG_RETURN_BOOL(OpclassIsVisible(oid));
1938 }
1939
1940 Datum
1941 pg_conversion_is_visible(PG_FUNCTION_ARGS)
1942 {
1943         Oid                     oid = PG_GETARG_OID(0);
1944
1945         PG_RETURN_BOOL(ConversionIsVisible(oid));
1946 }