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