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