OSDN Git Service

Re-run pgindent, fixing a problem where comment lines after a blank
[pg-rex/syncrep.git] / 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.80 2005/11/22 18:17:08 momjian 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. Items in
326          * the system namespace are surely in the path and so we needn't even do
327          * 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 be
337                  * hidden by another relation of the same name earlier in the path. So
338                  * 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. Items in
424          * the system namespace are surely in the path and so we needn't even do
425          * 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 be
435                  * hidden by another type of the same name earlier in the path. So we
436                  * 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 only
549                          * 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 this
553                          * one in the list, so we only need to look at the newest result
554                          * item.  If we have an unordered list, we have to scan the whole
555                          * 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. Items in
644          * the system namespace are surely in the path and so we needn't even do
645          * 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 be
655                  * hidden by another proc of the same name and arguments earlier in
656                  * the path.  So we must do a slow check to see if this is the same
657                  * 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 quite a
737          * few, for common operator names such as '=' or '+'.  To reduce the time
738          * spent in palloc, we allocate the result space as an array large enough
739          * to hold all the operators.  The original coding of this routine did a
740          * separate palloc for each operator, but profiling revealed that the
741          * pallocs used an unreasonably large fraction of parsing time.
742          */
743 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
744
745         if (catlist->n_members > 0)
746                 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
747
748         for (i = 0; i < catlist->n_members; i++)
749         {
750                 HeapTuple       opertup = &catlist->members[i]->tuple;
751                 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
752                 int                     pathpos = 0;
753                 FuncCandidateList newResult;
754
755                 /* Ignore operators of wrong kind, if specific kind requested */
756                 if (oprkind && operform->oprkind != oprkind)
757                         continue;
758
759                 if (OidIsValid(namespaceId))
760                 {
761                         /* Consider only opers in specified namespace */
762                         if (operform->oprnamespace != namespaceId)
763                                 continue;
764                         /* No need to check args, they must all be different */
765                 }
766                 else
767                 {
768                         /* Consider only opers that are in the search path */
769                         ListCell   *nsp;
770
771                         foreach(nsp, namespaceSearchPath)
772                         {
773                                 if (operform->oprnamespace == lfirst_oid(nsp))
774                                         break;
775                                 pathpos++;
776                         }
777                         if (nsp == NULL)
778                                 continue;               /* oper is not in search path */
779
780                         /*
781                          * Okay, it's in the search path, but does it have the same
782                          * arguments as something we already accepted?  If so, keep only
783                          * the one that appears earlier in the search path.
784                          *
785                          * If we have an ordered list from SearchSysCacheList (the normal
786                          * case), then any conflicting oper must immediately adjoin this
787                          * one in the list, so we only need to look at the newest result
788                          * item.  If we have an unordered list, we have to scan the whole
789                          * result list.
790                          */
791                         if (resultList)
792                         {
793                                 FuncCandidateList prevResult;
794
795                                 if (catlist->ordered)
796                                 {
797                                         if (operform->oprleft == resultList->args[0] &&
798                                                 operform->oprright == resultList->args[1])
799                                                 prevResult = resultList;
800                                         else
801                                                 prevResult = NULL;
802                                 }
803                                 else
804                                 {
805                                         for (prevResult = resultList;
806                                                  prevResult;
807                                                  prevResult = prevResult->next)
808                                         {
809                                                 if (operform->oprleft == prevResult->args[0] &&
810                                                         operform->oprright == prevResult->args[1])
811                                                         break;
812                                         }
813                                 }
814                                 if (prevResult)
815                                 {
816                                         /* We have a match with a previous result */
817                                         Assert(pathpos != prevResult->pathpos);
818                                         if (pathpos > prevResult->pathpos)
819                                                 continue;               /* keep previous result */
820                                         /* replace previous result */
821                                         prevResult->pathpos = pathpos;
822                                         prevResult->oid = HeapTupleGetOid(opertup);
823                                         continue;       /* args are same, of course */
824                                 }
825                         }
826                 }
827
828                 /*
829                  * Okay to add it to result list
830                  */
831                 newResult = (FuncCandidateList) (resultSpace + nextResult);
832                 nextResult += SPACE_PER_OP;
833
834                 newResult->pathpos = pathpos;
835                 newResult->oid = HeapTupleGetOid(opertup);
836                 newResult->nargs = 2;
837                 newResult->args[0] = operform->oprleft;
838                 newResult->args[1] = operform->oprright;
839                 newResult->next = resultList;
840                 resultList = newResult;
841         }
842
843         ReleaseSysCacheList(catlist);
844
845         return resultList;
846 }
847
848 /*
849  * OperatorIsVisible
850  *              Determine whether an operator (identified by OID) is visible in the
851  *              current search path.  Visible means "would be found by searching
852  *              for the unqualified operator name with exact argument matches".
853  */
854 bool
855 OperatorIsVisible(Oid oprid)
856 {
857         HeapTuple       oprtup;
858         Form_pg_operator oprform;
859         Oid                     oprnamespace;
860         bool            visible;
861
862         oprtup = SearchSysCache(OPEROID,
863                                                         ObjectIdGetDatum(oprid),
864                                                         0, 0, 0);
865         if (!HeapTupleIsValid(oprtup))
866                 elog(ERROR, "cache lookup failed for operator %u", oprid);
867         oprform = (Form_pg_operator) GETSTRUCT(oprtup);
868
869         recomputeNamespacePath();
870
871         /*
872          * Quick check: if it ain't in the path at all, it ain't visible. Items in
873          * the system namespace are surely in the path and so we needn't even do
874          * list_member_oid() for them.
875          */
876         oprnamespace = oprform->oprnamespace;
877         if (oprnamespace != PG_CATALOG_NAMESPACE &&
878                 !list_member_oid(namespaceSearchPath, oprnamespace))
879                 visible = false;
880         else
881         {
882                 /*
883                  * If it is in the path, it might still not be visible; it could be
884                  * hidden by another operator of the same name and arguments earlier
885                  * in the path.  So we must do a slow check to see if this is the same
886                  * operator that would be found by OpernameGetCandidates.
887                  */
888                 char       *oprname = NameStr(oprform->oprname);
889                 FuncCandidateList clist;
890
891                 visible = false;
892
893                 clist = OpernameGetCandidates(list_make1(makeString(oprname)),
894                                                                           oprform->oprkind);
895
896                 for (; clist; clist = clist->next)
897                 {
898                         if (clist->args[0] == oprform->oprleft &&
899                                 clist->args[1] == oprform->oprright)
900                         {
901                                 /* Found the expected entry; is it the right op? */
902                                 visible = (clist->oid == oprid);
903                                 break;
904                         }
905                 }
906         }
907
908         ReleaseSysCache(oprtup);
909
910         return visible;
911 }
912
913
914 /*
915  * OpclassGetCandidates
916  *              Given an index access method OID, retrieve a list of all the
917  *              opclasses for that AM that are visible in the search path.
918  *
919  * NOTE: the opcname_tmp field in the returned structs should not be used
920  * by callers, because it points at syscache entries that we release at
921  * the end of this routine.  If any callers needed the name information,
922  * we could pstrdup() the names ... but at present it'd be wasteful.
923  */
924 OpclassCandidateList
925 OpclassGetCandidates(Oid amid)
926 {
927         OpclassCandidateList resultList = NULL;
928         CatCList   *catlist;
929         int                     i;
930
931         /* Search syscache by AM OID only */
932         catlist = SearchSysCacheList(CLAAMNAMENSP, 1,
933                                                                  ObjectIdGetDatum(amid),
934                                                                  0, 0, 0);
935
936         recomputeNamespacePath();
937
938         for (i = 0; i < catlist->n_members; i++)
939         {
940                 HeapTuple       opctup = &catlist->members[i]->tuple;
941                 Form_pg_opclass opcform = (Form_pg_opclass) GETSTRUCT(opctup);
942                 int                     pathpos = 0;
943                 OpclassCandidateList newResult;
944                 ListCell   *nsp;
945
946                 /* Consider only opclasses that are in the search path */
947                 foreach(nsp, namespaceSearchPath)
948                 {
949                         if (opcform->opcnamespace == lfirst_oid(nsp))
950                                 break;
951                         pathpos++;
952                 }
953                 if (nsp == NULL)
954                         continue;                       /* opclass is not in search path */
955
956                 /*
957                  * Okay, it's in the search path, but does it have the same name as
958                  * something we already accepted?  If so, keep only the one that
959                  * appears earlier in the search path.
960                  *
961                  * If we have an ordered list from SearchSysCacheList (the normal
962                  * case), then any conflicting opclass must immediately adjoin this
963                  * one in the list, so we only need to look at the newest result item.
964                  * If we have an unordered list, we have to scan the whole result
965                  * list.
966                  */
967                 if (resultList)
968                 {
969                         OpclassCandidateList prevResult;
970
971                         if (catlist->ordered)
972                         {
973                                 if (strcmp(NameStr(opcform->opcname),
974                                                    resultList->opcname_tmp) == 0)
975                                         prevResult = resultList;
976                                 else
977                                         prevResult = NULL;
978                         }
979                         else
980                         {
981                                 for (prevResult = resultList;
982                                          prevResult;
983                                          prevResult = prevResult->next)
984                                 {
985                                         if (strcmp(NameStr(opcform->opcname),
986                                                            prevResult->opcname_tmp) == 0)
987                                                 break;
988                                 }
989                         }
990                         if (prevResult)
991                         {
992                                 /* We have a match with a previous result */
993                                 Assert(pathpos != prevResult->pathpos);
994                                 if (pathpos > prevResult->pathpos)
995                                         continue;       /* keep previous result */
996                                 /* replace previous result */
997                                 prevResult->opcname_tmp = NameStr(opcform->opcname);
998                                 prevResult->pathpos = pathpos;
999                                 prevResult->oid = HeapTupleGetOid(opctup);
1000                                 prevResult->opcintype = opcform->opcintype;
1001                                 prevResult->opcdefault = opcform->opcdefault;
1002                                 prevResult->opckeytype = opcform->opckeytype;
1003                                 continue;
1004                         }
1005                 }
1006
1007                 /*
1008                  * Okay to add it to result list
1009                  */
1010                 newResult = (OpclassCandidateList)
1011                         palloc(sizeof(struct _OpclassCandidateList));
1012                 newResult->opcname_tmp = NameStr(opcform->opcname);
1013                 newResult->pathpos = pathpos;
1014                 newResult->oid = HeapTupleGetOid(opctup);
1015                 newResult->opcintype = opcform->opcintype;
1016                 newResult->opcdefault = opcform->opcdefault;
1017                 newResult->opckeytype = opcform->opckeytype;
1018                 newResult->next = resultList;
1019                 resultList = newResult;
1020         }
1021
1022         ReleaseSysCacheList(catlist);
1023
1024         return resultList;
1025 }
1026
1027 /*
1028  * OpclassnameGetOpcid
1029  *              Try to resolve an unqualified index opclass name.
1030  *              Returns OID if opclass found in search path, else InvalidOid.
1031  *
1032  * This is essentially the same as TypenameGetTypid, but we have to have
1033  * an extra argument for the index AM OID.
1034  */
1035 Oid
1036 OpclassnameGetOpcid(Oid amid, const char *opcname)
1037 {
1038         Oid                     opcid;
1039         ListCell   *l;
1040
1041         recomputeNamespacePath();
1042
1043         foreach(l, namespaceSearchPath)
1044         {
1045                 Oid                     namespaceId = lfirst_oid(l);
1046
1047                 opcid = GetSysCacheOid(CLAAMNAMENSP,
1048                                                            ObjectIdGetDatum(amid),
1049                                                            PointerGetDatum(opcname),
1050                                                            ObjectIdGetDatum(namespaceId),
1051                                                            0);
1052                 if (OidIsValid(opcid))
1053                         return opcid;
1054         }
1055
1056         /* Not found in path */
1057         return InvalidOid;
1058 }
1059
1060 /*
1061  * OpclassIsVisible
1062  *              Determine whether an opclass (identified by OID) is visible in the
1063  *              current search path.  Visible means "would be found by searching
1064  *              for the unqualified opclass name".
1065  */
1066 bool
1067 OpclassIsVisible(Oid opcid)
1068 {
1069         HeapTuple       opctup;
1070         Form_pg_opclass opcform;
1071         Oid                     opcnamespace;
1072         bool            visible;
1073
1074         opctup = SearchSysCache(CLAOID,
1075                                                         ObjectIdGetDatum(opcid),
1076                                                         0, 0, 0);
1077         if (!HeapTupleIsValid(opctup))
1078                 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1079         opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1080
1081         recomputeNamespacePath();
1082
1083         /*
1084          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1085          * the system namespace are surely in the path and so we needn't even do
1086          * list_member_oid() for them.
1087          */
1088         opcnamespace = opcform->opcnamespace;
1089         if (opcnamespace != PG_CATALOG_NAMESPACE &&
1090                 !list_member_oid(namespaceSearchPath, opcnamespace))
1091                 visible = false;
1092         else
1093         {
1094                 /*
1095                  * If it is in the path, it might still not be visible; it could be
1096                  * hidden by another opclass of the same name earlier in the path. So
1097                  * we must do a slow check to see if this opclass would be found by
1098                  * OpclassnameGetOpcid.
1099                  */
1100                 char       *opcname = NameStr(opcform->opcname);
1101
1102                 visible = (OpclassnameGetOpcid(opcform->opcamid, opcname) == opcid);
1103         }
1104
1105         ReleaseSysCache(opctup);
1106
1107         return visible;
1108 }
1109
1110 /*
1111  * ConversionGetConid
1112  *              Try to resolve an unqualified conversion name.
1113  *              Returns OID if conversion found in search path, else InvalidOid.
1114  *
1115  * This is essentially the same as RelnameGetRelid.
1116  */
1117 Oid
1118 ConversionGetConid(const char *conname)
1119 {
1120         Oid                     conid;
1121         ListCell   *l;
1122
1123         recomputeNamespacePath();
1124
1125         foreach(l, namespaceSearchPath)
1126         {
1127                 Oid                     namespaceId = lfirst_oid(l);
1128
1129                 conid = GetSysCacheOid(CONNAMENSP,
1130                                                            PointerGetDatum(conname),
1131                                                            ObjectIdGetDatum(namespaceId),
1132                                                            0, 0);
1133                 if (OidIsValid(conid))
1134                         return conid;
1135         }
1136
1137         /* Not found in path */
1138         return InvalidOid;
1139 }
1140
1141 /*
1142  * ConversionIsVisible
1143  *              Determine whether a conversion (identified by OID) is visible in the
1144  *              current search path.  Visible means "would be found by searching
1145  *              for the unqualified conversion name".
1146  */
1147 bool
1148 ConversionIsVisible(Oid conid)
1149 {
1150         HeapTuple       contup;
1151         Form_pg_conversion conform;
1152         Oid                     connamespace;
1153         bool            visible;
1154
1155         contup = SearchSysCache(CONOID,
1156                                                         ObjectIdGetDatum(conid),
1157                                                         0, 0, 0);
1158         if (!HeapTupleIsValid(contup))
1159                 elog(ERROR, "cache lookup failed for conversion %u", conid);
1160         conform = (Form_pg_conversion) GETSTRUCT(contup);
1161
1162         recomputeNamespacePath();
1163
1164         /*
1165          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1166          * the system namespace are surely in the path and so we needn't even do
1167          * list_member_oid() for them.
1168          */
1169         connamespace = conform->connamespace;
1170         if (connamespace != PG_CATALOG_NAMESPACE &&
1171                 !list_member_oid(namespaceSearchPath, connamespace))
1172                 visible = false;
1173         else
1174         {
1175                 /*
1176                  * If it is in the path, it might still not be visible; it could be
1177                  * hidden by another conversion of the same name earlier in the path.
1178                  * So we must do a slow check to see if this conversion would be found
1179                  * by ConversionGetConid.
1180                  */
1181                 char       *conname = NameStr(conform->conname);
1182
1183                 visible = (ConversionGetConid(conname) == conid);
1184         }
1185
1186         ReleaseSysCache(contup);
1187
1188         return visible;
1189 }
1190
1191 /*
1192  * DeconstructQualifiedName
1193  *              Given a possibly-qualified name expressed as a list of String nodes,
1194  *              extract the schema name and object name.
1195  *
1196  * *nspname_p is set to NULL if there is no explicit schema name.
1197  */
1198 void
1199 DeconstructQualifiedName(List *names,
1200                                                  char **nspname_p,
1201                                                  char **objname_p)
1202 {
1203         char       *catalogname;
1204         char       *schemaname = NULL;
1205         char       *objname = NULL;
1206
1207         switch (list_length(names))
1208         {
1209                 case 1:
1210                         objname = strVal(linitial(names));
1211                         break;
1212                 case 2:
1213                         schemaname = strVal(linitial(names));
1214                         objname = strVal(lsecond(names));
1215                         break;
1216                 case 3:
1217                         catalogname = strVal(linitial(names));
1218                         schemaname = strVal(lsecond(names));
1219                         objname = strVal(lthird(names));
1220
1221                         /*
1222                          * We check the catalog name and then ignore it.
1223                          */
1224                         if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
1225                                 ereport(ERROR,
1226                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1227                                   errmsg("cross-database references are not implemented: %s",
1228                                                  NameListToString(names))));
1229                         break;
1230                 default:
1231                         ereport(ERROR,
1232                                         (errcode(ERRCODE_SYNTAX_ERROR),
1233                                 errmsg("improper qualified name (too many dotted names): %s",
1234                                            NameListToString(names))));
1235                         break;
1236         }
1237
1238         *nspname_p = schemaname;
1239         *objname_p = objname;
1240 }
1241
1242 /*
1243  * LookupExplicitNamespace
1244  *              Process an explicitly-specified schema name: look up the schema
1245  *              and verify we have USAGE (lookup) rights in it.
1246  *
1247  * Returns the namespace OID.  Raises ereport if any problem.
1248  */
1249 Oid
1250 LookupExplicitNamespace(const char *nspname)
1251 {
1252         Oid                     namespaceId;
1253         AclResult       aclresult;
1254
1255         namespaceId = GetSysCacheOid(NAMESPACENAME,
1256                                                                  CStringGetDatum(nspname),
1257                                                                  0, 0, 0);
1258         if (!OidIsValid(namespaceId))
1259                 ereport(ERROR,
1260                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1261                                  errmsg("schema \"%s\" does not exist", nspname)));
1262
1263         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
1264         if (aclresult != ACLCHECK_OK)
1265                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1266                                            nspname);
1267
1268         return namespaceId;
1269 }
1270
1271 /*
1272  * LookupCreationNamespace
1273  *              Look up the schema and verify we have CREATE rights on it.
1274  *
1275  * This is just like LookupExplicitNamespace except for the permission check.
1276  */
1277 Oid
1278 LookupCreationNamespace(const char *nspname)
1279 {
1280         Oid                     namespaceId;
1281         AclResult       aclresult;
1282
1283         namespaceId = GetSysCacheOid(NAMESPACENAME,
1284                                                                  CStringGetDatum(nspname),
1285                                                                  0, 0, 0);
1286         if (!OidIsValid(namespaceId))
1287                 ereport(ERROR,
1288                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1289                                  errmsg("schema \"%s\" does not exist", nspname)));
1290
1291         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
1292         if (aclresult != ACLCHECK_OK)
1293                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
1294                                            nspname);
1295
1296         return namespaceId;
1297 }
1298
1299 /*
1300  * QualifiedNameGetCreationNamespace
1301  *              Given a possibly-qualified name for an object (in List-of-Values
1302  *              format), determine what namespace the object should be created in.
1303  *              Also extract and return the object name (last component of list).
1304  *
1305  * Note: this does not apply any permissions check.  Callers must check
1306  * for CREATE rights on the selected namespace when appropriate.
1307  *
1308  * This is *not* used for tables.  Hence, the TEMP table namespace is
1309  * never selected as the creation target.
1310  */
1311 Oid
1312 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
1313 {
1314         char       *schemaname;
1315         char       *objname;
1316         Oid                     namespaceId;
1317
1318         /* deconstruct the name list */
1319         DeconstructQualifiedName(names, &schemaname, &objname);
1320
1321         if (schemaname)
1322         {
1323                 /* use exact schema given */
1324                 namespaceId = GetSysCacheOid(NAMESPACENAME,
1325                                                                          CStringGetDatum(schemaname),
1326                                                                          0, 0, 0);
1327                 if (!OidIsValid(namespaceId))
1328                         ereport(ERROR,
1329                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
1330                                          errmsg("schema \"%s\" does not exist", schemaname)));
1331                 /* we do not check for USAGE rights here! */
1332         }
1333         else
1334         {
1335                 /* use the default creation namespace */
1336                 recomputeNamespacePath();
1337                 namespaceId = defaultCreationNamespace;
1338                 if (!OidIsValid(namespaceId))
1339                         ereport(ERROR,
1340                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
1341                                          errmsg("no schema has been selected to create in")));
1342         }
1343
1344         *objname_p = objname;
1345         return namespaceId;
1346 }
1347
1348 /*
1349  * makeRangeVarFromNameList
1350  *              Utility routine to convert a qualified-name list into RangeVar form.
1351  */
1352 RangeVar *
1353 makeRangeVarFromNameList(List *names)
1354 {
1355         RangeVar   *rel = makeRangeVar(NULL, NULL);
1356
1357         switch (list_length(names))
1358         {
1359                 case 1:
1360                         rel->relname = strVal(linitial(names));
1361                         break;
1362                 case 2:
1363                         rel->schemaname = strVal(linitial(names));
1364                         rel->relname = strVal(lsecond(names));
1365                         break;
1366                 case 3:
1367                         rel->catalogname = strVal(linitial(names));
1368                         rel->schemaname = strVal(lsecond(names));
1369                         rel->relname = strVal(lthird(names));
1370                         break;
1371                 default:
1372                         ereport(ERROR,
1373                                         (errcode(ERRCODE_SYNTAX_ERROR),
1374                                  errmsg("improper relation name (too many dotted names): %s",
1375                                                 NameListToString(names))));
1376                         break;
1377         }
1378
1379         return rel;
1380 }
1381
1382 /*
1383  * NameListToString
1384  *              Utility routine to convert a qualified-name list into a string.
1385  *
1386  * This is used primarily to form error messages, and so we do not quote
1387  * the list elements, for the sake of legibility.
1388  */
1389 char *
1390 NameListToString(List *names)
1391 {
1392         StringInfoData string;
1393         ListCell   *l;
1394
1395         initStringInfo(&string);
1396
1397         foreach(l, names)
1398         {
1399                 if (l != list_head(names))
1400                         appendStringInfoChar(&string, '.');
1401                 appendStringInfoString(&string, strVal(lfirst(l)));
1402         }
1403
1404         return string.data;
1405 }
1406
1407 /*
1408  * NameListToQuotedString
1409  *              Utility routine to convert a qualified-name list into a string.
1410  *
1411  * Same as above except that names will be double-quoted where necessary,
1412  * so the string could be re-parsed (eg, by textToQualifiedNameList).
1413  */
1414 char *
1415 NameListToQuotedString(List *names)
1416 {
1417         StringInfoData string;
1418         ListCell   *l;
1419
1420         initStringInfo(&string);
1421
1422         foreach(l, names)
1423         {
1424                 if (l != list_head(names))
1425                         appendStringInfoChar(&string, '.');
1426                 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
1427         }
1428
1429         return string.data;
1430 }
1431
1432 /*
1433  * isTempNamespace - is the given namespace my temporary-table namespace?
1434  */
1435 bool
1436 isTempNamespace(Oid namespaceId)
1437 {
1438         if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
1439                 return true;
1440         return false;
1441 }
1442
1443 /*
1444  * isAnyTempNamespace - is the given namespace a temporary-table namespace
1445  * (either my own, or another backend's)?
1446  */
1447 bool
1448 isAnyTempNamespace(Oid namespaceId)
1449 {
1450         bool            result;
1451         char       *nspname;
1452
1453         /* If the namespace name starts with "pg_temp_", say "true" */
1454         nspname = get_namespace_name(namespaceId);
1455         if (!nspname)
1456                 return false;                   /* no such namespace? */
1457         result = (strncmp(nspname, "pg_temp_", 8) == 0);
1458         pfree(nspname);
1459         return result;
1460 }
1461
1462 /*
1463  * isOtherTempNamespace - is the given namespace some other backend's
1464  * temporary-table namespace?
1465  */
1466 bool
1467 isOtherTempNamespace(Oid namespaceId)
1468 {
1469         /* If it's my own temp namespace, say "false" */
1470         if (isTempNamespace(namespaceId))
1471                 return false;
1472         /* Else, if the namespace name starts with "pg_temp_", say "true" */
1473         return isAnyTempNamespace(namespaceId);
1474 }
1475
1476 /*
1477  * PushSpecialNamespace - push a "special" namespace onto the front of the
1478  * search path.
1479  *
1480  * This is a slightly messy hack intended only for support of CREATE SCHEMA.
1481  * Although the API is defined to allow a stack of pushed namespaces, we
1482  * presently only support one at a time.
1483  *
1484  * The pushed namespace will be removed from the search path at end of
1485  * transaction, whether commit or abort.
1486  */
1487 void
1488 PushSpecialNamespace(Oid namespaceId)
1489 {
1490         Assert(!OidIsValid(mySpecialNamespace));
1491         mySpecialNamespace = namespaceId;
1492         namespaceSearchPathValid = false;
1493 }
1494
1495 /*
1496  * PopSpecialNamespace - remove previously pushed special namespace.
1497  */
1498 void
1499 PopSpecialNamespace(Oid namespaceId)
1500 {
1501         Assert(mySpecialNamespace == namespaceId);
1502         mySpecialNamespace = InvalidOid;
1503         namespaceSearchPathValid = false;
1504 }
1505
1506 /*
1507  * FindConversionByName - find a conversion by possibly qualified name
1508  */
1509 Oid
1510 FindConversionByName(List *name)
1511 {
1512         char       *schemaname;
1513         char       *conversion_name;
1514         Oid                     namespaceId;
1515         Oid                     conoid;
1516         ListCell   *l;
1517
1518         /* deconstruct the name list */
1519         DeconstructQualifiedName(name, &schemaname, &conversion_name);
1520
1521         if (schemaname)
1522         {
1523                 /* use exact schema given */
1524                 namespaceId = LookupExplicitNamespace(schemaname);
1525                 return FindConversion(conversion_name, namespaceId);
1526         }
1527         else
1528         {
1529                 /* search for it in search path */
1530                 recomputeNamespacePath();
1531
1532                 foreach(l, namespaceSearchPath)
1533                 {
1534                         namespaceId = lfirst_oid(l);
1535                         conoid = FindConversion(conversion_name, namespaceId);
1536                         if (OidIsValid(conoid))
1537                                 return conoid;
1538                 }
1539         }
1540
1541         /* Not found in path */
1542         return InvalidOid;
1543 }
1544
1545 /*
1546  * FindDefaultConversionProc - find default encoding conversion proc
1547  */
1548 Oid
1549 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
1550 {
1551         Oid                     proc;
1552         ListCell   *l;
1553
1554         recomputeNamespacePath();
1555
1556         foreach(l, namespaceSearchPath)
1557         {
1558                 Oid                     namespaceId = lfirst_oid(l);
1559
1560                 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
1561                 if (OidIsValid(proc))
1562                         return proc;
1563         }
1564
1565         /* Not found in path */
1566         return InvalidOid;
1567 }
1568
1569 /*
1570  * recomputeNamespacePath - recompute path derived variables if needed.
1571  */
1572 static void
1573 recomputeNamespacePath(void)
1574 {
1575         Oid                     roleid = GetUserId();
1576         char       *rawname;
1577         List       *namelist;
1578         List       *oidlist;
1579         List       *newpath;
1580         ListCell   *l;
1581         Oid                     firstNS;
1582         MemoryContext oldcxt;
1583
1584         /*
1585          * Do nothing if path is already valid.
1586          */
1587         if (namespaceSearchPathValid && namespaceUser == roleid)
1588                 return;
1589
1590         /* Need a modifiable copy of namespace_search_path string */
1591         rawname = pstrdup(namespace_search_path);
1592
1593         /* Parse string into list of identifiers */
1594         if (!SplitIdentifierString(rawname, ',', &namelist))
1595         {
1596                 /* syntax error in name list */
1597                 /* this should not happen if GUC checked check_search_path */
1598                 elog(ERROR, "invalid list syntax");
1599         }
1600
1601         /*
1602          * Convert the list of names to a list of OIDs.  If any names are not
1603          * recognizable or we don't have read access, just leave them out of the
1604          * list.  (We can't raise an error, since the search_path setting has
1605          * already been accepted.)      Don't make duplicate entries, either.
1606          */
1607         oidlist = NIL;
1608         foreach(l, namelist)
1609         {
1610                 char       *curname = (char *) lfirst(l);
1611                 Oid                     namespaceId;
1612
1613                 if (strcmp(curname, "$user") == 0)
1614                 {
1615                         /* $user --- substitute namespace matching user name, if any */
1616                         HeapTuple       tuple;
1617
1618                         tuple = SearchSysCache(AUTHOID,
1619                                                                    ObjectIdGetDatum(roleid),
1620                                                                    0, 0, 0);
1621                         if (HeapTupleIsValid(tuple))
1622                         {
1623                                 char       *rname;
1624
1625                                 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
1626                                 namespaceId = GetSysCacheOid(NAMESPACENAME,
1627                                                                                          CStringGetDatum(rname),
1628                                                                                          0, 0, 0);
1629                                 ReleaseSysCache(tuple);
1630                                 if (OidIsValid(namespaceId) &&
1631                                         !list_member_oid(oidlist, namespaceId) &&
1632                                         pg_namespace_aclcheck(namespaceId, roleid,
1633                                                                                   ACL_USAGE) == ACLCHECK_OK)
1634                                         oidlist = lappend_oid(oidlist, namespaceId);
1635                         }
1636                 }
1637                 else
1638                 {
1639                         /* normal namespace reference */
1640                         namespaceId = GetSysCacheOid(NAMESPACENAME,
1641                                                                                  CStringGetDatum(curname),
1642                                                                                  0, 0, 0);
1643                         if (OidIsValid(namespaceId) &&
1644                                 !list_member_oid(oidlist, namespaceId) &&
1645                                 pg_namespace_aclcheck(namespaceId, roleid,
1646                                                                           ACL_USAGE) == ACLCHECK_OK)
1647                                 oidlist = lappend_oid(oidlist, namespaceId);
1648                 }
1649         }
1650
1651         /*
1652          * Remember the first member of the explicit list.
1653          */
1654         if (oidlist == NIL)
1655                 firstNS = InvalidOid;
1656         else
1657                 firstNS = linitial_oid(oidlist);
1658
1659         /*
1660          * Add any implicitly-searched namespaces to the list.  Note these go on
1661          * the front, not the back; also notice that we do not check USAGE
1662          * permissions for these.
1663          */
1664         if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
1665                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
1666
1667         if (OidIsValid(myTempNamespace) &&
1668                 !list_member_oid(oidlist, myTempNamespace))
1669                 oidlist = lcons_oid(myTempNamespace, oidlist);
1670
1671         if (OidIsValid(mySpecialNamespace) &&
1672                 !list_member_oid(oidlist, mySpecialNamespace))
1673                 oidlist = lcons_oid(mySpecialNamespace, oidlist);
1674
1675         /*
1676          * Now that we've successfully built the new list of namespace OIDs, save
1677          * it in permanent storage.
1678          */
1679         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1680         newpath = list_copy(oidlist);
1681         MemoryContextSwitchTo(oldcxt);
1682
1683         /* Now safe to assign to state variable. */
1684         list_free(namespaceSearchPath);
1685         namespaceSearchPath = newpath;
1686
1687         /*
1688          * Update info derived from search path.
1689          */
1690         firstExplicitNamespace = firstNS;
1691         if (OidIsValid(mySpecialNamespace))
1692                 defaultCreationNamespace = mySpecialNamespace;
1693         else
1694                 defaultCreationNamespace = firstNS;
1695
1696         /* Mark the path valid. */
1697         namespaceSearchPathValid = true;
1698         namespaceUser = roleid;
1699
1700         /* Clean up. */
1701         pfree(rawname);
1702         list_free(namelist);
1703         list_free(oidlist);
1704 }
1705
1706 /*
1707  * InitTempTableNamespace
1708  *              Initialize temp table namespace on first use in a particular backend
1709  */
1710 static void
1711 InitTempTableNamespace(void)
1712 {
1713         char            namespaceName[NAMEDATALEN];
1714         Oid                     namespaceId;
1715
1716         /*
1717          * First, do permission check to see if we are authorized to make temp
1718          * tables.      We use a nonstandard error message here since "databasename:
1719          * permission denied" might be a tad cryptic.
1720          *
1721          * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
1722          * that's necessary since current user ID could change during the session.
1723          * But there's no need to make the namespace in the first place until a
1724          * temp table creation request is made by someone with appropriate rights.
1725          */
1726         if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
1727                                                          ACL_CREATE_TEMP) != ACLCHECK_OK)
1728                 ereport(ERROR,
1729                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1730                                  errmsg("permission denied to create temporary tables in database \"%s\"",
1731                                                 get_database_name(MyDatabaseId))));
1732
1733         snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
1734
1735         namespaceId = GetSysCacheOid(NAMESPACENAME,
1736                                                                  CStringGetDatum(namespaceName),
1737                                                                  0, 0, 0);
1738         if (!OidIsValid(namespaceId))
1739         {
1740                 /*
1741                  * First use of this temp namespace in this database; create it. The
1742                  * temp namespaces are always owned by the superuser.  We leave their
1743                  * permissions at default --- i.e., no access except to superuser ---
1744                  * to ensure that unprivileged users can't peek at other backends'
1745                  * temp tables.  This works because the places that access the temp
1746                  * namespace for my own backend skip permissions checks on it.
1747                  */
1748                 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
1749                 /* Advance command counter to make namespace visible */
1750                 CommandCounterIncrement();
1751         }
1752         else
1753         {
1754                 /*
1755                  * If the namespace already exists, clean it out (in case the former
1756                  * owner crashed without doing so).
1757                  */
1758                 RemoveTempRelations(namespaceId);
1759         }
1760
1761         /*
1762          * Okay, we've prepared the temp namespace ... but it's not committed yet,
1763          * so all our work could be undone by transaction rollback.  Set flag for
1764          * AtEOXact_Namespace to know what to do.
1765          */
1766         myTempNamespace = namespaceId;
1767
1768         /* It should not be done already. */
1769         AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
1770         myTempNamespaceSubID = GetCurrentSubTransactionId();
1771
1772         namespaceSearchPathValid = false;       /* need to rebuild list */
1773 }
1774
1775 /*
1776  * End-of-transaction cleanup for namespaces.
1777  */
1778 void
1779 AtEOXact_Namespace(bool isCommit)
1780 {
1781         /*
1782          * If we abort the transaction in which a temp namespace was selected,
1783          * we'll have to do any creation or cleanout work over again.  So, just
1784          * forget the namespace entirely until next time.  On the other hand, if
1785          * we commit then register an exit callback to clean out the temp tables
1786          * at backend shutdown.  (We only want to register the callback once per
1787          * session, so this is a good place to do it.)
1788          */
1789         if (myTempNamespaceSubID != InvalidSubTransactionId)
1790         {
1791                 if (isCommit)
1792                         on_shmem_exit(RemoveTempRelationsCallback, 0);
1793                 else
1794                 {
1795                         myTempNamespace = InvalidOid;
1796                         namespaceSearchPathValid = false;       /* need to rebuild list */
1797                 }
1798                 myTempNamespaceSubID = InvalidSubTransactionId;
1799         }
1800
1801         /*
1802          * Clean up if someone failed to do PopSpecialNamespace
1803          */
1804         if (OidIsValid(mySpecialNamespace))
1805         {
1806                 mySpecialNamespace = InvalidOid;
1807                 namespaceSearchPathValid = false;               /* need to rebuild list */
1808         }
1809 }
1810
1811 /*
1812  * AtEOSubXact_Namespace
1813  *
1814  * At subtransaction commit, propagate the temp-namespace-creation
1815  * flag to the parent subtransaction.
1816  *
1817  * At subtransaction abort, forget the flag if we set it up.
1818  */
1819 void
1820 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
1821                                           SubTransactionId parentSubid)
1822 {
1823         if (myTempNamespaceSubID == mySubid)
1824         {
1825                 if (isCommit)
1826                         myTempNamespaceSubID = parentSubid;
1827                 else
1828                 {
1829                         myTempNamespaceSubID = InvalidSubTransactionId;
1830                         /* TEMP namespace creation failed, so reset state */
1831                         myTempNamespace = InvalidOid;
1832                         namespaceSearchPathValid = false;       /* need to rebuild list */
1833                 }
1834         }
1835 }
1836
1837 /*
1838  * Remove all relations in the specified temp namespace.
1839  *
1840  * This is called at backend shutdown (if we made any temp relations).
1841  * It is also called when we begin using a pre-existing temp namespace,
1842  * in order to clean out any relations that might have been created by
1843  * a crashed backend.
1844  */
1845 static void
1846 RemoveTempRelations(Oid tempNamespaceId)
1847 {
1848         ObjectAddress object;
1849
1850         /*
1851          * We want to get rid of everything in the target namespace, but not the
1852          * namespace itself (deleting it only to recreate it later would be a
1853          * waste of cycles).  We do this by finding everything that has a
1854          * dependency on the namespace.
1855          */
1856         object.classId = NamespaceRelationId;
1857         object.objectId = tempNamespaceId;
1858         object.objectSubId = 0;
1859
1860         deleteWhatDependsOn(&object, false);
1861 }
1862
1863 /*
1864  * Callback to remove temp relations at backend exit.
1865  */
1866 static void
1867 RemoveTempRelationsCallback(int code, Datum arg)
1868 {
1869         if (OidIsValid(myTempNamespace))        /* should always be true */
1870         {
1871                 /* Need to ensure we have a usable transaction. */
1872                 AbortOutOfAnyTransaction();
1873                 StartTransactionCommand();
1874
1875                 RemoveTempRelations(myTempNamespace);
1876
1877                 CommitTransactionCommand();
1878         }
1879 }
1880
1881
1882 /*
1883  * Routines for handling the GUC variable 'search_path'.
1884  */
1885
1886 /* assign_hook: validate new search_path, do extra actions as needed */
1887 const char *
1888 assign_search_path(const char *newval, bool doit, GucSource source)
1889 {
1890         char       *rawname;
1891         List       *namelist;
1892         ListCell   *l;
1893
1894         /* Need a modifiable copy of string */
1895         rawname = pstrdup(newval);
1896
1897         /* Parse string into list of identifiers */
1898         if (!SplitIdentifierString(rawname, ',', &namelist))
1899         {
1900                 /* syntax error in name list */
1901                 pfree(rawname);
1902                 list_free(namelist);
1903                 return NULL;
1904         }
1905
1906         /*
1907          * If we aren't inside a transaction, we cannot do database access so
1908          * cannot verify the individual names.  Must accept the list on faith.
1909          */
1910         if (source >= PGC_S_INTERACTIVE && IsTransactionState())
1911         {
1912                 /*
1913                  * Verify that all the names are either valid namespace names or
1914                  * "$user".  We do not require $user to correspond to a valid
1915                  * namespace.  We do not check for USAGE rights, either; should we?
1916                  *
1917                  * When source == PGC_S_TEST, we are checking the argument of an ALTER
1918                  * DATABASE SET or ALTER USER SET command.      It could be that the
1919                  * intended use of the search path is for some other database, so we
1920                  * should not error out if it mentions schemas not present in the
1921                  * current database.  We reduce the message to NOTICE instead.
1922                  */
1923                 foreach(l, namelist)
1924                 {
1925                         char       *curname = (char *) lfirst(l);
1926
1927                         if (strcmp(curname, "$user") == 0)
1928                                 continue;
1929                         if (!SearchSysCacheExists(NAMESPACENAME,
1930                                                                           CStringGetDatum(curname),
1931                                                                           0, 0, 0))
1932                                 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
1933                                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
1934                                                  errmsg("schema \"%s\" does not exist", curname)));
1935                 }
1936         }
1937
1938         pfree(rawname);
1939         list_free(namelist);
1940
1941         /*
1942          * We mark the path as needing recomputation, but don't do anything until
1943          * it's needed.  This avoids trying to do database access during GUC
1944          * initialization.
1945          */
1946         if (doit)
1947                 namespaceSearchPathValid = false;
1948
1949         return newval;
1950 }
1951
1952 /*
1953  * InitializeSearchPath: initialize module during InitPostgres.
1954  *
1955  * This is called after we are up enough to be able to do catalog lookups.
1956  */
1957 void
1958 InitializeSearchPath(void)
1959 {
1960         if (IsBootstrapProcessingMode())
1961         {
1962                 /*
1963                  * In bootstrap mode, the search path must be 'pg_catalog' so that
1964                  * tables are created in the proper namespace; ignore the GUC setting.
1965                  */
1966                 MemoryContext oldcxt;
1967
1968                 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
1969                 namespaceSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
1970                 MemoryContextSwitchTo(oldcxt);
1971                 defaultCreationNamespace = PG_CATALOG_NAMESPACE;
1972                 firstExplicitNamespace = PG_CATALOG_NAMESPACE;
1973                 namespaceSearchPathValid = true;
1974                 namespaceUser = GetUserId();
1975         }
1976         else
1977         {
1978                 /*
1979                  * In normal mode, arrange for a callback on any syscache invalidation
1980                  * of pg_namespace rows.
1981                  */
1982                 CacheRegisterSyscacheCallback(NAMESPACEOID,
1983                                                                           NamespaceCallback,
1984                                                                           (Datum) 0);
1985                 /* Force search path to be recomputed on next use */
1986                 namespaceSearchPathValid = false;
1987         }
1988 }
1989
1990 /*
1991  * NamespaceCallback
1992  *              Syscache inval callback function
1993  */
1994 static void
1995 NamespaceCallback(Datum arg, Oid relid)
1996 {
1997         /* Force search path to be recomputed on next use */
1998         namespaceSearchPathValid = false;
1999 }
2000
2001 /*
2002  * Fetch the active search path. The return value is a palloc'ed list
2003  * of OIDs; the caller is responsible for freeing this storage as
2004  * appropriate.
2005  *
2006  * The returned list includes the implicitly-prepended namespaces only if
2007  * includeImplicit is true.
2008  */
2009 List *
2010 fetch_search_path(bool includeImplicit)
2011 {
2012         List       *result;
2013
2014         recomputeNamespacePath();
2015
2016         result = list_copy(namespaceSearchPath);
2017         if (!includeImplicit)
2018         {
2019                 while (result && linitial_oid(result) != firstExplicitNamespace)
2020                         result = list_delete_first(result);
2021         }
2022
2023         return result;
2024 }
2025
2026 /*
2027  * Export the FooIsVisible functions as SQL-callable functions.
2028  */
2029
2030 Datum
2031 pg_table_is_visible(PG_FUNCTION_ARGS)
2032 {
2033         Oid                     oid = PG_GETARG_OID(0);
2034
2035         PG_RETURN_BOOL(RelationIsVisible(oid));
2036 }
2037
2038 Datum
2039 pg_type_is_visible(PG_FUNCTION_ARGS)
2040 {
2041         Oid                     oid = PG_GETARG_OID(0);
2042
2043         PG_RETURN_BOOL(TypeIsVisible(oid));
2044 }
2045
2046 Datum
2047 pg_function_is_visible(PG_FUNCTION_ARGS)
2048 {
2049         Oid                     oid = PG_GETARG_OID(0);
2050
2051         PG_RETURN_BOOL(FunctionIsVisible(oid));
2052 }
2053
2054 Datum
2055 pg_operator_is_visible(PG_FUNCTION_ARGS)
2056 {
2057         Oid                     oid = PG_GETARG_OID(0);
2058
2059         PG_RETURN_BOOL(OperatorIsVisible(oid));
2060 }
2061
2062 Datum
2063 pg_opclass_is_visible(PG_FUNCTION_ARGS)
2064 {
2065         Oid                     oid = PG_GETARG_OID(0);
2066
2067         PG_RETURN_BOOL(OpclassIsVisible(oid));
2068 }
2069
2070 Datum
2071 pg_conversion_is_visible(PG_FUNCTION_ARGS)
2072 {
2073         Oid                     oid = PG_GETARG_OID(0);
2074
2075         PG_RETURN_BOOL(ConversionIsVisible(oid));
2076 }