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