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