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