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