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