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