]> granicus.if.org Git - postgresql/blob - src/backend/catalog/namespace.c
Standardize get_whatever_oid functions for object types with
[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-2010, 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.126 2010/08/05 14:44:58 rhaas 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_conversion_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "catalog/pg_opclass.h"
30 #include "catalog/pg_operator.h"
31 #include "catalog/pg_opfamily.h"
32 #include "catalog/pg_proc.h"
33 #include "catalog/pg_ts_config.h"
34 #include "catalog/pg_ts_dict.h"
35 #include "catalog/pg_ts_parser.h"
36 #include "catalog/pg_ts_template.h"
37 #include "catalog/pg_type.h"
38 #include "commands/dbcommands.h"
39 #include "funcapi.h"
40 #include "miscadmin.h"
41 #include "nodes/makefuncs.h"
42 #include "parser/parse_func.h"
43 #include "storage/backendid.h"
44 #include "storage/ipc.h"
45 #include "utils/acl.h"
46 #include "utils/builtins.h"
47 #include "utils/guc.h"
48 #include "utils/inval.h"
49 #include "utils/lsyscache.h"
50 #include "utils/memutils.h"
51 #include "utils/rel.h"
52 #include "utils/syscache.h"
53
54
55 /*
56  * The namespace search path is a possibly-empty list of namespace OIDs.
57  * In addition to the explicit list, implicitly-searched namespaces
58  * may be included:
59  *
60  * 1. If a TEMP table namespace has been initialized in this session, it
61  * is implicitly searched first.  (The only time this doesn't happen is
62  * when we are obeying an override search path spec that says not to use the
63  * temp namespace, or the temp namespace is included in the explicit list.)
64  *
65  * 2. The system catalog namespace is always searched.  If the system
66  * namespace is present in the explicit path then it will be searched in
67  * the specified order; otherwise it will be searched after TEMP tables and
68  * *before* the explicit list.  (It might seem that the system namespace
69  * should be implicitly last, but this behavior appears to be required by
70  * SQL99.  Also, this provides a way to search the system namespace first
71  * without thereby making it the default creation target namespace.)
72  *
73  * For security reasons, searches using the search path will ignore the temp
74  * namespace when searching for any object type other than relations and
75  * types.  (We must allow types since temp tables have rowtypes.)
76  *
77  * The default creation target namespace is always the first element of the
78  * explicit list.  If the explicit list is empty, there is no default target.
79  *
80  * The textual specification of search_path can include "$user" to refer to
81  * the namespace named the same as the current user, if any.  (This is just
82  * ignored if there is no such namespace.)      Also, it can include "pg_temp"
83  * to refer to the current backend's temp namespace.  This is usually also
84  * ignorable if the temp namespace hasn't been set up, but there's a special
85  * case: if "pg_temp" appears first then it should be the default creation
86  * target.      We kluge this case a little bit so that the temp namespace isn't
87  * set up until the first attempt to create something in it.  (The reason for
88  * klugery is that we can't create the temp namespace outside a transaction,
89  * but initial GUC processing of search_path happens outside a transaction.)
90  * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
91  * but is not reflected in activeCreationNamespace because the namespace isn't
92  * set up yet.
93  *
94  * In bootstrap mode, the search path is set equal to "pg_catalog", so that
95  * the system namespace is the only one searched or inserted into.
96  * initdb is also careful to set search_path to "pg_catalog" for its
97  * post-bootstrap standalone backend runs.      Otherwise the default search
98  * path is determined by GUC.  The factory default path contains the PUBLIC
99  * namespace (if it exists), preceded by the user's personal namespace
100  * (if one exists).
101  *
102  * We support a stack of "override" search path settings for use within
103  * specific sections of backend code.  namespace_search_path is ignored
104  * whenever the override stack is nonempty.  activeSearchPath is always
105  * the actually active path; it points either to the search list of the
106  * topmost stack entry, or to baseSearchPath which is the list derived
107  * from namespace_search_path.
108  *
109  * If baseSearchPathValid is false, then baseSearchPath (and other
110  * derived variables) need to be recomputed from namespace_search_path.
111  * We mark it invalid upon an assignment to namespace_search_path or receipt
112  * of a syscache invalidation event for pg_namespace.  The recomputation
113  * is done during the next non-overridden lookup attempt.  Note that an
114  * override spec is never subject to recomputation.
115  *
116  * Any namespaces mentioned in namespace_search_path that are not readable
117  * by the current user ID are simply left out of baseSearchPath; so
118  * we have to be willing to recompute the path when current userid changes.
119  * namespaceUser is the userid the path has been computed for.
120  *
121  * Note: all data pointed to by these List variables is in TopMemoryContext.
122  */
123
124 /* These variables define the actually active state: */
125
126 static List *activeSearchPath = NIL;
127
128 /* default place to create stuff; if InvalidOid, no default */
129 static Oid      activeCreationNamespace = InvalidOid;
130
131 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
132 static bool activeTempCreationPending = false;
133
134 /* These variables are the values last derived from namespace_search_path: */
135
136 static List *baseSearchPath = NIL;
137
138 static Oid      baseCreationNamespace = InvalidOid;
139
140 static bool baseTempCreationPending = false;
141
142 static Oid      namespaceUser = InvalidOid;
143
144 /* The above four values are valid only if baseSearchPathValid */
145 static bool baseSearchPathValid = true;
146
147 /* Override requests are remembered in a stack of OverrideStackEntry structs */
148
149 typedef struct
150 {
151         List       *searchPath;         /* the desired search path */
152         Oid                     creationNamespace;              /* the desired creation namespace */
153         int                     nestLevel;              /* subtransaction nesting level */
154 } OverrideStackEntry;
155
156 static List *overrideStack = NIL;
157
158 /*
159  * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
160  * in a particular backend session (this happens when a CREATE TEMP TABLE
161  * command is first executed).  Thereafter it's the OID of the temp namespace.
162  *
163  * myTempToastNamespace is the OID of the namespace for my temp tables' toast
164  * tables.      It is set when myTempNamespace is, and is InvalidOid before that.
165  *
166  * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
167  * current subtransaction.      The flag propagates up the subtransaction tree,
168  * so the main transaction will correctly recognize the flag if all
169  * intermediate subtransactions commit.  When it is InvalidSubTransactionId,
170  * we either haven't made the TEMP namespace yet, or have successfully
171  * committed its creation, depending on whether myTempNamespace is valid.
172  */
173 static Oid      myTempNamespace = InvalidOid;
174
175 static Oid      myTempToastNamespace = InvalidOid;
176
177 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
178
179 /*
180  * This is the user's textual search path specification --- it's the value
181  * of the GUC variable 'search_path'.
182  */
183 char       *namespace_search_path = NULL;
184
185
186 /* Local functions */
187 static void recomputeNamespacePath(void);
188 static void InitTempTableNamespace(void);
189 static void RemoveTempRelations(Oid tempNamespaceId);
190 static void RemoveTempRelationsCallback(int code, Datum arg);
191 static void NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr);
192 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
193                            int **argnumbers);
194
195 /* These don't really need to appear in any header file */
196 Datum           pg_table_is_visible(PG_FUNCTION_ARGS);
197 Datum           pg_type_is_visible(PG_FUNCTION_ARGS);
198 Datum           pg_function_is_visible(PG_FUNCTION_ARGS);
199 Datum           pg_operator_is_visible(PG_FUNCTION_ARGS);
200 Datum           pg_opclass_is_visible(PG_FUNCTION_ARGS);
201 Datum           pg_conversion_is_visible(PG_FUNCTION_ARGS);
202 Datum           pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
203 Datum           pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
204 Datum           pg_ts_template_is_visible(PG_FUNCTION_ARGS);
205 Datum           pg_ts_config_is_visible(PG_FUNCTION_ARGS);
206 Datum           pg_my_temp_schema(PG_FUNCTION_ARGS);
207 Datum           pg_is_other_temp_schema(PG_FUNCTION_ARGS);
208
209
210 /*
211  * RangeVarGetRelid
212  *              Given a RangeVar describing an existing relation,
213  *              select the proper namespace and look up the relation OID.
214  *
215  * If the relation is not found, return InvalidOid if failOK = true,
216  * otherwise raise an error.
217  */
218 Oid
219 RangeVarGetRelid(const RangeVar *relation, bool failOK)
220 {
221         Oid                     namespaceId;
222         Oid                     relId;
223
224         /*
225          * We check the catalog name and then ignore it.
226          */
227         if (relation->catalogname)
228         {
229                 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
230                         ereport(ERROR,
231                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
232                                          errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
233                                                         relation->catalogname, relation->schemaname,
234                                                         relation->relname)));
235         }
236
237         /*
238          * If istemp is set, this is a reference to a temp relation.  The parser
239          * never generates such a RangeVar in simple DML, but it can happen in
240          * contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY KEY)".  Such a
241          * command will generate an added CREATE INDEX operation, which must be
242          * careful to find the temp table, even when pg_temp is not first in the
243          * search path.
244          */
245         if (relation->istemp)
246         {
247                 if (relation->schemaname)
248                         ereport(ERROR,
249                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
250                                    errmsg("temporary tables cannot specify a schema name")));
251                 if (OidIsValid(myTempNamespace))
252                         relId = get_relname_relid(relation->relname, myTempNamespace);
253                 else    /* this probably can't happen? */
254                         relId = InvalidOid;
255         }
256         else if (relation->schemaname)
257         {
258                 /* use exact schema given */
259                 namespaceId = LookupExplicitNamespace(relation->schemaname);
260                 relId = get_relname_relid(relation->relname, namespaceId);
261         }
262         else
263         {
264                 /* search the namespace path */
265                 relId = RelnameGetRelid(relation->relname);
266         }
267
268         if (!OidIsValid(relId) && !failOK)
269         {
270                 if (relation->schemaname)
271                         ereport(ERROR,
272                                         (errcode(ERRCODE_UNDEFINED_TABLE),
273                                          errmsg("relation \"%s.%s\" does not exist",
274                                                         relation->schemaname, relation->relname)));
275                 else
276                         ereport(ERROR,
277                                         (errcode(ERRCODE_UNDEFINED_TABLE),
278                                          errmsg("relation \"%s\" does not exist",
279                                                         relation->relname)));
280         }
281         return relId;
282 }
283
284 /*
285  * RangeVarGetCreationNamespace
286  *              Given a RangeVar describing a to-be-created relation,
287  *              choose which namespace to create it in.
288  *
289  * Note: calling this may result in a CommandCounterIncrement operation.
290  * That will happen on the first request for a temp table in any particular
291  * backend run; we will need to either create or clean out the temp schema.
292  */
293 Oid
294 RangeVarGetCreationNamespace(const RangeVar *newRelation)
295 {
296         Oid                     namespaceId;
297
298         /*
299          * We check the catalog name and then ignore it.
300          */
301         if (newRelation->catalogname)
302         {
303                 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
304                         ereport(ERROR,
305                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
306                                          errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
307                                                         newRelation->catalogname, newRelation->schemaname,
308                                                         newRelation->relname)));
309         }
310
311         if (newRelation->istemp)
312         {
313                 /* TEMP tables are created in our backend-local temp namespace */
314                 if (newRelation->schemaname)
315                         ereport(ERROR,
316                                         (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
317                                    errmsg("temporary tables cannot specify a schema name")));
318                 /* Initialize temp namespace if first time through */
319                 if (!OidIsValid(myTempNamespace))
320                         InitTempTableNamespace();
321                 return myTempNamespace;
322         }
323
324         if (newRelation->schemaname)
325         {
326                 /* check for pg_temp alias */
327                 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
328                 {
329                         /* Initialize temp namespace if first time through */
330                         if (!OidIsValid(myTempNamespace))
331                                 InitTempTableNamespace();
332                         return myTempNamespace;
333                 }
334                 /* use exact schema given */
335                 namespaceId = get_namespace_oid(newRelation->schemaname, false);
336                 /* we do not check for USAGE rights here! */
337         }
338         else
339         {
340                 /* use the default creation namespace */
341                 recomputeNamespacePath();
342                 if (activeTempCreationPending)
343                 {
344                         /* Need to initialize temp namespace */
345                         InitTempTableNamespace();
346                         return myTempNamespace;
347                 }
348                 namespaceId = activeCreationNamespace;
349                 if (!OidIsValid(namespaceId))
350                         ereport(ERROR,
351                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
352                                          errmsg("no schema has been selected to create in")));
353         }
354
355         /* Note: callers will check for CREATE rights when appropriate */
356
357         return namespaceId;
358 }
359
360 /*
361  * RelnameGetRelid
362  *              Try to resolve an unqualified relation name.
363  *              Returns OID if relation found in search path, else InvalidOid.
364  */
365 Oid
366 RelnameGetRelid(const char *relname)
367 {
368         Oid                     relid;
369         ListCell   *l;
370
371         recomputeNamespacePath();
372
373         foreach(l, activeSearchPath)
374         {
375                 Oid                     namespaceId = lfirst_oid(l);
376
377                 relid = get_relname_relid(relname, namespaceId);
378                 if (OidIsValid(relid))
379                         return relid;
380         }
381
382         /* Not found in path */
383         return InvalidOid;
384 }
385
386
387 /*
388  * RelationIsVisible
389  *              Determine whether a relation (identified by OID) is visible in the
390  *              current search path.  Visible means "would be found by searching
391  *              for the unqualified relation name".
392  */
393 bool
394 RelationIsVisible(Oid relid)
395 {
396         HeapTuple       reltup;
397         Form_pg_class relform;
398         Oid                     relnamespace;
399         bool            visible;
400
401         reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
402         if (!HeapTupleIsValid(reltup))
403                 elog(ERROR, "cache lookup failed for relation %u", relid);
404         relform = (Form_pg_class) GETSTRUCT(reltup);
405
406         recomputeNamespacePath();
407
408         /*
409          * Quick check: if it ain't in the path at all, it ain't visible. Items in
410          * the system namespace are surely in the path and so we needn't even do
411          * list_member_oid() for them.
412          */
413         relnamespace = relform->relnamespace;
414         if (relnamespace != PG_CATALOG_NAMESPACE &&
415                 !list_member_oid(activeSearchPath, relnamespace))
416                 visible = false;
417         else
418         {
419                 /*
420                  * If it is in the path, it might still not be visible; it could be
421                  * hidden by another relation of the same name earlier in the path. So
422                  * we must do a slow check for conflicting relations.
423                  */
424                 char       *relname = NameStr(relform->relname);
425                 ListCell   *l;
426
427                 visible = false;
428                 foreach(l, activeSearchPath)
429                 {
430                         Oid                     namespaceId = lfirst_oid(l);
431
432                         if (namespaceId == relnamespace)
433                         {
434                                 /* Found it first in path */
435                                 visible = true;
436                                 break;
437                         }
438                         if (OidIsValid(get_relname_relid(relname, namespaceId)))
439                         {
440                                 /* Found something else first in path */
441                                 break;
442                         }
443                 }
444         }
445
446         ReleaseSysCache(reltup);
447
448         return visible;
449 }
450
451
452 /*
453  * TypenameGetTypid
454  *              Try to resolve an unqualified datatype name.
455  *              Returns OID if type found in search path, else InvalidOid.
456  *
457  * This is essentially the same as RelnameGetRelid.
458  */
459 Oid
460 TypenameGetTypid(const char *typname)
461 {
462         Oid                     typid;
463         ListCell   *l;
464
465         recomputeNamespacePath();
466
467         foreach(l, activeSearchPath)
468         {
469                 Oid                     namespaceId = lfirst_oid(l);
470
471                 typid = GetSysCacheOid2(TYPENAMENSP,
472                                                                 PointerGetDatum(typname),
473                                                                 ObjectIdGetDatum(namespaceId));
474                 if (OidIsValid(typid))
475                         return typid;
476         }
477
478         /* Not found in path */
479         return InvalidOid;
480 }
481
482 /*
483  * TypeIsVisible
484  *              Determine whether a type (identified by OID) is visible in the
485  *              current search path.  Visible means "would be found by searching
486  *              for the unqualified type name".
487  */
488 bool
489 TypeIsVisible(Oid typid)
490 {
491         HeapTuple       typtup;
492         Form_pg_type typform;
493         Oid                     typnamespace;
494         bool            visible;
495
496         typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
497         if (!HeapTupleIsValid(typtup))
498                 elog(ERROR, "cache lookup failed for type %u", typid);
499         typform = (Form_pg_type) GETSTRUCT(typtup);
500
501         recomputeNamespacePath();
502
503         /*
504          * Quick check: if it ain't in the path at all, it ain't visible. Items in
505          * the system namespace are surely in the path and so we needn't even do
506          * list_member_oid() for them.
507          */
508         typnamespace = typform->typnamespace;
509         if (typnamespace != PG_CATALOG_NAMESPACE &&
510                 !list_member_oid(activeSearchPath, typnamespace))
511                 visible = false;
512         else
513         {
514                 /*
515                  * If it is in the path, it might still not be visible; it could be
516                  * hidden by another type of the same name earlier in the path. So we
517                  * must do a slow check for conflicting types.
518                  */
519                 char       *typname = NameStr(typform->typname);
520                 ListCell   *l;
521
522                 visible = false;
523                 foreach(l, activeSearchPath)
524                 {
525                         Oid                     namespaceId = lfirst_oid(l);
526
527                         if (namespaceId == typnamespace)
528                         {
529                                 /* Found it first in path */
530                                 visible = true;
531                                 break;
532                         }
533                         if (SearchSysCacheExists2(TYPENAMENSP,
534                                                                           PointerGetDatum(typname),
535                                                                           ObjectIdGetDatum(namespaceId)))
536                         {
537                                 /* Found something else first in path */
538                                 break;
539                         }
540                 }
541         }
542
543         ReleaseSysCache(typtup);
544
545         return visible;
546 }
547
548
549 /*
550  * FuncnameGetCandidates
551  *              Given a possibly-qualified function name and argument count,
552  *              retrieve a list of the possible matches.
553  *
554  * If nargs is -1, we return all functions matching the given name,
555  * regardless of argument count.  (argnames must be NIL, and expand_variadic
556  * and expand_defaults must be false, in this case.)
557  *
558  * If argnames isn't NIL, we are considering a named- or mixed-notation call,
559  * and only functions having all the listed argument names will be returned.
560  * (We assume that length(argnames) <= nargs and all the passed-in names are
561  * distinct.)  The returned structs will include an argnumbers array showing
562  * the actual argument index for each logical argument position.
563  *
564  * If expand_variadic is true, then variadic functions having the same number
565  * or fewer arguments will be retrieved, with the variadic argument and any
566  * additional argument positions filled with the variadic element type.
567  * nvargs in the returned struct is set to the number of such arguments.
568  * If expand_variadic is false, variadic arguments are not treated specially,
569  * and the returned nvargs will always be zero.
570  *
571  * If expand_defaults is true, functions that could match after insertion of
572  * default argument values will also be retrieved.      In this case the returned
573  * structs could have nargs > passed-in nargs, and ndargs is set to the number
574  * of additional args (which can be retrieved from the function's
575  * proargdefaults entry).
576  *
577  * It is not possible for nvargs and ndargs to both be nonzero in the same
578  * list entry, since default insertion allows matches to functions with more
579  * than nargs arguments while the variadic transformation requires the same
580  * number or less.
581  *
582  * When argnames isn't NIL, the returned args[] type arrays are not ordered
583  * according to the functions' declarations, but rather according to the call:
584  * first any positional arguments, then the named arguments, then defaulted
585  * arguments (if needed and allowed by expand_defaults).  The argnumbers[]
586  * array can be used to map this back to the catalog information.
587  * argnumbers[k] is set to the proargtypes index of the k'th call argument.
588  *
589  * We search a single namespace if the function name is qualified, else
590  * all namespaces in the search path.  In the multiple-namespace case,
591  * we arrange for entries in earlier namespaces to mask identical entries in
592  * later namespaces.
593  *
594  * When expanding variadics, we arrange for non-variadic functions to mask
595  * variadic ones if the expanded argument list is the same.  It is still
596  * possible for there to be conflicts between different variadic functions,
597  * however.
598  *
599  * It is guaranteed that the return list will never contain multiple entries
600  * with identical argument lists.  When expand_defaults is true, the entries
601  * could have more than nargs positions, but we still guarantee that they are
602  * distinct in the first nargs positions.  However, if argnames isn't NIL or
603  * either expand_variadic or expand_defaults is true, there might be multiple
604  * candidate functions that expand to identical argument lists.  Rather than
605  * throw error here, we report such situations by returning a single entry
606  * with oid = 0 that represents a set of such conflicting candidates.
607  * The caller might end up discarding such an entry anyway, but if it selects
608  * such an entry it should react as though the call were ambiguous.
609  */
610 FuncCandidateList
611 FuncnameGetCandidates(List *names, int nargs, List *argnames,
612                                           bool expand_variadic, bool expand_defaults)
613 {
614         FuncCandidateList resultList = NULL;
615         bool            any_special = false;
616         char       *schemaname;
617         char       *funcname;
618         Oid                     namespaceId;
619         CatCList   *catlist;
620         int                     i;
621
622         /* check for caller error */
623         Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
624
625         /* deconstruct the name list */
626         DeconstructQualifiedName(names, &schemaname, &funcname);
627
628         if (schemaname)
629         {
630                 /* use exact schema given */
631                 namespaceId = LookupExplicitNamespace(schemaname);
632         }
633         else
634         {
635                 /* flag to indicate we need namespace search */
636                 namespaceId = InvalidOid;
637                 recomputeNamespacePath();
638         }
639
640         /* Search syscache by name only */
641         catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
642
643         for (i = 0; i < catlist->n_members; i++)
644         {
645                 HeapTuple       proctup = &catlist->members[i]->tuple;
646                 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
647                 int                     pronargs = procform->pronargs;
648                 int                     effective_nargs;
649                 int                     pathpos = 0;
650                 bool            variadic;
651                 bool            use_defaults;
652                 Oid                     va_elem_type;
653                 int                *argnumbers = NULL;
654                 FuncCandidateList newResult;
655
656                 if (OidIsValid(namespaceId))
657                 {
658                         /* Consider only procs in specified namespace */
659                         if (procform->pronamespace != namespaceId)
660                                 continue;
661                 }
662                 else
663                 {
664                         /*
665                          * Consider only procs that are in the search path and are not in
666                          * the temp namespace.
667                          */
668                         ListCell   *nsp;
669
670                         foreach(nsp, activeSearchPath)
671                         {
672                                 if (procform->pronamespace == lfirst_oid(nsp) &&
673                                         procform->pronamespace != myTempNamespace)
674                                         break;
675                                 pathpos++;
676                         }
677                         if (nsp == NULL)
678                                 continue;               /* proc is not in search path */
679                 }
680
681                 if (argnames != NIL)
682                 {
683                         /*
684                          * Call uses named or mixed notation
685                          *
686                          * Named or mixed notation can match a variadic function only if
687                          * expand_variadic is off; otherwise there is no way to match the
688                          * presumed-nameless parameters expanded from the variadic array.
689                          */
690                         if (OidIsValid(procform->provariadic) && expand_variadic)
691                                 continue;
692                         va_elem_type = InvalidOid;
693                         variadic = false;
694
695                         /*
696                          * Check argument count.
697                          */
698                         Assert(nargs >= 0); /* -1 not supported with argnames */
699
700                         if (pronargs > nargs && expand_defaults)
701                         {
702                                 /* Ignore if not enough default expressions */
703                                 if (nargs + procform->pronargdefaults < pronargs)
704                                         continue;
705                                 use_defaults = true;
706                         }
707                         else
708                                 use_defaults = false;
709
710                         /* Ignore if it doesn't match requested argument count */
711                         if (pronargs != nargs && !use_defaults)
712                                 continue;
713
714                         /* Check for argument name match, generate positional mapping */
715                         if (!MatchNamedCall(proctup, nargs, argnames,
716                                                                 &argnumbers))
717                                 continue;
718
719                         /* Named argument matching is always "special" */
720                         any_special = true;
721                 }
722                 else
723                 {
724                         /*
725                          * Call uses positional notation
726                          *
727                          * Check if function is variadic, and get variadic element type if
728                          * so.  If expand_variadic is false, we should just ignore
729                          * variadic-ness.
730                          */
731                         if (pronargs <= nargs && expand_variadic)
732                         {
733                                 va_elem_type = procform->provariadic;
734                                 variadic = OidIsValid(va_elem_type);
735                                 any_special |= variadic;
736                         }
737                         else
738                         {
739                                 va_elem_type = InvalidOid;
740                                 variadic = false;
741                         }
742
743                         /*
744                          * Check if function can match by using parameter defaults.
745                          */
746                         if (pronargs > nargs && expand_defaults)
747                         {
748                                 /* Ignore if not enough default expressions */
749                                 if (nargs + procform->pronargdefaults < pronargs)
750                                         continue;
751                                 use_defaults = true;
752                                 any_special = true;
753                         }
754                         else
755                                 use_defaults = false;
756
757                         /* Ignore if it doesn't match requested argument count */
758                         if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
759                                 continue;
760                 }
761
762                 /*
763                  * We must compute the effective argument list so that we can easily
764                  * compare it to earlier results.  We waste a palloc cycle if it gets
765                  * masked by an earlier result, but really that's a pretty infrequent
766                  * case so it's not worth worrying about.
767                  */
768                 effective_nargs = Max(pronargs, nargs);
769                 newResult = (FuncCandidateList)
770                         palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
771                                    + effective_nargs * sizeof(Oid));
772                 newResult->pathpos = pathpos;
773                 newResult->oid = HeapTupleGetOid(proctup);
774                 newResult->nargs = effective_nargs;
775                 newResult->argnumbers = argnumbers;
776                 if (argnumbers)
777                 {
778                         /* Re-order the argument types into call's logical order */
779                         Oid                *proargtypes = procform->proargtypes.values;
780                         int                     i;
781
782                         for (i = 0; i < pronargs; i++)
783                                 newResult->args[i] = proargtypes[argnumbers[i]];
784                 }
785                 else
786                 {
787                         /* Simple positional case, just copy proargtypes as-is */
788                         memcpy(newResult->args, procform->proargtypes.values,
789                                    pronargs * sizeof(Oid));
790                 }
791                 if (variadic)
792                 {
793                         int                     i;
794
795                         newResult->nvargs = effective_nargs - pronargs + 1;
796                         /* Expand variadic argument into N copies of element type */
797                         for (i = pronargs - 1; i < effective_nargs; i++)
798                                 newResult->args[i] = va_elem_type;
799                 }
800                 else
801                         newResult->nvargs = 0;
802                 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
803
804                 /*
805                  * Does it have the same arguments as something we already accepted?
806                  * If so, decide what to do to avoid returning duplicate argument
807                  * lists.  We can skip this check for the single-namespace case if no
808                  * special (named, variadic or defaults) match has been made, since
809                  * then the unique index on pg_proc guarantees all the matches have
810                  * different argument lists.
811                  */
812                 if (resultList != NULL &&
813                         (any_special || !OidIsValid(namespaceId)))
814                 {
815                         /*
816                          * If we have an ordered list from SearchSysCacheList (the normal
817                          * case), then any conflicting proc must immediately adjoin this
818                          * one in the list, so we only need to look at the newest result
819                          * item.  If we have an unordered list, we have to scan the whole
820                          * result list.  Also, if either the current candidate or any
821                          * previous candidate is a special match, we can't assume that
822                          * conflicts are adjacent.
823                          *
824                          * We ignore defaulted arguments in deciding what is a match.
825                          */
826                         FuncCandidateList prevResult;
827
828                         if (catlist->ordered && !any_special)
829                         {
830                                 /* ndargs must be 0 if !any_special */
831                                 if (effective_nargs == resultList->nargs &&
832                                         memcmp(newResult->args,
833                                                    resultList->args,
834                                                    effective_nargs * sizeof(Oid)) == 0)
835                                         prevResult = resultList;
836                                 else
837                                         prevResult = NULL;
838                         }
839                         else
840                         {
841                                 int                     cmp_nargs = newResult->nargs - newResult->ndargs;
842
843                                 for (prevResult = resultList;
844                                          prevResult;
845                                          prevResult = prevResult->next)
846                                 {
847                                         if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
848                                                 memcmp(newResult->args,
849                                                            prevResult->args,
850                                                            cmp_nargs * sizeof(Oid)) == 0)
851                                                 break;
852                                 }
853                         }
854
855                         if (prevResult)
856                         {
857                                 /*
858                                  * We have a match with a previous result.      Decide which one
859                                  * to keep, or mark it ambiguous if we can't decide.  The
860                                  * logic here is preference > 0 means prefer the old result,
861                                  * preference < 0 means prefer the new, preference = 0 means
862                                  * ambiguous.
863                                  */
864                                 int                     preference;
865
866                                 if (pathpos != prevResult->pathpos)
867                                 {
868                                         /*
869                                          * Prefer the one that's earlier in the search path.
870                                          */
871                                         preference = pathpos - prevResult->pathpos;
872                                 }
873                                 else if (variadic && prevResult->nvargs == 0)
874                                 {
875                                         /*
876                                          * With variadic functions we could have, for example,
877                                          * both foo(numeric) and foo(variadic numeric[]) in the
878                                          * same namespace; if so we prefer the non-variadic match
879                                          * on efficiency grounds.
880                                          */
881                                         preference = 1;
882                                 }
883                                 else if (!variadic && prevResult->nvargs > 0)
884                                 {
885                                         preference = -1;
886                                 }
887                                 else
888                                 {
889                                         /*----------
890                                          * We can't decide.  This can happen with, for example,
891                                          * both foo(numeric, variadic numeric[]) and
892                                          * foo(variadic numeric[]) in the same namespace, or
893                                          * both foo(int) and foo (int, int default something)
894                                          * in the same namespace, or both foo(a int, b text)
895                                          * and foo(b text, a int) in the same namespace.
896                                          *----------
897                                          */
898                                         preference = 0;
899                                 }
900
901                                 if (preference > 0)
902                                 {
903                                         /* keep previous result */
904                                         pfree(newResult);
905                                         continue;
906                                 }
907                                 else if (preference < 0)
908                                 {
909                                         /* remove previous result from the list */
910                                         if (prevResult == resultList)
911                                                 resultList = prevResult->next;
912                                         else
913                                         {
914                                                 FuncCandidateList prevPrevResult;
915
916                                                 for (prevPrevResult = resultList;
917                                                          prevPrevResult;
918                                                          prevPrevResult = prevPrevResult->next)
919                                                 {
920                                                         if (prevResult == prevPrevResult->next)
921                                                         {
922                                                                 prevPrevResult->next = prevResult->next;
923                                                                 break;
924                                                         }
925                                                 }
926                                                 Assert(prevPrevResult); /* assert we found it */
927                                         }
928                                         pfree(prevResult);
929                                         /* fall through to add newResult to list */
930                                 }
931                                 else
932                                 {
933                                         /* mark old result as ambiguous, discard new */
934                                         prevResult->oid = InvalidOid;
935                                         pfree(newResult);
936                                         continue;
937                                 }
938                         }
939                 }
940
941                 /*
942                  * Okay to add it to result list
943                  */
944                 newResult->next = resultList;
945                 resultList = newResult;
946         }
947
948         ReleaseSysCacheList(catlist);
949
950         return resultList;
951 }
952
953 /*
954  * MatchNamedCall
955  *              Given a pg_proc heap tuple and a call's list of argument names,
956  *              check whether the function could match the call.
957  *
958  * The call could match if all supplied argument names are accepted by
959  * the function, in positions after the last positional argument, and there
960  * are defaults for all unsupplied arguments.
961  *
962  * The number of positional arguments is nargs - list_length(argnames).
963  * Note caller has already done basic checks on argument count.
964  *
965  * On match, return true and fill *argnumbers with a palloc'd array showing
966  * the mapping from call argument positions to actual function argument
967  * numbers.  Defaulted arguments are included in this map, at positions
968  * after the last supplied argument.
969  */
970 static bool
971 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
972                            int **argnumbers)
973 {
974         Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
975         int                     pronargs = procform->pronargs;
976         int                     numposargs = nargs - list_length(argnames);
977         int                     pronallargs;
978         Oid                *p_argtypes;
979         char      **p_argnames;
980         char       *p_argmodes;
981         bool            arggiven[FUNC_MAX_ARGS];
982         bool            isnull;
983         int                     ap;                             /* call args position */
984         int                     pp;                             /* proargs position */
985         ListCell   *lc;
986
987         Assert(argnames != NIL);
988         Assert(numposargs >= 0);
989         Assert(nargs <= pronargs);
990
991         /* Ignore this function if its proargnames is null */
992         (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
993                                                    &isnull);
994         if (isnull)
995                 return false;
996
997         /* OK, let's extract the argument names and types */
998         pronallargs = get_func_arg_info(proctup,
999                                                                         &p_argtypes, &p_argnames, &p_argmodes);
1000         Assert(p_argnames != NULL);
1001
1002         /* initialize state for matching */
1003         *argnumbers = (int *) palloc(pronargs * sizeof(int));
1004         memset(arggiven, false, pronargs * sizeof(bool));
1005
1006         /* there are numposargs positional args before the named args */
1007         for (ap = 0; ap < numposargs; ap++)
1008         {
1009                 (*argnumbers)[ap] = ap;
1010                 arggiven[ap] = true;
1011         }
1012
1013         /* now examine the named args */
1014         foreach(lc, argnames)
1015         {
1016                 char       *argname = (char *) lfirst(lc);
1017                 bool            found;
1018                 int                     i;
1019
1020                 pp = 0;
1021                 found = false;
1022                 for (i = 0; i < pronallargs; i++)
1023                 {
1024                         /* consider only input parameters */
1025                         if (p_argmodes &&
1026                                 (p_argmodes[i] != FUNC_PARAM_IN &&
1027                                  p_argmodes[i] != FUNC_PARAM_INOUT &&
1028                                  p_argmodes[i] != FUNC_PARAM_VARIADIC))
1029                                 continue;
1030                         if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1031                         {
1032                                 /* fail if argname matches a positional argument */
1033                                 if (arggiven[pp])
1034                                         return false;
1035                                 arggiven[pp] = true;
1036                                 (*argnumbers)[ap] = pp;
1037                                 found = true;
1038                                 break;
1039                         }
1040                         /* increase pp only for input parameters */
1041                         pp++;
1042                 }
1043                 /* if name isn't in proargnames, fail */
1044                 if (!found)
1045                         return false;
1046                 ap++;
1047         }
1048
1049         Assert(ap == nargs);            /* processed all actual parameters */
1050
1051         /* Check for default arguments */
1052         if (nargs < pronargs)
1053         {
1054                 int                     first_arg_with_default = pronargs - procform->pronargdefaults;
1055
1056                 for (pp = numposargs; pp < pronargs; pp++)
1057                 {
1058                         if (arggiven[pp])
1059                                 continue;
1060                         /* fail if arg not given and no default available */
1061                         if (pp < first_arg_with_default)
1062                                 return false;
1063                         (*argnumbers)[ap++] = pp;
1064                 }
1065         }
1066
1067         Assert(ap == pronargs);         /* processed all function parameters */
1068
1069         return true;
1070 }
1071
1072 /*
1073  * FunctionIsVisible
1074  *              Determine whether a function (identified by OID) is visible in the
1075  *              current search path.  Visible means "would be found by searching
1076  *              for the unqualified function name with exact argument matches".
1077  */
1078 bool
1079 FunctionIsVisible(Oid funcid)
1080 {
1081         HeapTuple       proctup;
1082         Form_pg_proc procform;
1083         Oid                     pronamespace;
1084         bool            visible;
1085
1086         proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1087         if (!HeapTupleIsValid(proctup))
1088                 elog(ERROR, "cache lookup failed for function %u", funcid);
1089         procform = (Form_pg_proc) GETSTRUCT(proctup);
1090
1091         recomputeNamespacePath();
1092
1093         /*
1094          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1095          * the system namespace are surely in the path and so we needn't even do
1096          * list_member_oid() for them.
1097          */
1098         pronamespace = procform->pronamespace;
1099         if (pronamespace != PG_CATALOG_NAMESPACE &&
1100                 !list_member_oid(activeSearchPath, pronamespace))
1101                 visible = false;
1102         else
1103         {
1104                 /*
1105                  * If it is in the path, it might still not be visible; it could be
1106                  * hidden by another proc of the same name and arguments earlier in
1107                  * the path.  So we must do a slow check to see if this is the same
1108                  * proc that would be found by FuncnameGetCandidates.
1109                  */
1110                 char       *proname = NameStr(procform->proname);
1111                 int                     nargs = procform->pronargs;
1112                 FuncCandidateList clist;
1113
1114                 visible = false;
1115
1116                 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1117                                                                           nargs, NIL, false, false);
1118
1119                 for (; clist; clist = clist->next)
1120                 {
1121                         if (memcmp(clist->args, procform->proargtypes.values,
1122                                            nargs * sizeof(Oid)) == 0)
1123                         {
1124                                 /* Found the expected entry; is it the right proc? */
1125                                 visible = (clist->oid == funcid);
1126                                 break;
1127                         }
1128                 }
1129         }
1130
1131         ReleaseSysCache(proctup);
1132
1133         return visible;
1134 }
1135
1136
1137 /*
1138  * OpernameGetOprid
1139  *              Given a possibly-qualified operator name and exact input datatypes,
1140  *              look up the operator.  Returns InvalidOid if not found.
1141  *
1142  * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1143  * a postfix op.
1144  *
1145  * If the operator name is not schema-qualified, it is sought in the current
1146  * namespace search path.
1147  */
1148 Oid
1149 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1150 {
1151         char       *schemaname;
1152         char       *opername;
1153         CatCList   *catlist;
1154         ListCell   *l;
1155
1156         /* deconstruct the name list */
1157         DeconstructQualifiedName(names, &schemaname, &opername);
1158
1159         if (schemaname)
1160         {
1161                 /* search only in exact schema given */
1162                 Oid                     namespaceId;
1163                 HeapTuple       opertup;
1164
1165                 namespaceId = LookupExplicitNamespace(schemaname);
1166                 opertup = SearchSysCache4(OPERNAMENSP,
1167                                                                   CStringGetDatum(opername),
1168                                                                   ObjectIdGetDatum(oprleft),
1169                                                                   ObjectIdGetDatum(oprright),
1170                                                                   ObjectIdGetDatum(namespaceId));
1171                 if (HeapTupleIsValid(opertup))
1172                 {
1173                         Oid                     result = HeapTupleGetOid(opertup);
1174
1175                         ReleaseSysCache(opertup);
1176                         return result;
1177                 }
1178                 return InvalidOid;
1179         }
1180
1181         /* Search syscache by name and argument types */
1182         catlist = SearchSysCacheList3(OPERNAMENSP,
1183                                                                   CStringGetDatum(opername),
1184                                                                   ObjectIdGetDatum(oprleft),
1185                                                                   ObjectIdGetDatum(oprright));
1186
1187         if (catlist->n_members == 0)
1188         {
1189                 /* no hope, fall out early */
1190                 ReleaseSysCacheList(catlist);
1191                 return InvalidOid;
1192         }
1193
1194         /*
1195          * We have to find the list member that is first in the search path, if
1196          * there's more than one.  This doubly-nested loop looks ugly, but in
1197          * practice there should usually be few catlist members.
1198          */
1199         recomputeNamespacePath();
1200
1201         foreach(l, activeSearchPath)
1202         {
1203                 Oid                     namespaceId = lfirst_oid(l);
1204                 int                     i;
1205
1206                 if (namespaceId == myTempNamespace)
1207                         continue;                       /* do not look in temp namespace */
1208
1209                 for (i = 0; i < catlist->n_members; i++)
1210                 {
1211                         HeapTuple       opertup = &catlist->members[i]->tuple;
1212                         Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1213
1214                         if (operform->oprnamespace == namespaceId)
1215                         {
1216                                 Oid                     result = HeapTupleGetOid(opertup);
1217
1218                                 ReleaseSysCacheList(catlist);
1219                                 return result;
1220                         }
1221                 }
1222         }
1223
1224         ReleaseSysCacheList(catlist);
1225         return InvalidOid;
1226 }
1227
1228 /*
1229  * OpernameGetCandidates
1230  *              Given a possibly-qualified operator name and operator kind,
1231  *              retrieve a list of the possible matches.
1232  *
1233  * If oprkind is '\0', we return all operators matching the given name,
1234  * regardless of arguments.
1235  *
1236  * We search a single namespace if the operator name is qualified, else
1237  * all namespaces in the search path.  The return list will never contain
1238  * multiple entries with identical argument lists --- in the multiple-
1239  * namespace case, we arrange for entries in earlier namespaces to mask
1240  * identical entries in later namespaces.
1241  *
1242  * The returned items always have two args[] entries --- one or the other
1243  * will be InvalidOid for a prefix or postfix oprkind.  nargs is 2, too.
1244  */
1245 FuncCandidateList
1246 OpernameGetCandidates(List *names, char oprkind)
1247 {
1248         FuncCandidateList resultList = NULL;
1249         char       *resultSpace = NULL;
1250         int                     nextResult = 0;
1251         char       *schemaname;
1252         char       *opername;
1253         Oid                     namespaceId;
1254         CatCList   *catlist;
1255         int                     i;
1256
1257         /* deconstruct the name list */
1258         DeconstructQualifiedName(names, &schemaname, &opername);
1259
1260         if (schemaname)
1261         {
1262                 /* use exact schema given */
1263                 namespaceId = LookupExplicitNamespace(schemaname);
1264         }
1265         else
1266         {
1267                 /* flag to indicate we need namespace search */
1268                 namespaceId = InvalidOid;
1269                 recomputeNamespacePath();
1270         }
1271
1272         /* Search syscache by name only */
1273         catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1274
1275         /*
1276          * In typical scenarios, most if not all of the operators found by the
1277          * catcache search will end up getting returned; and there can be quite a
1278          * few, for common operator names such as '=' or '+'.  To reduce the time
1279          * spent in palloc, we allocate the result space as an array large enough
1280          * to hold all the operators.  The original coding of this routine did a
1281          * separate palloc for each operator, but profiling revealed that the
1282          * pallocs used an unreasonably large fraction of parsing time.
1283          */
1284 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1285
1286         if (catlist->n_members > 0)
1287                 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1288
1289         for (i = 0; i < catlist->n_members; i++)
1290         {
1291                 HeapTuple       opertup = &catlist->members[i]->tuple;
1292                 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1293                 int                     pathpos = 0;
1294                 FuncCandidateList newResult;
1295
1296                 /* Ignore operators of wrong kind, if specific kind requested */
1297                 if (oprkind && operform->oprkind != oprkind)
1298                         continue;
1299
1300                 if (OidIsValid(namespaceId))
1301                 {
1302                         /* Consider only opers in specified namespace */
1303                         if (operform->oprnamespace != namespaceId)
1304                                 continue;
1305                         /* No need to check args, they must all be different */
1306                 }
1307                 else
1308                 {
1309                         /*
1310                          * Consider only opers that are in the search path and are not in
1311                          * the temp namespace.
1312                          */
1313                         ListCell   *nsp;
1314
1315                         foreach(nsp, activeSearchPath)
1316                         {
1317                                 if (operform->oprnamespace == lfirst_oid(nsp) &&
1318                                         operform->oprnamespace != myTempNamespace)
1319                                         break;
1320                                 pathpos++;
1321                         }
1322                         if (nsp == NULL)
1323                                 continue;               /* oper is not in search path */
1324
1325                         /*
1326                          * Okay, it's in the search path, but does it have the same
1327                          * arguments as something we already accepted?  If so, keep only
1328                          * the one that appears earlier in the search path.
1329                          *
1330                          * If we have an ordered list from SearchSysCacheList (the normal
1331                          * case), then any conflicting oper must immediately adjoin this
1332                          * one in the list, so we only need to look at the newest result
1333                          * item.  If we have an unordered list, we have to scan the whole
1334                          * result list.
1335                          */
1336                         if (resultList)
1337                         {
1338                                 FuncCandidateList prevResult;
1339
1340                                 if (catlist->ordered)
1341                                 {
1342                                         if (operform->oprleft == resultList->args[0] &&
1343                                                 operform->oprright == resultList->args[1])
1344                                                 prevResult = resultList;
1345                                         else
1346                                                 prevResult = NULL;
1347                                 }
1348                                 else
1349                                 {
1350                                         for (prevResult = resultList;
1351                                                  prevResult;
1352                                                  prevResult = prevResult->next)
1353                                         {
1354                                                 if (operform->oprleft == prevResult->args[0] &&
1355                                                         operform->oprright == prevResult->args[1])
1356                                                         break;
1357                                         }
1358                                 }
1359                                 if (prevResult)
1360                                 {
1361                                         /* We have a match with a previous result */
1362                                         Assert(pathpos != prevResult->pathpos);
1363                                         if (pathpos > prevResult->pathpos)
1364                                                 continue;               /* keep previous result */
1365                                         /* replace previous result */
1366                                         prevResult->pathpos = pathpos;
1367                                         prevResult->oid = HeapTupleGetOid(opertup);
1368                                         continue;       /* args are same, of course */
1369                                 }
1370                         }
1371                 }
1372
1373                 /*
1374                  * Okay to add it to result list
1375                  */
1376                 newResult = (FuncCandidateList) (resultSpace + nextResult);
1377                 nextResult += SPACE_PER_OP;
1378
1379                 newResult->pathpos = pathpos;
1380                 newResult->oid = HeapTupleGetOid(opertup);
1381                 newResult->nargs = 2;
1382                 newResult->nvargs = 0;
1383                 newResult->ndargs = 0;
1384                 newResult->argnumbers = NULL;
1385                 newResult->args[0] = operform->oprleft;
1386                 newResult->args[1] = operform->oprright;
1387                 newResult->next = resultList;
1388                 resultList = newResult;
1389         }
1390
1391         ReleaseSysCacheList(catlist);
1392
1393         return resultList;
1394 }
1395
1396 /*
1397  * OperatorIsVisible
1398  *              Determine whether an operator (identified by OID) is visible in the
1399  *              current search path.  Visible means "would be found by searching
1400  *              for the unqualified operator name with exact argument matches".
1401  */
1402 bool
1403 OperatorIsVisible(Oid oprid)
1404 {
1405         HeapTuple       oprtup;
1406         Form_pg_operator oprform;
1407         Oid                     oprnamespace;
1408         bool            visible;
1409
1410         oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1411         if (!HeapTupleIsValid(oprtup))
1412                 elog(ERROR, "cache lookup failed for operator %u", oprid);
1413         oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1414
1415         recomputeNamespacePath();
1416
1417         /*
1418          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1419          * the system namespace are surely in the path and so we needn't even do
1420          * list_member_oid() for them.
1421          */
1422         oprnamespace = oprform->oprnamespace;
1423         if (oprnamespace != PG_CATALOG_NAMESPACE &&
1424                 !list_member_oid(activeSearchPath, oprnamespace))
1425                 visible = false;
1426         else
1427         {
1428                 /*
1429                  * If it is in the path, it might still not be visible; it could be
1430                  * hidden by another operator of the same name and arguments earlier
1431                  * in the path.  So we must do a slow check to see if this is the same
1432                  * operator that would be found by OpernameGetOprId.
1433                  */
1434                 char       *oprname = NameStr(oprform->oprname);
1435
1436                 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1437                                                                         oprform->oprleft, oprform->oprright)
1438                                    == oprid);
1439         }
1440
1441         ReleaseSysCache(oprtup);
1442
1443         return visible;
1444 }
1445
1446
1447 /*
1448  * OpclassnameGetOpcid
1449  *              Try to resolve an unqualified index opclass name.
1450  *              Returns OID if opclass found in search path, else InvalidOid.
1451  *
1452  * This is essentially the same as TypenameGetTypid, but we have to have
1453  * an extra argument for the index AM OID.
1454  */
1455 Oid
1456 OpclassnameGetOpcid(Oid amid, const char *opcname)
1457 {
1458         Oid                     opcid;
1459         ListCell   *l;
1460
1461         recomputeNamespacePath();
1462
1463         foreach(l, activeSearchPath)
1464         {
1465                 Oid                     namespaceId = lfirst_oid(l);
1466
1467                 if (namespaceId == myTempNamespace)
1468                         continue;                       /* do not look in temp namespace */
1469
1470                 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1471                                                                 ObjectIdGetDatum(amid),
1472                                                                 PointerGetDatum(opcname),
1473                                                                 ObjectIdGetDatum(namespaceId));
1474                 if (OidIsValid(opcid))
1475                         return opcid;
1476         }
1477
1478         /* Not found in path */
1479         return InvalidOid;
1480 }
1481
1482 /*
1483  * OpclassIsVisible
1484  *              Determine whether an opclass (identified by OID) is visible in the
1485  *              current search path.  Visible means "would be found by searching
1486  *              for the unqualified opclass name".
1487  */
1488 bool
1489 OpclassIsVisible(Oid opcid)
1490 {
1491         HeapTuple       opctup;
1492         Form_pg_opclass opcform;
1493         Oid                     opcnamespace;
1494         bool            visible;
1495
1496         opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1497         if (!HeapTupleIsValid(opctup))
1498                 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1499         opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1500
1501         recomputeNamespacePath();
1502
1503         /*
1504          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1505          * the system namespace are surely in the path and so we needn't even do
1506          * list_member_oid() for them.
1507          */
1508         opcnamespace = opcform->opcnamespace;
1509         if (opcnamespace != PG_CATALOG_NAMESPACE &&
1510                 !list_member_oid(activeSearchPath, opcnamespace))
1511                 visible = false;
1512         else
1513         {
1514                 /*
1515                  * If it is in the path, it might still not be visible; it could be
1516                  * hidden by another opclass of the same name earlier in the path. So
1517                  * we must do a slow check to see if this opclass would be found by
1518                  * OpclassnameGetOpcid.
1519                  */
1520                 char       *opcname = NameStr(opcform->opcname);
1521
1522                 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1523         }
1524
1525         ReleaseSysCache(opctup);
1526
1527         return visible;
1528 }
1529
1530 /*
1531  * OpfamilynameGetOpfid
1532  *              Try to resolve an unqualified index opfamily name.
1533  *              Returns OID if opfamily found in search path, else InvalidOid.
1534  *
1535  * This is essentially the same as TypenameGetTypid, but we have to have
1536  * an extra argument for the index AM OID.
1537  */
1538 Oid
1539 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1540 {
1541         Oid                     opfid;
1542         ListCell   *l;
1543
1544         recomputeNamespacePath();
1545
1546         foreach(l, activeSearchPath)
1547         {
1548                 Oid                     namespaceId = lfirst_oid(l);
1549
1550                 if (namespaceId == myTempNamespace)
1551                         continue;                       /* do not look in temp namespace */
1552
1553                 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1554                                                                 ObjectIdGetDatum(amid),
1555                                                                 PointerGetDatum(opfname),
1556                                                                 ObjectIdGetDatum(namespaceId));
1557                 if (OidIsValid(opfid))
1558                         return opfid;
1559         }
1560
1561         /* Not found in path */
1562         return InvalidOid;
1563 }
1564
1565 /*
1566  * OpfamilyIsVisible
1567  *              Determine whether an opfamily (identified by OID) is visible in the
1568  *              current search path.  Visible means "would be found by searching
1569  *              for the unqualified opfamily name".
1570  */
1571 bool
1572 OpfamilyIsVisible(Oid opfid)
1573 {
1574         HeapTuple       opftup;
1575         Form_pg_opfamily opfform;
1576         Oid                     opfnamespace;
1577         bool            visible;
1578
1579         opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1580         if (!HeapTupleIsValid(opftup))
1581                 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1582         opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1583
1584         recomputeNamespacePath();
1585
1586         /*
1587          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1588          * the system namespace are surely in the path and so we needn't even do
1589          * list_member_oid() for them.
1590          */
1591         opfnamespace = opfform->opfnamespace;
1592         if (opfnamespace != PG_CATALOG_NAMESPACE &&
1593                 !list_member_oid(activeSearchPath, opfnamespace))
1594                 visible = false;
1595         else
1596         {
1597                 /*
1598                  * If it is in the path, it might still not be visible; it could be
1599                  * hidden by another opfamily of the same name earlier in the path. So
1600                  * we must do a slow check to see if this opfamily would be found by
1601                  * OpfamilynameGetOpfid.
1602                  */
1603                 char       *opfname = NameStr(opfform->opfname);
1604
1605                 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1606         }
1607
1608         ReleaseSysCache(opftup);
1609
1610         return visible;
1611 }
1612
1613 /*
1614  * ConversionGetConid
1615  *              Try to resolve an unqualified conversion name.
1616  *              Returns OID if conversion found in search path, else InvalidOid.
1617  *
1618  * This is essentially the same as RelnameGetRelid.
1619  */
1620 Oid
1621 ConversionGetConid(const char *conname)
1622 {
1623         Oid                     conid;
1624         ListCell   *l;
1625
1626         recomputeNamespacePath();
1627
1628         foreach(l, activeSearchPath)
1629         {
1630                 Oid                     namespaceId = lfirst_oid(l);
1631
1632                 if (namespaceId == myTempNamespace)
1633                         continue;                       /* do not look in temp namespace */
1634
1635                 conid = GetSysCacheOid2(CONNAMENSP,
1636                                                                 PointerGetDatum(conname),
1637                                                                 ObjectIdGetDatum(namespaceId));
1638                 if (OidIsValid(conid))
1639                         return conid;
1640         }
1641
1642         /* Not found in path */
1643         return InvalidOid;
1644 }
1645
1646 /*
1647  * ConversionIsVisible
1648  *              Determine whether a conversion (identified by OID) is visible in the
1649  *              current search path.  Visible means "would be found by searching
1650  *              for the unqualified conversion name".
1651  */
1652 bool
1653 ConversionIsVisible(Oid conid)
1654 {
1655         HeapTuple       contup;
1656         Form_pg_conversion conform;
1657         Oid                     connamespace;
1658         bool            visible;
1659
1660         contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1661         if (!HeapTupleIsValid(contup))
1662                 elog(ERROR, "cache lookup failed for conversion %u", conid);
1663         conform = (Form_pg_conversion) GETSTRUCT(contup);
1664
1665         recomputeNamespacePath();
1666
1667         /*
1668          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1669          * the system namespace are surely in the path and so we needn't even do
1670          * list_member_oid() for them.
1671          */
1672         connamespace = conform->connamespace;
1673         if (connamespace != PG_CATALOG_NAMESPACE &&
1674                 !list_member_oid(activeSearchPath, connamespace))
1675                 visible = false;
1676         else
1677         {
1678                 /*
1679                  * If it is in the path, it might still not be visible; it could be
1680                  * hidden by another conversion of the same name earlier in the path.
1681                  * So we must do a slow check to see if this conversion would be found
1682                  * by ConversionGetConid.
1683                  */
1684                 char       *conname = NameStr(conform->conname);
1685
1686                 visible = (ConversionGetConid(conname) == conid);
1687         }
1688
1689         ReleaseSysCache(contup);
1690
1691         return visible;
1692 }
1693
1694 /*
1695  * TSParserGetPrsid - find a TS parser by possibly qualified name
1696  *
1697  * If not found, returns InvalidOid if failOK, else throws error
1698  */
1699 Oid
1700 TSParserGetPrsid(List *names, bool failOK)
1701 {
1702         char       *schemaname;
1703         char       *parser_name;
1704         Oid                     namespaceId;
1705         Oid                     prsoid = InvalidOid;
1706         ListCell   *l;
1707
1708         /* deconstruct the name list */
1709         DeconstructQualifiedName(names, &schemaname, &parser_name);
1710
1711         if (schemaname)
1712         {
1713                 /* use exact schema given */
1714                 namespaceId = LookupExplicitNamespace(schemaname);
1715                 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1716                                                                  PointerGetDatum(parser_name),
1717                                                                  ObjectIdGetDatum(namespaceId));
1718         }
1719         else
1720         {
1721                 /* search for it in search path */
1722                 recomputeNamespacePath();
1723
1724                 foreach(l, activeSearchPath)
1725                 {
1726                         namespaceId = lfirst_oid(l);
1727
1728                         if (namespaceId == myTempNamespace)
1729                                 continue;               /* do not look in temp namespace */
1730
1731                         prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1732                                                                          PointerGetDatum(parser_name),
1733                                                                          ObjectIdGetDatum(namespaceId));
1734                         if (OidIsValid(prsoid))
1735                                 break;
1736                 }
1737         }
1738
1739         if (!OidIsValid(prsoid) && !failOK)
1740                 ereport(ERROR,
1741                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1742                                  errmsg("text search parser \"%s\" does not exist",
1743                                                 NameListToString(names))));
1744
1745         return prsoid;
1746 }
1747
1748 /*
1749  * TSParserIsVisible
1750  *              Determine whether a parser (identified by OID) is visible in the
1751  *              current search path.  Visible means "would be found by searching
1752  *              for the unqualified parser name".
1753  */
1754 bool
1755 TSParserIsVisible(Oid prsId)
1756 {
1757         HeapTuple       tup;
1758         Form_pg_ts_parser form;
1759         Oid                     namespace;
1760         bool            visible;
1761
1762         tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1763         if (!HeapTupleIsValid(tup))
1764                 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1765         form = (Form_pg_ts_parser) GETSTRUCT(tup);
1766
1767         recomputeNamespacePath();
1768
1769         /*
1770          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1771          * the system namespace are surely in the path and so we needn't even do
1772          * list_member_oid() for them.
1773          */
1774         namespace = form->prsnamespace;
1775         if (namespace != PG_CATALOG_NAMESPACE &&
1776                 !list_member_oid(activeSearchPath, namespace))
1777                 visible = false;
1778         else
1779         {
1780                 /*
1781                  * If it is in the path, it might still not be visible; it could be
1782                  * hidden by another parser of the same name earlier in the path. So
1783                  * we must do a slow check for conflicting parsers.
1784                  */
1785                 char       *name = NameStr(form->prsname);
1786                 ListCell   *l;
1787
1788                 visible = false;
1789                 foreach(l, activeSearchPath)
1790                 {
1791                         Oid                     namespaceId = lfirst_oid(l);
1792
1793                         if (namespaceId == myTempNamespace)
1794                                 continue;               /* do not look in temp namespace */
1795
1796                         if (namespaceId == namespace)
1797                         {
1798                                 /* Found it first in path */
1799                                 visible = true;
1800                                 break;
1801                         }
1802                         if (SearchSysCacheExists2(TSPARSERNAMENSP,
1803                                                                           PointerGetDatum(name),
1804                                                                           ObjectIdGetDatum(namespaceId)))
1805                         {
1806                                 /* Found something else first in path */
1807                                 break;
1808                         }
1809                 }
1810         }
1811
1812         ReleaseSysCache(tup);
1813
1814         return visible;
1815 }
1816
1817 /*
1818  * TSDictionaryGetDictid - find a TS dictionary by possibly qualified name
1819  *
1820  * If not found, returns InvalidOid if failOK, else throws error
1821  */
1822 Oid
1823 TSDictionaryGetDictid(List *names, bool failOK)
1824 {
1825         char       *schemaname;
1826         char       *dict_name;
1827         Oid                     namespaceId;
1828         Oid                     dictoid = InvalidOid;
1829         ListCell   *l;
1830
1831         /* deconstruct the name list */
1832         DeconstructQualifiedName(names, &schemaname, &dict_name);
1833
1834         if (schemaname)
1835         {
1836                 /* use exact schema given */
1837                 namespaceId = LookupExplicitNamespace(schemaname);
1838                 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1839                                                                   PointerGetDatum(dict_name),
1840                                                                   ObjectIdGetDatum(namespaceId));
1841         }
1842         else
1843         {
1844                 /* search for it in search path */
1845                 recomputeNamespacePath();
1846
1847                 foreach(l, activeSearchPath)
1848                 {
1849                         namespaceId = lfirst_oid(l);
1850
1851                         if (namespaceId == myTempNamespace)
1852                                 continue;               /* do not look in temp namespace */
1853
1854                         dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1855                                                                           PointerGetDatum(dict_name),
1856                                                                           ObjectIdGetDatum(namespaceId));
1857                         if (OidIsValid(dictoid))
1858                                 break;
1859                 }
1860         }
1861
1862         if (!OidIsValid(dictoid) && !failOK)
1863                 ereport(ERROR,
1864                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1865                                  errmsg("text search dictionary \"%s\" does not exist",
1866                                                 NameListToString(names))));
1867
1868         return dictoid;
1869 }
1870
1871 /*
1872  * TSDictionaryIsVisible
1873  *              Determine whether a dictionary (identified by OID) is visible in the
1874  *              current search path.  Visible means "would be found by searching
1875  *              for the unqualified dictionary name".
1876  */
1877 bool
1878 TSDictionaryIsVisible(Oid dictId)
1879 {
1880         HeapTuple       tup;
1881         Form_pg_ts_dict form;
1882         Oid                     namespace;
1883         bool            visible;
1884
1885         tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
1886         if (!HeapTupleIsValid(tup))
1887                 elog(ERROR, "cache lookup failed for text search dictionary %u",
1888                          dictId);
1889         form = (Form_pg_ts_dict) GETSTRUCT(tup);
1890
1891         recomputeNamespacePath();
1892
1893         /*
1894          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1895          * the system namespace are surely in the path and so we needn't even do
1896          * list_member_oid() for them.
1897          */
1898         namespace = form->dictnamespace;
1899         if (namespace != PG_CATALOG_NAMESPACE &&
1900                 !list_member_oid(activeSearchPath, namespace))
1901                 visible = false;
1902         else
1903         {
1904                 /*
1905                  * If it is in the path, it might still not be visible; it could be
1906                  * hidden by another dictionary of the same name earlier in the path.
1907                  * So we must do a slow check for conflicting dictionaries.
1908                  */
1909                 char       *name = NameStr(form->dictname);
1910                 ListCell   *l;
1911
1912                 visible = false;
1913                 foreach(l, activeSearchPath)
1914                 {
1915                         Oid                     namespaceId = lfirst_oid(l);
1916
1917                         if (namespaceId == myTempNamespace)
1918                                 continue;               /* do not look in temp namespace */
1919
1920                         if (namespaceId == namespace)
1921                         {
1922                                 /* Found it first in path */
1923                                 visible = true;
1924                                 break;
1925                         }
1926                         if (SearchSysCacheExists2(TSDICTNAMENSP,
1927                                                                           PointerGetDatum(name),
1928                                                                           ObjectIdGetDatum(namespaceId)))
1929                         {
1930                                 /* Found something else first in path */
1931                                 break;
1932                         }
1933                 }
1934         }
1935
1936         ReleaseSysCache(tup);
1937
1938         return visible;
1939 }
1940
1941 /*
1942  * TSTemplateGetTmplid - find a TS template by possibly qualified name
1943  *
1944  * If not found, returns InvalidOid if failOK, else throws error
1945  */
1946 Oid
1947 TSTemplateGetTmplid(List *names, bool failOK)
1948 {
1949         char       *schemaname;
1950         char       *template_name;
1951         Oid                     namespaceId;
1952         Oid                     tmploid = InvalidOid;
1953         ListCell   *l;
1954
1955         /* deconstruct the name list */
1956         DeconstructQualifiedName(names, &schemaname, &template_name);
1957
1958         if (schemaname)
1959         {
1960                 /* use exact schema given */
1961                 namespaceId = LookupExplicitNamespace(schemaname);
1962                 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1963                                                                   PointerGetDatum(template_name),
1964                                                                   ObjectIdGetDatum(namespaceId));
1965         }
1966         else
1967         {
1968                 /* search for it in search path */
1969                 recomputeNamespacePath();
1970
1971                 foreach(l, activeSearchPath)
1972                 {
1973                         namespaceId = lfirst_oid(l);
1974
1975                         if (namespaceId == myTempNamespace)
1976                                 continue;               /* do not look in temp namespace */
1977
1978                         tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1979                                                                           PointerGetDatum(template_name),
1980                                                                           ObjectIdGetDatum(namespaceId));
1981                         if (OidIsValid(tmploid))
1982                                 break;
1983                 }
1984         }
1985
1986         if (!OidIsValid(tmploid) && !failOK)
1987                 ereport(ERROR,
1988                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1989                                  errmsg("text search template \"%s\" does not exist",
1990                                                 NameListToString(names))));
1991
1992         return tmploid;
1993 }
1994
1995 /*
1996  * TSTemplateIsVisible
1997  *              Determine whether a template (identified by OID) is visible in the
1998  *              current search path.  Visible means "would be found by searching
1999  *              for the unqualified template name".
2000  */
2001 bool
2002 TSTemplateIsVisible(Oid tmplId)
2003 {
2004         HeapTuple       tup;
2005         Form_pg_ts_template form;
2006         Oid                     namespace;
2007         bool            visible;
2008
2009         tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2010         if (!HeapTupleIsValid(tup))
2011                 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2012         form = (Form_pg_ts_template) GETSTRUCT(tup);
2013
2014         recomputeNamespacePath();
2015
2016         /*
2017          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2018          * the system namespace are surely in the path and so we needn't even do
2019          * list_member_oid() for them.
2020          */
2021         namespace = form->tmplnamespace;
2022         if (namespace != PG_CATALOG_NAMESPACE &&
2023                 !list_member_oid(activeSearchPath, namespace))
2024                 visible = false;
2025         else
2026         {
2027                 /*
2028                  * If it is in the path, it might still not be visible; it could be
2029                  * hidden by another template of the same name earlier in the path. So
2030                  * we must do a slow check for conflicting templates.
2031                  */
2032                 char       *name = NameStr(form->tmplname);
2033                 ListCell   *l;
2034
2035                 visible = false;
2036                 foreach(l, activeSearchPath)
2037                 {
2038                         Oid                     namespaceId = lfirst_oid(l);
2039
2040                         if (namespaceId == myTempNamespace)
2041                                 continue;               /* do not look in temp namespace */
2042
2043                         if (namespaceId == namespace)
2044                         {
2045                                 /* Found it first in path */
2046                                 visible = true;
2047                                 break;
2048                         }
2049                         if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2050                                                                           PointerGetDatum(name),
2051                                                                           ObjectIdGetDatum(namespaceId)))
2052                         {
2053                                 /* Found something else first in path */
2054                                 break;
2055                         }
2056                 }
2057         }
2058
2059         ReleaseSysCache(tup);
2060
2061         return visible;
2062 }
2063
2064 /*
2065  * TSConfigGetCfgid - find a TS config by possibly qualified name
2066  *
2067  * If not found, returns InvalidOid if failOK, else throws error
2068  */
2069 Oid
2070 TSConfigGetCfgid(List *names, bool failOK)
2071 {
2072         char       *schemaname;
2073         char       *config_name;
2074         Oid                     namespaceId;
2075         Oid                     cfgoid = InvalidOid;
2076         ListCell   *l;
2077
2078         /* deconstruct the name list */
2079         DeconstructQualifiedName(names, &schemaname, &config_name);
2080
2081         if (schemaname)
2082         {
2083                 /* use exact schema given */
2084                 namespaceId = LookupExplicitNamespace(schemaname);
2085                 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2086                                                                  PointerGetDatum(config_name),
2087                                                                  ObjectIdGetDatum(namespaceId));
2088         }
2089         else
2090         {
2091                 /* search for it in search path */
2092                 recomputeNamespacePath();
2093
2094                 foreach(l, activeSearchPath)
2095                 {
2096                         namespaceId = lfirst_oid(l);
2097
2098                         if (namespaceId == myTempNamespace)
2099                                 continue;               /* do not look in temp namespace */
2100
2101                         cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2102                                                                          PointerGetDatum(config_name),
2103                                                                          ObjectIdGetDatum(namespaceId));
2104                         if (OidIsValid(cfgoid))
2105                                 break;
2106                 }
2107         }
2108
2109         if (!OidIsValid(cfgoid) && !failOK)
2110                 ereport(ERROR,
2111                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2112                                  errmsg("text search configuration \"%s\" does not exist",
2113                                                 NameListToString(names))));
2114
2115         return cfgoid;
2116 }
2117
2118 /*
2119  * TSConfigIsVisible
2120  *              Determine whether a text search configuration (identified by OID)
2121  *              is visible in the current search path.  Visible means "would be found
2122  *              by searching for the unqualified text search configuration name".
2123  */
2124 bool
2125 TSConfigIsVisible(Oid cfgid)
2126 {
2127         HeapTuple       tup;
2128         Form_pg_ts_config form;
2129         Oid                     namespace;
2130         bool            visible;
2131
2132         tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2133         if (!HeapTupleIsValid(tup))
2134                 elog(ERROR, "cache lookup failed for text search configuration %u",
2135                          cfgid);
2136         form = (Form_pg_ts_config) GETSTRUCT(tup);
2137
2138         recomputeNamespacePath();
2139
2140         /*
2141          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2142          * the system namespace are surely in the path and so we needn't even do
2143          * list_member_oid() for them.
2144          */
2145         namespace = form->cfgnamespace;
2146         if (namespace != PG_CATALOG_NAMESPACE &&
2147                 !list_member_oid(activeSearchPath, namespace))
2148                 visible = false;
2149         else
2150         {
2151                 /*
2152                  * If it is in the path, it might still not be visible; it could be
2153                  * hidden by another configuration of the same name earlier in the
2154                  * path. So we must do a slow check for conflicting configurations.
2155                  */
2156                 char       *name = NameStr(form->cfgname);
2157                 ListCell   *l;
2158
2159                 visible = false;
2160                 foreach(l, activeSearchPath)
2161                 {
2162                         Oid                     namespaceId = lfirst_oid(l);
2163
2164                         if (namespaceId == myTempNamespace)
2165                                 continue;               /* do not look in temp namespace */
2166
2167                         if (namespaceId == namespace)
2168                         {
2169                                 /* Found it first in path */
2170                                 visible = true;
2171                                 break;
2172                         }
2173                         if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2174                                                                           PointerGetDatum(name),
2175                                                                           ObjectIdGetDatum(namespaceId)))
2176                         {
2177                                 /* Found something else first in path */
2178                                 break;
2179                         }
2180                 }
2181         }
2182
2183         ReleaseSysCache(tup);
2184
2185         return visible;
2186 }
2187
2188
2189 /*
2190  * DeconstructQualifiedName
2191  *              Given a possibly-qualified name expressed as a list of String nodes,
2192  *              extract the schema name and object name.
2193  *
2194  * *nspname_p is set to NULL if there is no explicit schema name.
2195  */
2196 void
2197 DeconstructQualifiedName(List *names,
2198                                                  char **nspname_p,
2199                                                  char **objname_p)
2200 {
2201         char       *catalogname;
2202         char       *schemaname = NULL;
2203         char       *objname = NULL;
2204
2205         switch (list_length(names))
2206         {
2207                 case 1:
2208                         objname = strVal(linitial(names));
2209                         break;
2210                 case 2:
2211                         schemaname = strVal(linitial(names));
2212                         objname = strVal(lsecond(names));
2213                         break;
2214                 case 3:
2215                         catalogname = strVal(linitial(names));
2216                         schemaname = strVal(lsecond(names));
2217                         objname = strVal(lthird(names));
2218
2219                         /*
2220                          * We check the catalog name and then ignore it.
2221                          */
2222                         if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2223                                 ereport(ERROR,
2224                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2225                                   errmsg("cross-database references are not implemented: %s",
2226                                                  NameListToString(names))));
2227                         break;
2228                 default:
2229                         ereport(ERROR,
2230                                         (errcode(ERRCODE_SYNTAX_ERROR),
2231                                 errmsg("improper qualified name (too many dotted names): %s",
2232                                            NameListToString(names))));
2233                         break;
2234         }
2235
2236         *nspname_p = schemaname;
2237         *objname_p = objname;
2238 }
2239
2240 /*
2241  * LookupNamespaceNoError
2242  *              Look up a schema name.
2243  *
2244  * Returns the namespace OID, or InvalidOid if not found.
2245  *
2246  * Note this does NOT perform any permissions check --- callers are
2247  * responsible for being sure that an appropriate check is made.
2248  * In the majority of cases LookupExplicitNamespace is preferable.
2249  */
2250 Oid
2251 LookupNamespaceNoError(const char *nspname)
2252 {
2253         /* check for pg_temp alias */
2254         if (strcmp(nspname, "pg_temp") == 0)
2255         {
2256                 if (OidIsValid(myTempNamespace))
2257                         return myTempNamespace;
2258
2259                 /*
2260                  * Since this is used only for looking up existing objects, there is
2261                  * no point in trying to initialize the temp namespace here; and doing
2262                  * so might create problems for some callers. Just report "not found".
2263                  */
2264                 return InvalidOid;
2265         }
2266
2267         return get_namespace_oid(nspname, true);
2268 }
2269
2270 /*
2271  * LookupExplicitNamespace
2272  *              Process an explicitly-specified schema name: look up the schema
2273  *              and verify we have USAGE (lookup) rights in it.
2274  *
2275  * Returns the namespace OID.  Raises ereport if any problem.
2276  */
2277 Oid
2278 LookupExplicitNamespace(const char *nspname)
2279 {
2280         Oid                     namespaceId;
2281         AclResult       aclresult;
2282
2283         /* check for pg_temp alias */
2284         if (strcmp(nspname, "pg_temp") == 0)
2285         {
2286                 if (OidIsValid(myTempNamespace))
2287                         return myTempNamespace;
2288
2289                 /*
2290                  * Since this is used only for looking up existing objects, there is
2291                  * no point in trying to initialize the temp namespace here; and doing
2292                  * so might create problems for some callers. Just fall through and
2293                  * give the "does not exist" error.
2294                  */
2295         }
2296
2297         namespaceId = get_namespace_oid(nspname, false);
2298
2299         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2300         if (aclresult != ACLCHECK_OK)
2301                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2302                                            nspname);
2303
2304         return namespaceId;
2305 }
2306
2307 /*
2308  * LookupCreationNamespace
2309  *              Look up the schema and verify we have CREATE rights on it.
2310  *
2311  * This is just like LookupExplicitNamespace except for the different
2312  * permission check, and that we are willing to create pg_temp if needed.
2313  *
2314  * Note: calling this may result in a CommandCounterIncrement operation,
2315  * if we have to create or clean out the temp namespace.
2316  */
2317 Oid
2318 LookupCreationNamespace(const char *nspname)
2319 {
2320         Oid                     namespaceId;
2321         AclResult       aclresult;
2322
2323         /* check for pg_temp alias */
2324         if (strcmp(nspname, "pg_temp") == 0)
2325         {
2326                 /* Initialize temp namespace if first time through */
2327                 if (!OidIsValid(myTempNamespace))
2328                         InitTempTableNamespace();
2329                 return myTempNamespace;
2330         }
2331
2332         namespaceId = get_namespace_oid(nspname, false);
2333
2334         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2335         if (aclresult != ACLCHECK_OK)
2336                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2337                                            nspname);
2338
2339         return namespaceId;
2340 }
2341
2342 /*
2343  * QualifiedNameGetCreationNamespace
2344  *              Given a possibly-qualified name for an object (in List-of-Values
2345  *              format), determine what namespace the object should be created in.
2346  *              Also extract and return the object name (last component of list).
2347  *
2348  * Note: this does not apply any permissions check.  Callers must check
2349  * for CREATE rights on the selected namespace when appropriate.
2350  *
2351  * Note: calling this may result in a CommandCounterIncrement operation,
2352  * if we have to create or clean out the temp namespace.
2353  */
2354 Oid
2355 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2356 {
2357         char       *schemaname;
2358         Oid                     namespaceId;
2359
2360         /* deconstruct the name list */
2361         DeconstructQualifiedName(names, &schemaname, objname_p);
2362
2363         if (schemaname)
2364         {
2365                 /* check for pg_temp alias */
2366                 if (strcmp(schemaname, "pg_temp") == 0)
2367                 {
2368                         /* Initialize temp namespace if first time through */
2369                         if (!OidIsValid(myTempNamespace))
2370                                 InitTempTableNamespace();
2371                         return myTempNamespace;
2372                 }
2373                 /* use exact schema given */
2374                 namespaceId = get_namespace_oid(schemaname, false);
2375                 /* we do not check for USAGE rights here! */
2376         }
2377         else
2378         {
2379                 /* use the default creation namespace */
2380                 recomputeNamespacePath();
2381                 if (activeTempCreationPending)
2382                 {
2383                         /* Need to initialize temp namespace */
2384                         InitTempTableNamespace();
2385                         return myTempNamespace;
2386                 }
2387                 namespaceId = activeCreationNamespace;
2388                 if (!OidIsValid(namespaceId))
2389                         ereport(ERROR,
2390                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
2391                                          errmsg("no schema has been selected to create in")));
2392         }
2393
2394         return namespaceId;
2395 }
2396
2397 /*
2398  * get_namespace_oid - given a namespace name, look up the OID
2399  *
2400  * If missing_ok is false, throw an error if namespace name not found.  If
2401  * true, just return InvalidOid.
2402  */
2403 Oid
2404 get_namespace_oid(const char *nspname, bool missing_ok)
2405 {
2406         Oid                     oid;
2407
2408         oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2409         if (!OidIsValid(oid) && !missing_ok)
2410         ereport(ERROR,
2411                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2412                  errmsg("schema \"%s\" does not exist", nspname)));
2413
2414         return oid;
2415 }
2416
2417 /*
2418  * makeRangeVarFromNameList
2419  *              Utility routine to convert a qualified-name list into RangeVar form.
2420  */
2421 RangeVar *
2422 makeRangeVarFromNameList(List *names)
2423 {
2424         RangeVar   *rel = makeRangeVar(NULL, NULL, -1);
2425
2426         switch (list_length(names))
2427         {
2428                 case 1:
2429                         rel->relname = strVal(linitial(names));
2430                         break;
2431                 case 2:
2432                         rel->schemaname = strVal(linitial(names));
2433                         rel->relname = strVal(lsecond(names));
2434                         break;
2435                 case 3:
2436                         rel->catalogname = strVal(linitial(names));
2437                         rel->schemaname = strVal(lsecond(names));
2438                         rel->relname = strVal(lthird(names));
2439                         break;
2440                 default:
2441                         ereport(ERROR,
2442                                         (errcode(ERRCODE_SYNTAX_ERROR),
2443                                  errmsg("improper relation name (too many dotted names): %s",
2444                                                 NameListToString(names))));
2445                         break;
2446         }
2447
2448         return rel;
2449 }
2450
2451 /*
2452  * NameListToString
2453  *              Utility routine to convert a qualified-name list into a string.
2454  *
2455  * This is used primarily to form error messages, and so we do not quote
2456  * the list elements, for the sake of legibility.
2457  *
2458  * In most scenarios the list elements should always be Value strings,
2459  * but we also allow A_Star for the convenience of ColumnRef processing.
2460  */
2461 char *
2462 NameListToString(List *names)
2463 {
2464         StringInfoData string;
2465         ListCell   *l;
2466
2467         initStringInfo(&string);
2468
2469         foreach(l, names)
2470         {
2471                 Node       *name = (Node *) lfirst(l);
2472
2473                 if (l != list_head(names))
2474                         appendStringInfoChar(&string, '.');
2475
2476                 if (IsA(name, String))
2477                         appendStringInfoString(&string, strVal(name));
2478                 else if (IsA(name, A_Star))
2479                         appendStringInfoString(&string, "*");
2480                 else
2481                         elog(ERROR, "unexpected node type in name list: %d",
2482                                  (int) nodeTag(name));
2483         }
2484
2485         return string.data;
2486 }
2487
2488 /*
2489  * NameListToQuotedString
2490  *              Utility routine to convert a qualified-name list into a string.
2491  *
2492  * Same as above except that names will be double-quoted where necessary,
2493  * so the string could be re-parsed (eg, by textToQualifiedNameList).
2494  */
2495 char *
2496 NameListToQuotedString(List *names)
2497 {
2498         StringInfoData string;
2499         ListCell   *l;
2500
2501         initStringInfo(&string);
2502
2503         foreach(l, names)
2504         {
2505                 if (l != list_head(names))
2506                         appendStringInfoChar(&string, '.');
2507                 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2508         }
2509
2510         return string.data;
2511 }
2512
2513 /*
2514  * isTempNamespace - is the given namespace my temporary-table namespace?
2515  */
2516 bool
2517 isTempNamespace(Oid namespaceId)
2518 {
2519         if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2520                 return true;
2521         return false;
2522 }
2523
2524 /*
2525  * isTempToastNamespace - is the given namespace my temporary-toast-table
2526  *              namespace?
2527  */
2528 bool
2529 isTempToastNamespace(Oid namespaceId)
2530 {
2531         if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2532                 return true;
2533         return false;
2534 }
2535
2536 /*
2537  * isTempOrToastNamespace - is the given namespace my temporary-table
2538  *              namespace or my temporary-toast-table namespace?
2539  */
2540 bool
2541 isTempOrToastNamespace(Oid namespaceId)
2542 {
2543         if (OidIsValid(myTempNamespace) &&
2544          (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2545                 return true;
2546         return false;
2547 }
2548
2549 /*
2550  * isAnyTempNamespace - is the given namespace a temporary-table namespace
2551  * (either my own, or another backend's)?  Temporary-toast-table namespaces
2552  * are included, too.
2553  */
2554 bool
2555 isAnyTempNamespace(Oid namespaceId)
2556 {
2557         bool            result;
2558         char       *nspname;
2559
2560         /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2561         nspname = get_namespace_name(namespaceId);
2562         if (!nspname)
2563                 return false;                   /* no such namespace? */
2564         result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2565                 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2566         pfree(nspname);
2567         return result;
2568 }
2569
2570 /*
2571  * isOtherTempNamespace - is the given namespace some other backend's
2572  * temporary-table namespace (including temporary-toast-table namespaces)?
2573  *
2574  * Note: for most purposes in the C code, this function is obsolete.  Use
2575  * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2576  */
2577 bool
2578 isOtherTempNamespace(Oid namespaceId)
2579 {
2580         /* If it's my own temp namespace, say "false" */
2581         if (isTempOrToastNamespace(namespaceId))
2582                 return false;
2583         /* Else, if it's any temp namespace, say "true" */
2584         return isAnyTempNamespace(namespaceId);
2585 }
2586
2587 /*
2588  * GetTempNamespaceBackendId - if the given namespace is a temporary-table
2589  * namespace (either my own, or another backend's), return the BackendId
2590  * that owns it.  Temporary-toast-table namespaces are included, too.
2591  * If it isn't a temp namespace, return -1.
2592  */
2593 int
2594 GetTempNamespaceBackendId(Oid namespaceId)
2595 {
2596         int                     result;
2597         char       *nspname;
2598
2599         /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2600         nspname = get_namespace_name(namespaceId);
2601         if (!nspname)
2602                 return -1;                              /* no such namespace? */
2603         if (strncmp(nspname, "pg_temp_", 8) == 0)
2604                 result = atoi(nspname + 8);
2605         else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
2606                 result = atoi(nspname + 14);
2607         else
2608                 result = -1;
2609         pfree(nspname);
2610         return result;
2611 }
2612
2613 /*
2614  * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
2615  * which must already be assigned.      (This is only used when creating a toast
2616  * table for a temp table, so we must have already done InitTempTableNamespace)
2617  */
2618 Oid
2619 GetTempToastNamespace(void)
2620 {
2621         Assert(OidIsValid(myTempToastNamespace));
2622         return myTempToastNamespace;
2623 }
2624
2625
2626 /*
2627  * GetOverrideSearchPath - fetch current search path definition in form
2628  * used by PushOverrideSearchPath.
2629  *
2630  * The result structure is allocated in the specified memory context
2631  * (which might or might not be equal to CurrentMemoryContext); but any
2632  * junk created by revalidation calculations will be in CurrentMemoryContext.
2633  */
2634 OverrideSearchPath *
2635 GetOverrideSearchPath(MemoryContext context)
2636 {
2637         OverrideSearchPath *result;
2638         List       *schemas;
2639         MemoryContext oldcxt;
2640
2641         recomputeNamespacePath();
2642
2643         oldcxt = MemoryContextSwitchTo(context);
2644
2645         result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
2646         schemas = list_copy(activeSearchPath);
2647         while (schemas && linitial_oid(schemas) != activeCreationNamespace)
2648         {
2649                 if (linitial_oid(schemas) == myTempNamespace)
2650                         result->addTemp = true;
2651                 else
2652                 {
2653                         Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
2654                         result->addCatalog = true;
2655                 }
2656                 schemas = list_delete_first(schemas);
2657         }
2658         result->schemas = schemas;
2659
2660         MemoryContextSwitchTo(oldcxt);
2661
2662         return result;
2663 }
2664
2665 /*
2666  * PushOverrideSearchPath - temporarily override the search path
2667  *
2668  * We allow nested overrides, hence the push/pop terminology.  The GUC
2669  * search_path variable is ignored while an override is active.
2670  */
2671 void
2672 PushOverrideSearchPath(OverrideSearchPath *newpath)
2673 {
2674         OverrideStackEntry *entry;
2675         List       *oidlist;
2676         Oid                     firstNS;
2677         MemoryContext oldcxt;
2678
2679         /*
2680          * Copy the list for safekeeping, and insert implicitly-searched
2681          * namespaces as needed.  This code should track recomputeNamespacePath.
2682          */
2683         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2684
2685         oidlist = list_copy(newpath->schemas);
2686
2687         /*
2688          * Remember the first member of the explicit list.
2689          */
2690         if (oidlist == NIL)
2691                 firstNS = InvalidOid;
2692         else
2693                 firstNS = linitial_oid(oidlist);
2694
2695         /*
2696          * Add any implicitly-searched namespaces to the list.  Note these go on
2697          * the front, not the back; also notice that we do not check USAGE
2698          * permissions for these.
2699          */
2700         if (newpath->addCatalog)
2701                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2702
2703         if (newpath->addTemp)
2704         {
2705                 Assert(OidIsValid(myTempNamespace));
2706                 oidlist = lcons_oid(myTempNamespace, oidlist);
2707         }
2708
2709         /*
2710          * Build the new stack entry, then insert it at the head of the list.
2711          */
2712         entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
2713         entry->searchPath = oidlist;
2714         entry->creationNamespace = firstNS;
2715         entry->nestLevel = GetCurrentTransactionNestLevel();
2716
2717         overrideStack = lcons(entry, overrideStack);
2718
2719         /* And make it active. */
2720         activeSearchPath = entry->searchPath;
2721         activeCreationNamespace = entry->creationNamespace;
2722         activeTempCreationPending = false;      /* XXX is this OK? */
2723
2724         MemoryContextSwitchTo(oldcxt);
2725 }
2726
2727 /*
2728  * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
2729  *
2730  * Any push during a (sub)transaction will be popped automatically at abort.
2731  * But it's caller error if a push isn't popped in normal control flow.
2732  */
2733 void
2734 PopOverrideSearchPath(void)
2735 {
2736         OverrideStackEntry *entry;
2737
2738         /* Sanity checks. */
2739         if (overrideStack == NIL)
2740                 elog(ERROR, "bogus PopOverrideSearchPath call");
2741         entry = (OverrideStackEntry *) linitial(overrideStack);
2742         if (entry->nestLevel != GetCurrentTransactionNestLevel())
2743                 elog(ERROR, "bogus PopOverrideSearchPath call");
2744
2745         /* Pop the stack and free storage. */
2746         overrideStack = list_delete_first(overrideStack);
2747         list_free(entry->searchPath);
2748         pfree(entry);
2749
2750         /* Activate the next level down. */
2751         if (overrideStack)
2752         {
2753                 entry = (OverrideStackEntry *) linitial(overrideStack);
2754                 activeSearchPath = entry->searchPath;
2755                 activeCreationNamespace = entry->creationNamespace;
2756                 activeTempCreationPending = false;              /* XXX is this OK? */
2757         }
2758         else
2759         {
2760                 /* If not baseSearchPathValid, this is useless but harmless */
2761                 activeSearchPath = baseSearchPath;
2762                 activeCreationNamespace = baseCreationNamespace;
2763                 activeTempCreationPending = baseTempCreationPending;
2764         }
2765 }
2766
2767
2768 /*
2769  * FindConversionByName - find a conversion by possibly qualified name
2770  */
2771 Oid
2772 FindConversionByName(List *name)
2773 {
2774         char       *schemaname;
2775         char       *conversion_name;
2776         Oid                     namespaceId;
2777         Oid                     conoid;
2778         ListCell   *l;
2779
2780         /* deconstruct the name list */
2781         DeconstructQualifiedName(name, &schemaname, &conversion_name);
2782
2783         if (schemaname)
2784         {
2785                 /* use exact schema given */
2786                 namespaceId = LookupExplicitNamespace(schemaname);
2787                 return GetSysCacheOid2(CONNAMENSP,
2788                                                            PointerGetDatum(conversion_name),
2789                                                            ObjectIdGetDatum(namespaceId));
2790         }
2791         else
2792         {
2793                 /* search for it in search path */
2794                 recomputeNamespacePath();
2795
2796                 foreach(l, activeSearchPath)
2797                 {
2798                         namespaceId = lfirst_oid(l);
2799
2800                         if (namespaceId == myTempNamespace)
2801                                 continue;               /* do not look in temp namespace */
2802
2803                         conoid = GetSysCacheOid2(CONNAMENSP,
2804                                                                          PointerGetDatum(conversion_name),
2805                                                                          ObjectIdGetDatum(namespaceId));
2806                         if (OidIsValid(conoid))
2807                                 return conoid;
2808                 }
2809         }
2810
2811         /* Not found in path */
2812         return InvalidOid;
2813 }
2814
2815 /*
2816  * FindDefaultConversionProc - find default encoding conversion proc
2817  */
2818 Oid
2819 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
2820 {
2821         Oid                     proc;
2822         ListCell   *l;
2823
2824         recomputeNamespacePath();
2825
2826         foreach(l, activeSearchPath)
2827         {
2828                 Oid                     namespaceId = lfirst_oid(l);
2829
2830                 if (namespaceId == myTempNamespace)
2831                         continue;                       /* do not look in temp namespace */
2832
2833                 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
2834                 if (OidIsValid(proc))
2835                         return proc;
2836         }
2837
2838         /* Not found in path */
2839         return InvalidOid;
2840 }
2841
2842 /*
2843  * recomputeNamespacePath - recompute path derived variables if needed.
2844  */
2845 static void
2846 recomputeNamespacePath(void)
2847 {
2848         Oid                     roleid = GetUserId();
2849         char       *rawname;
2850         List       *namelist;
2851         List       *oidlist;
2852         List       *newpath;
2853         ListCell   *l;
2854         bool            temp_missing;
2855         Oid                     firstNS;
2856         MemoryContext oldcxt;
2857
2858         /* Do nothing if an override search spec is active. */
2859         if (overrideStack)
2860                 return;
2861
2862         /* Do nothing if path is already valid. */
2863         if (baseSearchPathValid && namespaceUser == roleid)
2864                 return;
2865
2866         /* Need a modifiable copy of namespace_search_path string */
2867         rawname = pstrdup(namespace_search_path);
2868
2869         /* Parse string into list of identifiers */
2870         if (!SplitIdentifierString(rawname, ',', &namelist))
2871         {
2872                 /* syntax error in name list */
2873                 /* this should not happen if GUC checked check_search_path */
2874                 elog(ERROR, "invalid list syntax");
2875         }
2876
2877         /*
2878          * Convert the list of names to a list of OIDs.  If any names are not
2879          * recognizable or we don't have read access, just leave them out of the
2880          * list.  (We can't raise an error, since the search_path setting has
2881          * already been accepted.)      Don't make duplicate entries, either.
2882          */
2883         oidlist = NIL;
2884         temp_missing = false;
2885         foreach(l, namelist)
2886         {
2887                 char       *curname = (char *) lfirst(l);
2888                 Oid                     namespaceId;
2889
2890                 if (strcmp(curname, "$user") == 0)
2891                 {
2892                         /* $user --- substitute namespace matching user name, if any */
2893                         HeapTuple       tuple;
2894
2895                         tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2896                         if (HeapTupleIsValid(tuple))
2897                         {
2898                                 char       *rname;
2899
2900                                 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
2901                                 namespaceId = get_namespace_oid(rname, true);
2902                                 ReleaseSysCache(tuple);
2903                                 if (OidIsValid(namespaceId) &&
2904                                         !list_member_oid(oidlist, namespaceId) &&
2905                                         pg_namespace_aclcheck(namespaceId, roleid,
2906                                                                                   ACL_USAGE) == ACLCHECK_OK)
2907                                         oidlist = lappend_oid(oidlist, namespaceId);
2908                         }
2909                 }
2910                 else if (strcmp(curname, "pg_temp") == 0)
2911                 {
2912                         /* pg_temp --- substitute temp namespace, if any */
2913                         if (OidIsValid(myTempNamespace))
2914                         {
2915                                 if (!list_member_oid(oidlist, myTempNamespace))
2916                                         oidlist = lappend_oid(oidlist, myTempNamespace);
2917                         }
2918                         else
2919                         {
2920                                 /* If it ought to be the creation namespace, set flag */
2921                                 if (oidlist == NIL)
2922                                         temp_missing = true;
2923                         }
2924                 }
2925                 else
2926                 {
2927                         /* normal namespace reference */
2928                         namespaceId = get_namespace_oid(curname, true);
2929                         if (OidIsValid(namespaceId) &&
2930                                 !list_member_oid(oidlist, namespaceId) &&
2931                                 pg_namespace_aclcheck(namespaceId, roleid,
2932                                                                           ACL_USAGE) == ACLCHECK_OK)
2933                                 oidlist = lappend_oid(oidlist, namespaceId);
2934                 }
2935         }
2936
2937         /*
2938          * Remember the first member of the explicit list.      (Note: this is
2939          * nominally wrong if temp_missing, but we need it anyway to distinguish
2940          * explicit from implicit mention of pg_catalog.)
2941          */
2942         if (oidlist == NIL)
2943                 firstNS = InvalidOid;
2944         else
2945                 firstNS = linitial_oid(oidlist);
2946
2947         /*
2948          * Add any implicitly-searched namespaces to the list.  Note these go on
2949          * the front, not the back; also notice that we do not check USAGE
2950          * permissions for these.
2951          */
2952         if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
2953                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2954
2955         if (OidIsValid(myTempNamespace) &&
2956                 !list_member_oid(oidlist, myTempNamespace))
2957                 oidlist = lcons_oid(myTempNamespace, oidlist);
2958
2959         /*
2960          * Now that we've successfully built the new list of namespace OIDs, save
2961          * it in permanent storage.
2962          */
2963         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2964         newpath = list_copy(oidlist);
2965         MemoryContextSwitchTo(oldcxt);
2966
2967         /* Now safe to assign to state variables. */
2968         list_free(baseSearchPath);
2969         baseSearchPath = newpath;
2970         baseCreationNamespace = firstNS;
2971         baseTempCreationPending = temp_missing;
2972
2973         /* Mark the path valid. */
2974         baseSearchPathValid = true;
2975         namespaceUser = roleid;
2976
2977         /* And make it active. */
2978         activeSearchPath = baseSearchPath;
2979         activeCreationNamespace = baseCreationNamespace;
2980         activeTempCreationPending = baseTempCreationPending;
2981
2982         /* Clean up. */
2983         pfree(rawname);
2984         list_free(namelist);
2985         list_free(oidlist);
2986 }
2987
2988 /*
2989  * InitTempTableNamespace
2990  *              Initialize temp table namespace on first use in a particular backend
2991  */
2992 static void
2993 InitTempTableNamespace(void)
2994 {
2995         char            namespaceName[NAMEDATALEN];
2996         Oid                     namespaceId;
2997         Oid                     toastspaceId;
2998
2999         Assert(!OidIsValid(myTempNamespace));
3000
3001         /*
3002          * First, do permission check to see if we are authorized to make temp
3003          * tables.      We use a nonstandard error message here since "databasename:
3004          * permission denied" might be a tad cryptic.
3005          *
3006          * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3007          * that's necessary since current user ID could change during the session.
3008          * But there's no need to make the namespace in the first place until a
3009          * temp table creation request is made by someone with appropriate rights.
3010          */
3011         if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3012                                                          ACL_CREATE_TEMP) != ACLCHECK_OK)
3013                 ereport(ERROR,
3014                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3015                                  errmsg("permission denied to create temporary tables in database \"%s\"",
3016                                                 get_database_name(MyDatabaseId))));
3017
3018         /*
3019          * Do not allow a Hot Standby slave session to make temp tables.  Aside
3020          * from problems with modifying the system catalogs, there is a naming
3021          * conflict: pg_temp_N belongs to the session with BackendId N on the
3022          * master, not to a slave session with the same BackendId.      We should not
3023          * be able to get here anyway due to XactReadOnly checks, but let's just
3024          * make real sure.      Note that this also backstops various operations that
3025          * allow XactReadOnly transactions to modify temp tables; they'd need
3026          * RecoveryInProgress checks if not for this.
3027          */
3028         if (RecoveryInProgress())
3029                 ereport(ERROR,
3030                                 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3031                                  errmsg("cannot create temporary tables during recovery")));
3032
3033         snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3034
3035         namespaceId = get_namespace_oid(namespaceName, true);
3036         if (!OidIsValid(namespaceId))
3037         {
3038                 /*
3039                  * First use of this temp namespace in this database; create it. The
3040                  * temp namespaces are always owned by the superuser.  We leave their
3041                  * permissions at default --- i.e., no access except to superuser ---
3042                  * to ensure that unprivileged users can't peek at other backends'
3043                  * temp tables.  This works because the places that access the temp
3044                  * namespace for my own backend skip permissions checks on it.
3045                  */
3046                 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3047                 /* Advance command counter to make namespace visible */
3048                 CommandCounterIncrement();
3049         }
3050         else
3051         {
3052                 /*
3053                  * If the namespace already exists, clean it out (in case the former
3054                  * owner crashed without doing so).
3055                  */
3056                 RemoveTempRelations(namespaceId);
3057         }
3058
3059         /*
3060          * If the corresponding toast-table namespace doesn't exist yet, create
3061          * it. (We assume there is no need to clean it out if it does exist, since
3062          * dropping a parent table should make its toast table go away.)
3063          */
3064         snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3065                          MyBackendId);
3066
3067         toastspaceId = get_namespace_oid(namespaceName, true);
3068         if (!OidIsValid(toastspaceId))
3069         {
3070                 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3071                 /* Advance command counter to make namespace visible */
3072                 CommandCounterIncrement();
3073         }
3074
3075         /*
3076          * Okay, we've prepared the temp namespace ... but it's not committed yet,
3077          * so all our work could be undone by transaction rollback.  Set flag for
3078          * AtEOXact_Namespace to know what to do.
3079          */
3080         myTempNamespace = namespaceId;
3081         myTempToastNamespace = toastspaceId;
3082
3083         /* It should not be done already. */
3084         AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3085         myTempNamespaceSubID = GetCurrentSubTransactionId();
3086
3087         baseSearchPathValid = false;    /* need to rebuild list */
3088 }
3089
3090 /*
3091  * End-of-transaction cleanup for namespaces.
3092  */
3093 void
3094 AtEOXact_Namespace(bool isCommit)
3095 {
3096         /*
3097          * If we abort the transaction in which a temp namespace was selected,
3098          * we'll have to do any creation or cleanout work over again.  So, just
3099          * forget the namespace entirely until next time.  On the other hand, if
3100          * we commit then register an exit callback to clean out the temp tables
3101          * at backend shutdown.  (We only want to register the callback once per
3102          * session, so this is a good place to do it.)
3103          */
3104         if (myTempNamespaceSubID != InvalidSubTransactionId)
3105         {
3106                 if (isCommit)
3107                         on_shmem_exit(RemoveTempRelationsCallback, 0);
3108                 else
3109                 {
3110                         myTempNamespace = InvalidOid;
3111                         myTempToastNamespace = InvalidOid;
3112                         baseSearchPathValid = false;            /* need to rebuild list */
3113                 }
3114                 myTempNamespaceSubID = InvalidSubTransactionId;
3115         }
3116
3117         /*
3118          * Clean up if someone failed to do PopOverrideSearchPath
3119          */
3120         if (overrideStack)
3121         {
3122                 if (isCommit)
3123                         elog(WARNING, "leaked override search path");
3124                 while (overrideStack)
3125                 {
3126                         OverrideStackEntry *entry;
3127
3128                         entry = (OverrideStackEntry *) linitial(overrideStack);
3129                         overrideStack = list_delete_first(overrideStack);
3130                         list_free(entry->searchPath);
3131                         pfree(entry);
3132                 }
3133                 /* If not baseSearchPathValid, this is useless but harmless */
3134                 activeSearchPath = baseSearchPath;
3135                 activeCreationNamespace = baseCreationNamespace;
3136                 activeTempCreationPending = baseTempCreationPending;
3137         }
3138 }
3139
3140 /*
3141  * AtEOSubXact_Namespace
3142  *
3143  * At subtransaction commit, propagate the temp-namespace-creation
3144  * flag to the parent subtransaction.
3145  *
3146  * At subtransaction abort, forget the flag if we set it up.
3147  */
3148 void
3149 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3150                                           SubTransactionId parentSubid)
3151 {
3152         OverrideStackEntry *entry;
3153
3154         if (myTempNamespaceSubID == mySubid)
3155         {
3156                 if (isCommit)
3157                         myTempNamespaceSubID = parentSubid;
3158                 else
3159                 {
3160                         myTempNamespaceSubID = InvalidSubTransactionId;
3161                         /* TEMP namespace creation failed, so reset state */
3162                         myTempNamespace = InvalidOid;
3163                         myTempToastNamespace = InvalidOid;
3164                         baseSearchPathValid = false;            /* need to rebuild list */
3165                 }
3166         }
3167
3168         /*
3169          * Clean up if someone failed to do PopOverrideSearchPath
3170          */
3171         while (overrideStack)
3172         {
3173                 entry = (OverrideStackEntry *) linitial(overrideStack);
3174                 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3175                         break;
3176                 if (isCommit)
3177                         elog(WARNING, "leaked override search path");
3178                 overrideStack = list_delete_first(overrideStack);
3179                 list_free(entry->searchPath);
3180                 pfree(entry);
3181         }
3182
3183         /* Activate the next level down. */
3184         if (overrideStack)
3185         {
3186                 entry = (OverrideStackEntry *) linitial(overrideStack);
3187                 activeSearchPath = entry->searchPath;
3188                 activeCreationNamespace = entry->creationNamespace;
3189                 activeTempCreationPending = false;              /* XXX is this OK? */
3190         }
3191         else
3192         {
3193                 /* If not baseSearchPathValid, this is useless but harmless */
3194                 activeSearchPath = baseSearchPath;
3195                 activeCreationNamespace = baseCreationNamespace;
3196                 activeTempCreationPending = baseTempCreationPending;
3197         }
3198 }
3199
3200 /*
3201  * Remove all relations in the specified temp namespace.
3202  *
3203  * This is called at backend shutdown (if we made any temp relations).
3204  * It is also called when we begin using a pre-existing temp namespace,
3205  * in order to clean out any relations that might have been created by
3206  * a crashed backend.
3207  */
3208 static void
3209 RemoveTempRelations(Oid tempNamespaceId)
3210 {
3211         ObjectAddress object;
3212
3213         /*
3214          * We want to get rid of everything in the target namespace, but not the
3215          * namespace itself (deleting it only to recreate it later would be a
3216          * waste of cycles).  We do this by finding everything that has a
3217          * dependency on the namespace.
3218          */
3219         object.classId = NamespaceRelationId;
3220         object.objectId = tempNamespaceId;
3221         object.objectSubId = 0;
3222
3223         deleteWhatDependsOn(&object, false);
3224 }
3225
3226 /*
3227  * Callback to remove temp relations at backend exit.
3228  */
3229 static void
3230 RemoveTempRelationsCallback(int code, Datum arg)
3231 {
3232         if (OidIsValid(myTempNamespace))        /* should always be true */
3233         {
3234                 /* Need to ensure we have a usable transaction. */
3235                 AbortOutOfAnyTransaction();
3236                 StartTransactionCommand();
3237
3238                 RemoveTempRelations(myTempNamespace);
3239
3240                 CommitTransactionCommand();
3241         }
3242 }
3243
3244 /*
3245  * Remove all temp tables from the temporary namespace.
3246  */
3247 void
3248 ResetTempTableNamespace(void)
3249 {
3250         if (OidIsValid(myTempNamespace))
3251                 RemoveTempRelations(myTempNamespace);
3252 }
3253
3254
3255 /*
3256  * Routines for handling the GUC variable 'search_path'.
3257  */
3258
3259 /* assign_hook: validate new search_path, do extra actions as needed */
3260 const char *
3261 assign_search_path(const char *newval, bool doit, GucSource source)
3262 {
3263         char       *rawname;
3264         List       *namelist;
3265         ListCell   *l;
3266
3267         /* Need a modifiable copy of string */
3268         rawname = pstrdup(newval);
3269
3270         /* Parse string into list of identifiers */
3271         if (!SplitIdentifierString(rawname, ',', &namelist))
3272         {
3273                 /* syntax error in name list */
3274                 pfree(rawname);
3275                 list_free(namelist);
3276                 return NULL;
3277         }
3278
3279         /*
3280          * If we aren't inside a transaction, we cannot do database access so
3281          * cannot verify the individual names.  Must accept the list on faith.
3282          */
3283         if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3284         {
3285                 /*
3286                  * Verify that all the names are either valid namespace names or
3287                  * "$user" or "pg_temp".  We do not require $user to correspond to a
3288                  * valid namespace, and pg_temp might not exist yet.  We do not check
3289                  * for USAGE rights, either; should we?
3290                  *
3291                  * When source == PGC_S_TEST, we are checking the argument of an ALTER
3292                  * DATABASE SET or ALTER USER SET command.      It could be that the
3293                  * intended use of the search path is for some other database, so we
3294                  * should not error out if it mentions schemas not present in the
3295                  * current database.  We reduce the message to NOTICE instead.
3296                  */
3297                 foreach(l, namelist)
3298                 {
3299                         char       *curname = (char *) lfirst(l);
3300
3301                         if (strcmp(curname, "$user") == 0)
3302                                 continue;
3303                         if (strcmp(curname, "pg_temp") == 0)
3304                                 continue;
3305                         if (!SearchSysCacheExists1(NAMESPACENAME,
3306                                                                            CStringGetDatum(curname)))
3307                                 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3308                                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3309                                                  errmsg("schema \"%s\" does not exist", curname)));
3310                 }
3311         }
3312
3313         pfree(rawname);
3314         list_free(namelist);
3315
3316         /*
3317          * We mark the path as needing recomputation, but don't do anything until
3318          * it's needed.  This avoids trying to do database access during GUC
3319          * initialization.
3320          */
3321         if (doit)
3322                 baseSearchPathValid = false;
3323
3324         return newval;
3325 }
3326
3327 /*
3328  * InitializeSearchPath: initialize module during InitPostgres.
3329  *
3330  * This is called after we are up enough to be able to do catalog lookups.
3331  */
3332 void
3333 InitializeSearchPath(void)
3334 {
3335         if (IsBootstrapProcessingMode())
3336         {
3337                 /*
3338                  * In bootstrap mode, the search path must be 'pg_catalog' so that
3339                  * tables are created in the proper namespace; ignore the GUC setting.
3340                  */
3341                 MemoryContext oldcxt;
3342
3343                 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3344                 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3345                 MemoryContextSwitchTo(oldcxt);
3346                 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3347                 baseTempCreationPending = false;
3348                 baseSearchPathValid = true;
3349                 namespaceUser = GetUserId();
3350                 activeSearchPath = baseSearchPath;
3351                 activeCreationNamespace = baseCreationNamespace;
3352                 activeTempCreationPending = baseTempCreationPending;
3353         }
3354         else
3355         {
3356                 /*
3357                  * In normal mode, arrange for a callback on any syscache invalidation
3358                  * of pg_namespace rows.
3359                  */
3360                 CacheRegisterSyscacheCallback(NAMESPACEOID,
3361                                                                           NamespaceCallback,
3362                                                                           (Datum) 0);
3363                 /* Force search path to be recomputed on next use */
3364                 baseSearchPathValid = false;
3365         }
3366 }
3367
3368 /*
3369  * NamespaceCallback
3370  *              Syscache inval callback function
3371  */
3372 static void
3373 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3374 {
3375         /* Force search path to be recomputed on next use */
3376         baseSearchPathValid = false;
3377 }
3378
3379 /*
3380  * Fetch the active search path. The return value is a palloc'ed list
3381  * of OIDs; the caller is responsible for freeing this storage as
3382  * appropriate.
3383  *
3384  * The returned list includes the implicitly-prepended namespaces only if
3385  * includeImplicit is true.
3386  *
3387  * Note: calling this may result in a CommandCounterIncrement operation,
3388  * if we have to create or clean out the temp namespace.
3389  */
3390 List *
3391 fetch_search_path(bool includeImplicit)
3392 {
3393         List       *result;
3394
3395         recomputeNamespacePath();
3396
3397         /*
3398          * If the temp namespace should be first, force it to exist.  This is so
3399          * that callers can trust the result to reflect the actual default
3400          * creation namespace.  It's a bit bogus to do this here, since
3401          * current_schema() is supposedly a stable function without side-effects,
3402          * but the alternatives seem worse.
3403          */
3404         if (activeTempCreationPending)
3405         {
3406                 InitTempTableNamespace();
3407                 recomputeNamespacePath();
3408         }
3409
3410         result = list_copy(activeSearchPath);
3411         if (!includeImplicit)
3412         {
3413                 while (result && linitial_oid(result) != activeCreationNamespace)
3414                         result = list_delete_first(result);
3415         }
3416
3417         return result;
3418 }
3419
3420 /*
3421  * Fetch the active search path into a caller-allocated array of OIDs.
3422  * Returns the number of path entries.  (If this is more than sarray_len,
3423  * then the data didn't fit and is not all stored.)
3424  *
3425  * The returned list always includes the implicitly-prepended namespaces,
3426  * but never includes the temp namespace.  (This is suitable for existing
3427  * users, which would want to ignore the temp namespace anyway.)  This
3428  * definition allows us to not worry about initializing the temp namespace.
3429  */
3430 int
3431 fetch_search_path_array(Oid *sarray, int sarray_len)
3432 {
3433         int                     count = 0;
3434         ListCell   *l;
3435
3436         recomputeNamespacePath();
3437
3438         foreach(l, activeSearchPath)
3439         {
3440                 Oid                     namespaceId = lfirst_oid(l);
3441
3442                 if (namespaceId == myTempNamespace)
3443                         continue;                       /* do not include temp namespace */
3444
3445                 if (count < sarray_len)
3446                         sarray[count] = namespaceId;
3447                 count++;
3448         }
3449
3450         return count;
3451 }
3452
3453
3454 /*
3455  * Export the FooIsVisible functions as SQL-callable functions.
3456  *
3457  * Note: as of Postgres 8.4, these will silently return NULL if called on
3458  * a nonexistent object OID, rather than failing.  This is to avoid race
3459  * condition errors when a query that's scanning a catalog using an MVCC
3460  * snapshot uses one of these functions.  The underlying IsVisible functions
3461  * operate on SnapshotNow semantics and so might see the object as already
3462  * gone when it's still visible to the MVCC snapshot.  (There is no race
3463  * condition in the current coding because we don't accept sinval messages
3464  * between the SearchSysCacheExists test and the subsequent lookup.)
3465  */
3466
3467 Datum
3468 pg_table_is_visible(PG_FUNCTION_ARGS)
3469 {
3470         Oid                     oid = PG_GETARG_OID(0);
3471
3472         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3473                 PG_RETURN_NULL();
3474
3475         PG_RETURN_BOOL(RelationIsVisible(oid));
3476 }
3477
3478 Datum
3479 pg_type_is_visible(PG_FUNCTION_ARGS)
3480 {
3481         Oid                     oid = PG_GETARG_OID(0);
3482
3483         if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3484                 PG_RETURN_NULL();
3485
3486         PG_RETURN_BOOL(TypeIsVisible(oid));
3487 }
3488
3489 Datum
3490 pg_function_is_visible(PG_FUNCTION_ARGS)
3491 {
3492         Oid                     oid = PG_GETARG_OID(0);
3493
3494         if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3495                 PG_RETURN_NULL();
3496
3497         PG_RETURN_BOOL(FunctionIsVisible(oid));
3498 }
3499
3500 Datum
3501 pg_operator_is_visible(PG_FUNCTION_ARGS)
3502 {
3503         Oid                     oid = PG_GETARG_OID(0);
3504
3505         if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3506                 PG_RETURN_NULL();
3507
3508         PG_RETURN_BOOL(OperatorIsVisible(oid));
3509 }
3510
3511 Datum
3512 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3513 {
3514         Oid                     oid = PG_GETARG_OID(0);
3515
3516         if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3517                 PG_RETURN_NULL();
3518
3519         PG_RETURN_BOOL(OpclassIsVisible(oid));
3520 }
3521
3522 Datum
3523 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3524 {
3525         Oid                     oid = PG_GETARG_OID(0);
3526
3527         if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3528                 PG_RETURN_NULL();
3529
3530         PG_RETURN_BOOL(ConversionIsVisible(oid));
3531 }
3532
3533 Datum
3534 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3535 {
3536         Oid                     oid = PG_GETARG_OID(0);
3537
3538         if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3539                 PG_RETURN_NULL();
3540
3541         PG_RETURN_BOOL(TSParserIsVisible(oid));
3542 }
3543
3544 Datum
3545 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3546 {
3547         Oid                     oid = PG_GETARG_OID(0);
3548
3549         if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3550                 PG_RETURN_NULL();
3551
3552         PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3553 }
3554
3555 Datum
3556 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3557 {
3558         Oid                     oid = PG_GETARG_OID(0);
3559
3560         if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3561                 PG_RETURN_NULL();
3562
3563         PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3564 }
3565
3566 Datum
3567 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3568 {
3569         Oid                     oid = PG_GETARG_OID(0);
3570
3571         if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3572                 PG_RETURN_NULL();
3573
3574         PG_RETURN_BOOL(TSConfigIsVisible(oid));
3575 }
3576
3577 Datum
3578 pg_my_temp_schema(PG_FUNCTION_ARGS)
3579 {
3580         PG_RETURN_OID(myTempNamespace);
3581 }
3582
3583 Datum
3584 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3585 {
3586         Oid                     oid = PG_GETARG_OID(0);
3587
3588         PG_RETURN_BOOL(isOtherTempNamespace(oid));
3589 }