]> granicus.if.org Git - postgresql/blob - src/backend/catalog/namespace.c
Wrap calls to SearchSysCache and related functions using macros.
[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.123 2010/02/14 18:42:13 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 = GetSysCacheOid1(NAMESPACENAME,
336                                                                           CStringGetDatum(newRelation->schemaname));
337                 if (!OidIsValid(namespaceId))
338                         ereport(ERROR,
339                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
340                                          errmsg("schema \"%s\" does not exist",
341                                                         newRelation->schemaname)));
342                 /* we do not check for USAGE rights here! */
343         }
344         else
345         {
346                 /* use the default creation namespace */
347                 recomputeNamespacePath();
348                 if (activeTempCreationPending)
349                 {
350                         /* Need to initialize temp namespace */
351                         InitTempTableNamespace();
352                         return myTempNamespace;
353                 }
354                 namespaceId = activeCreationNamespace;
355                 if (!OidIsValid(namespaceId))
356                         ereport(ERROR,
357                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
358                                          errmsg("no schema has been selected to create in")));
359         }
360
361         /* Note: callers will check for CREATE rights when appropriate */
362
363         return namespaceId;
364 }
365
366 /*
367  * RelnameGetRelid
368  *              Try to resolve an unqualified relation name.
369  *              Returns OID if relation found in search path, else InvalidOid.
370  */
371 Oid
372 RelnameGetRelid(const char *relname)
373 {
374         Oid                     relid;
375         ListCell   *l;
376
377         recomputeNamespacePath();
378
379         foreach(l, activeSearchPath)
380         {
381                 Oid                     namespaceId = lfirst_oid(l);
382
383                 relid = get_relname_relid(relname, namespaceId);
384                 if (OidIsValid(relid))
385                         return relid;
386         }
387
388         /* Not found in path */
389         return InvalidOid;
390 }
391
392
393 /*
394  * RelationIsVisible
395  *              Determine whether a relation (identified by OID) is visible in the
396  *              current search path.  Visible means "would be found by searching
397  *              for the unqualified relation name".
398  */
399 bool
400 RelationIsVisible(Oid relid)
401 {
402         HeapTuple       reltup;
403         Form_pg_class relform;
404         Oid                     relnamespace;
405         bool            visible;
406
407         reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
408         if (!HeapTupleIsValid(reltup))
409                 elog(ERROR, "cache lookup failed for relation %u", relid);
410         relform = (Form_pg_class) GETSTRUCT(reltup);
411
412         recomputeNamespacePath();
413
414         /*
415          * Quick check: if it ain't in the path at all, it ain't visible. Items in
416          * the system namespace are surely in the path and so we needn't even do
417          * list_member_oid() for them.
418          */
419         relnamespace = relform->relnamespace;
420         if (relnamespace != PG_CATALOG_NAMESPACE &&
421                 !list_member_oid(activeSearchPath, relnamespace))
422                 visible = false;
423         else
424         {
425                 /*
426                  * If it is in the path, it might still not be visible; it could be
427                  * hidden by another relation of the same name earlier in the path. So
428                  * we must do a slow check for conflicting relations.
429                  */
430                 char       *relname = NameStr(relform->relname);
431                 ListCell   *l;
432
433                 visible = false;
434                 foreach(l, activeSearchPath)
435                 {
436                         Oid                     namespaceId = lfirst_oid(l);
437
438                         if (namespaceId == relnamespace)
439                         {
440                                 /* Found it first in path */
441                                 visible = true;
442                                 break;
443                         }
444                         if (OidIsValid(get_relname_relid(relname, namespaceId)))
445                         {
446                                 /* Found something else first in path */
447                                 break;
448                         }
449                 }
450         }
451
452         ReleaseSysCache(reltup);
453
454         return visible;
455 }
456
457
458 /*
459  * TypenameGetTypid
460  *              Try to resolve an unqualified datatype name.
461  *              Returns OID if type found in search path, else InvalidOid.
462  *
463  * This is essentially the same as RelnameGetRelid.
464  */
465 Oid
466 TypenameGetTypid(const char *typname)
467 {
468         Oid                     typid;
469         ListCell   *l;
470
471         recomputeNamespacePath();
472
473         foreach(l, activeSearchPath)
474         {
475                 Oid                     namespaceId = lfirst_oid(l);
476
477                 typid = GetSysCacheOid2(TYPENAMENSP,
478                                                                 PointerGetDatum(typname),
479                                                                 ObjectIdGetDatum(namespaceId));
480                 if (OidIsValid(typid))
481                         return typid;
482         }
483
484         /* Not found in path */
485         return InvalidOid;
486 }
487
488 /*
489  * TypeIsVisible
490  *              Determine whether a type (identified by OID) is visible in the
491  *              current search path.  Visible means "would be found by searching
492  *              for the unqualified type name".
493  */
494 bool
495 TypeIsVisible(Oid typid)
496 {
497         HeapTuple       typtup;
498         Form_pg_type typform;
499         Oid                     typnamespace;
500         bool            visible;
501
502         typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
503         if (!HeapTupleIsValid(typtup))
504                 elog(ERROR, "cache lookup failed for type %u", typid);
505         typform = (Form_pg_type) GETSTRUCT(typtup);
506
507         recomputeNamespacePath();
508
509         /*
510          * Quick check: if it ain't in the path at all, it ain't visible. Items in
511          * the system namespace are surely in the path and so we needn't even do
512          * list_member_oid() for them.
513          */
514         typnamespace = typform->typnamespace;
515         if (typnamespace != PG_CATALOG_NAMESPACE &&
516                 !list_member_oid(activeSearchPath, typnamespace))
517                 visible = false;
518         else
519         {
520                 /*
521                  * If it is in the path, it might still not be visible; it could be
522                  * hidden by another type of the same name earlier in the path. So we
523                  * must do a slow check for conflicting types.
524                  */
525                 char       *typname = NameStr(typform->typname);
526                 ListCell   *l;
527
528                 visible = false;
529                 foreach(l, activeSearchPath)
530                 {
531                         Oid                     namespaceId = lfirst_oid(l);
532
533                         if (namespaceId == typnamespace)
534                         {
535                                 /* Found it first in path */
536                                 visible = true;
537                                 break;
538                         }
539                         if (SearchSysCacheExists2(TYPENAMENSP,
540                                                                           PointerGetDatum(typname),
541                                                                           ObjectIdGetDatum(namespaceId)))
542                         {
543                                 /* Found something else first in path */
544                                 break;
545                         }
546                 }
547         }
548
549         ReleaseSysCache(typtup);
550
551         return visible;
552 }
553
554
555 /*
556  * FuncnameGetCandidates
557  *              Given a possibly-qualified function name and argument count,
558  *              retrieve a list of the possible matches.
559  *
560  * If nargs is -1, we return all functions matching the given name,
561  * regardless of argument count.  (argnames must be NIL, and expand_variadic
562  * and expand_defaults must be false, in this case.)
563  *
564  * If argnames isn't NIL, we are considering a named- or mixed-notation call,
565  * and only functions having all the listed argument names will be returned.
566  * (We assume that length(argnames) <= nargs and all the passed-in names are
567  * distinct.)  The returned structs will include an argnumbers array showing
568  * the actual argument index for each logical argument position.
569  *
570  * If expand_variadic is true, then variadic functions having the same number
571  * or fewer arguments will be retrieved, with the variadic argument and any
572  * additional argument positions filled with the variadic element type.
573  * nvargs in the returned struct is set to the number of such arguments.
574  * If expand_variadic is false, variadic arguments are not treated specially,
575  * and the returned nvargs will always be zero.
576  *
577  * If expand_defaults is true, functions that could match after insertion of
578  * default argument values will also be retrieved.      In this case the returned
579  * structs could have nargs > passed-in nargs, and ndargs is set to the number
580  * of additional args (which can be retrieved from the function's
581  * proargdefaults entry).
582  *
583  * It is not possible for nvargs and ndargs to both be nonzero in the same
584  * list entry, since default insertion allows matches to functions with more
585  * than nargs arguments while the variadic transformation requires the same
586  * number or less.
587  *
588  * When argnames isn't NIL, the returned args[] type arrays are not ordered
589  * according to the functions' declarations, but rather according to the call:
590  * first any positional arguments, then the named arguments, then defaulted
591  * arguments (if needed and allowed by expand_defaults).  The argnumbers[]
592  * array can be used to map this back to the catalog information.
593  * argnumbers[k] is set to the proargtypes index of the k'th call argument.
594  *
595  * We search a single namespace if the function name is qualified, else
596  * all namespaces in the search path.  In the multiple-namespace case,
597  * we arrange for entries in earlier namespaces to mask identical entries in
598  * later namespaces.
599  *
600  * When expanding variadics, we arrange for non-variadic functions to mask
601  * variadic ones if the expanded argument list is the same.  It is still
602  * possible for there to be conflicts between different variadic functions,
603  * however.
604  *
605  * It is guaranteed that the return list will never contain multiple entries
606  * with identical argument lists.  When expand_defaults is true, the entries
607  * could have more than nargs positions, but we still guarantee that they are
608  * distinct in the first nargs positions.  However, if argnames isn't NIL or
609  * either expand_variadic or expand_defaults is true, there might be multiple
610  * candidate functions that expand to identical argument lists.  Rather than
611  * throw error here, we report such situations by returning a single entry
612  * with oid = 0 that represents a set of such conflicting candidates.
613  * The caller might end up discarding such an entry anyway, but if it selects
614  * such an entry it should react as though the call were ambiguous.
615  */
616 FuncCandidateList
617 FuncnameGetCandidates(List *names, int nargs, List *argnames,
618                                           bool expand_variadic, bool expand_defaults)
619 {
620         FuncCandidateList resultList = NULL;
621         bool            any_special = false;
622         char       *schemaname;
623         char       *funcname;
624         Oid                     namespaceId;
625         CatCList   *catlist;
626         int                     i;
627
628         /* check for caller error */
629         Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
630
631         /* deconstruct the name list */
632         DeconstructQualifiedName(names, &schemaname, &funcname);
633
634         if (schemaname)
635         {
636                 /* use exact schema given */
637                 namespaceId = LookupExplicitNamespace(schemaname);
638         }
639         else
640         {
641                 /* flag to indicate we need namespace search */
642                 namespaceId = InvalidOid;
643                 recomputeNamespacePath();
644         }
645
646         /* Search syscache by name only */
647         catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
648
649         for (i = 0; i < catlist->n_members; i++)
650         {
651                 HeapTuple       proctup = &catlist->members[i]->tuple;
652                 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
653                 int                     pronargs = procform->pronargs;
654                 int                     effective_nargs;
655                 int                     pathpos = 0;
656                 bool            variadic;
657                 bool            use_defaults;
658                 Oid                     va_elem_type;
659                 int                *argnumbers = NULL;
660                 FuncCandidateList newResult;
661
662                 if (OidIsValid(namespaceId))
663                 {
664                         /* Consider only procs in specified namespace */
665                         if (procform->pronamespace != namespaceId)
666                                 continue;
667                 }
668                 else
669                 {
670                         /*
671                          * Consider only procs that are in the search path and are not in
672                          * the temp namespace.
673                          */
674                         ListCell   *nsp;
675
676                         foreach(nsp, activeSearchPath)
677                         {
678                                 if (procform->pronamespace == lfirst_oid(nsp) &&
679                                         procform->pronamespace != myTempNamespace)
680                                         break;
681                                 pathpos++;
682                         }
683                         if (nsp == NULL)
684                                 continue;               /* proc is not in search path */
685                 }
686
687                 if (argnames != NIL)
688                 {
689                         /*
690                          * Call uses named or mixed notation
691                          *
692                          * Named or mixed notation can match a variadic function only
693                          * if expand_variadic is off; otherwise there is no way to match
694                          * the presumed-nameless parameters expanded from the variadic
695                          * array.
696                          */
697                         if (OidIsValid(procform->provariadic) && expand_variadic)
698                                 continue;
699                         va_elem_type = InvalidOid;
700                         variadic = false;
701
702                         /*
703                          * Check argument count.
704                          */
705                         Assert(nargs >= 0);                     /* -1 not supported with argnames */
706
707                         if (pronargs > nargs && expand_defaults)
708                         {
709                                 /* Ignore if not enough default expressions */
710                                 if (nargs + procform->pronargdefaults < pronargs)
711                                         continue;
712                                 use_defaults = true;
713                         }
714                         else
715                                 use_defaults = false;
716
717                         /* Ignore if it doesn't match requested argument count */
718                         if (pronargs != nargs && !use_defaults)
719                                 continue;
720
721                         /* Check for argument name match, generate positional mapping */
722                         if (!MatchNamedCall(proctup, nargs, argnames,
723                                                                 &argnumbers))
724                                 continue;
725
726                         /* Named argument matching is always "special" */
727                         any_special = true;
728                 }
729                 else
730                 {
731                         /*
732                          * Call uses positional notation
733                          *
734                          * Check if function is variadic, and get variadic element type if
735                          * so.  If expand_variadic is false, we should just ignore
736                          * variadic-ness.
737                          */
738                         if (pronargs <= nargs && expand_variadic)
739                         {
740                                 va_elem_type = procform->provariadic;
741                                 variadic = OidIsValid(va_elem_type);
742                                 any_special |= variadic;
743                         }
744                         else
745                         {
746                                 va_elem_type = InvalidOid;
747                                 variadic = false;
748                         }
749
750                         /*
751                          * Check if function can match by using parameter defaults.
752                          */
753                         if (pronargs > nargs && expand_defaults)
754                         {
755                                 /* Ignore if not enough default expressions */
756                                 if (nargs + procform->pronargdefaults < pronargs)
757                                         continue;
758                                 use_defaults = true;
759                                 any_special = true;
760                         }
761                         else
762                                 use_defaults = false;
763
764                         /* Ignore if it doesn't match requested argument count */
765                         if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
766                                 continue;
767                 }
768
769                 /*
770                  * We must compute the effective argument list so that we can easily
771                  * compare it to earlier results.  We waste a palloc cycle if it gets
772                  * masked by an earlier result, but really that's a pretty infrequent
773                  * case so it's not worth worrying about.
774                  */
775                 effective_nargs = Max(pronargs, nargs);
776                 newResult = (FuncCandidateList)
777                         palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
778                                    + effective_nargs * sizeof(Oid));
779                 newResult->pathpos = pathpos;
780                 newResult->oid = HeapTupleGetOid(proctup);
781                 newResult->nargs = effective_nargs;
782                 newResult->argnumbers = argnumbers;
783                 if (argnumbers)
784                 {
785                         /* Re-order the argument types into call's logical order */
786                         Oid                *proargtypes = procform->proargtypes.values;
787                         int                     i;
788
789                         for (i = 0; i < pronargs; i++)
790                                 newResult->args[i] = proargtypes[argnumbers[i]];
791                 }
792                 else
793                 {
794                         /* Simple positional case, just copy proargtypes as-is */
795                         memcpy(newResult->args, procform->proargtypes.values,
796                                    pronargs * sizeof(Oid));
797                 }
798                 if (variadic)
799                 {
800                         int                     i;
801
802                         newResult->nvargs = effective_nargs - pronargs + 1;
803                         /* Expand variadic argument into N copies of element type */
804                         for (i = pronargs - 1; i < effective_nargs; i++)
805                                 newResult->args[i] = va_elem_type;
806                 }
807                 else
808                         newResult->nvargs = 0;
809                 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
810
811                 /*
812                  * Does it have the same arguments as something we already accepted?
813                  * If so, decide what to do to avoid returning duplicate argument
814                  * lists.  We can skip this check for the single-namespace case if no
815                  * special (named, variadic or defaults) match has been made, since
816                  * then the unique index on pg_proc guarantees all the matches have
817                  * different argument lists.
818                  */
819                 if (resultList != NULL &&
820                         (any_special || !OidIsValid(namespaceId)))
821                 {
822                         /*
823                          * If we have an ordered list from SearchSysCacheList (the normal
824                          * case), then any conflicting proc must immediately adjoin this
825                          * one in the list, so we only need to look at the newest result
826                          * item.  If we have an unordered list, we have to scan the whole
827                          * result list.  Also, if either the current candidate or any
828                          * previous candidate is a special match, we can't assume that
829                          * conflicts are adjacent.
830                          *
831                          * We ignore defaulted arguments in deciding what is a match.
832                          */
833                         FuncCandidateList prevResult;
834
835                         if (catlist->ordered && !any_special)
836                         {
837                                 /* ndargs must be 0 if !any_special */
838                                 if (effective_nargs == resultList->nargs &&
839                                         memcmp(newResult->args,
840                                                    resultList->args,
841                                                    effective_nargs * sizeof(Oid)) == 0)
842                                         prevResult = resultList;
843                                 else
844                                         prevResult = NULL;
845                         }
846                         else
847                         {
848                                 int                     cmp_nargs = newResult->nargs - newResult->ndargs;
849
850                                 for (prevResult = resultList;
851                                          prevResult;
852                                          prevResult = prevResult->next)
853                                 {
854                                         if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
855                                                 memcmp(newResult->args,
856                                                            prevResult->args,
857                                                            cmp_nargs * sizeof(Oid)) == 0)
858                                                 break;
859                                 }
860                         }
861
862                         if (prevResult)
863                         {
864                                 /*
865                                  * We have a match with a previous result.      Decide which one
866                                  * to keep, or mark it ambiguous if we can't decide.  The
867                                  * logic here is preference > 0 means prefer the old result,
868                                  * preference < 0 means prefer the new, preference = 0 means
869                                  * ambiguous.
870                                  */
871                                 int                     preference;
872
873                                 if (pathpos != prevResult->pathpos)
874                                 {
875                                         /*
876                                          * Prefer the one that's earlier in the search path.
877                                          */
878                                         preference = pathpos - prevResult->pathpos;
879                                 }
880                                 else if (variadic && prevResult->nvargs == 0)
881                                 {
882                                         /*
883                                          * With variadic functions we could have, for example,
884                                          * both foo(numeric) and foo(variadic numeric[]) in the
885                                          * same namespace; if so we prefer the non-variadic match
886                                          * on efficiency grounds.
887                                          */
888                                         preference = 1;
889                                 }
890                                 else if (!variadic && prevResult->nvargs > 0)
891                                 {
892                                         preference = -1;
893                                 }
894                                 else
895                                 {
896                                         /*----------
897                                          * We can't decide.  This can happen with, for example,
898                                          * both foo(numeric, variadic numeric[]) and
899                                          * foo(variadic numeric[]) in the same namespace, or
900                                          * both foo(int) and foo (int, int default something)
901                                          * in the same namespace, or both foo(a int, b text)
902                                          * and foo(b text, a int) in the same namespace.
903                                          *----------
904                                          */
905                                         preference = 0;
906                                 }
907
908                                 if (preference > 0)
909                                 {
910                                         /* keep previous result */
911                                         pfree(newResult);
912                                         continue;
913                                 }
914                                 else if (preference < 0)
915                                 {
916                                         /* remove previous result from the list */
917                                         if (prevResult == resultList)
918                                                 resultList = prevResult->next;
919                                         else
920                                         {
921                                                 FuncCandidateList prevPrevResult;
922
923                                                 for (prevPrevResult = resultList;
924                                                          prevPrevResult;
925                                                          prevPrevResult = prevPrevResult->next)
926                                                 {
927                                                         if (prevResult == prevPrevResult->next)
928                                                         {
929                                                                 prevPrevResult->next = prevResult->next;
930                                                                 break;
931                                                         }
932                                                 }
933                                                 Assert(prevPrevResult); /* assert we found it */
934                                         }
935                                         pfree(prevResult);
936                                         /* fall through to add newResult to list */
937                                 }
938                                 else
939                                 {
940                                         /* mark old result as ambiguous, discard new */
941                                         prevResult->oid = InvalidOid;
942                                         pfree(newResult);
943                                         continue;
944                                 }
945                         }
946                 }
947
948                 /*
949                  * Okay to add it to result list
950                  */
951                 newResult->next = resultList;
952                 resultList = newResult;
953         }
954
955         ReleaseSysCacheList(catlist);
956
957         return resultList;
958 }
959
960 /*
961  * MatchNamedCall
962  *              Given a pg_proc heap tuple and a call's list of argument names,
963  *              check whether the function could match the call.
964  *
965  * The call could match if all supplied argument names are accepted by
966  * the function, in positions after the last positional argument, and there
967  * are defaults for all unsupplied arguments.
968  *
969  * The number of positional arguments is nargs - list_length(argnames).
970  * Note caller has already done basic checks on argument count.
971  *
972  * On match, return true and fill *argnumbers with a palloc'd array showing
973  * the mapping from call argument positions to actual function argument
974  * numbers.  Defaulted arguments are included in this map, at positions
975  * after the last supplied argument.
976  */
977 static bool
978 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
979                            int **argnumbers)
980 {
981         Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
982         int                     pronargs = procform->pronargs;
983         int                     numposargs = nargs - list_length(argnames);
984         int                     pronallargs;
985         Oid                *p_argtypes;
986         char      **p_argnames;
987         char       *p_argmodes;
988         bool            arggiven[FUNC_MAX_ARGS];
989         bool            isnull;
990         int                     ap;                             /* call args position */
991         int                     pp;                             /* proargs position */
992         ListCell   *lc;
993
994         Assert(argnames != NIL);
995         Assert(numposargs >= 0);
996         Assert(nargs <= pronargs);
997
998         /* Ignore this function if its proargnames is null */
999         (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1000                                                    &isnull);
1001         if (isnull)
1002                 return false;
1003
1004         /* OK, let's extract the argument names and types */
1005         pronallargs = get_func_arg_info(proctup,
1006                                                                         &p_argtypes, &p_argnames, &p_argmodes);
1007         Assert(p_argnames != NULL);
1008
1009         /* initialize state for matching */
1010         *argnumbers = (int *) palloc(pronargs * sizeof(int));
1011         memset(arggiven, false, pronargs * sizeof(bool));
1012
1013         /* there are numposargs positional args before the named args */
1014         for (ap = 0; ap < numposargs; ap++)
1015         {
1016                 (*argnumbers)[ap] = ap;
1017                 arggiven[ap] = true;
1018         }
1019
1020         /* now examine the named args */
1021         foreach(lc, argnames)
1022         {
1023                 char   *argname = (char *) lfirst(lc);
1024                 bool    found;
1025                 int             i;
1026
1027                 pp = 0;
1028                 found = false;
1029                 for (i = 0; i < pronallargs; i++)
1030                 {
1031                         /* consider only input parameters */
1032                         if (p_argmodes &&
1033                                 (p_argmodes[i] != FUNC_PARAM_IN &&
1034                                  p_argmodes[i] != FUNC_PARAM_INOUT &&
1035                                  p_argmodes[i] != FUNC_PARAM_VARIADIC))
1036                                 continue;
1037                         if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1038                         {
1039                                 /* fail if argname matches a positional argument */
1040                                 if (arggiven[pp])
1041                                         return false;
1042                                 arggiven[pp] = true;
1043                                 (*argnumbers)[ap] = pp;
1044                                 found = true;
1045                                 break;
1046                         }
1047                         /* increase pp only for input parameters */
1048                         pp++;
1049                 }
1050                 /* if name isn't in proargnames, fail */
1051                 if (!found)
1052                         return false;
1053                 ap++;
1054         }
1055
1056         Assert(ap == nargs);            /* processed all actual parameters */
1057
1058         /* Check for default arguments */
1059         if (nargs < pronargs)
1060         {
1061                 int             first_arg_with_default = pronargs - procform->pronargdefaults;
1062
1063                 for (pp = numposargs; pp < pronargs; pp++)
1064                 {
1065                         if (arggiven[pp])
1066                                 continue;
1067                         /* fail if arg not given and no default available */
1068                         if (pp < first_arg_with_default)
1069                                 return false;
1070                         (*argnumbers)[ap++] = pp;
1071                 }
1072         }
1073
1074         Assert(ap == pronargs);         /* processed all function parameters */
1075
1076         return true;
1077 }
1078
1079 /*
1080  * FunctionIsVisible
1081  *              Determine whether a function (identified by OID) is visible in the
1082  *              current search path.  Visible means "would be found by searching
1083  *              for the unqualified function name with exact argument matches".
1084  */
1085 bool
1086 FunctionIsVisible(Oid funcid)
1087 {
1088         HeapTuple       proctup;
1089         Form_pg_proc procform;
1090         Oid                     pronamespace;
1091         bool            visible;
1092
1093         proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1094         if (!HeapTupleIsValid(proctup))
1095                 elog(ERROR, "cache lookup failed for function %u", funcid);
1096         procform = (Form_pg_proc) GETSTRUCT(proctup);
1097
1098         recomputeNamespacePath();
1099
1100         /*
1101          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1102          * the system namespace are surely in the path and so we needn't even do
1103          * list_member_oid() for them.
1104          */
1105         pronamespace = procform->pronamespace;
1106         if (pronamespace != PG_CATALOG_NAMESPACE &&
1107                 !list_member_oid(activeSearchPath, pronamespace))
1108                 visible = false;
1109         else
1110         {
1111                 /*
1112                  * If it is in the path, it might still not be visible; it could be
1113                  * hidden by another proc of the same name and arguments earlier in
1114                  * the path.  So we must do a slow check to see if this is the same
1115                  * proc that would be found by FuncnameGetCandidates.
1116                  */
1117                 char       *proname = NameStr(procform->proname);
1118                 int                     nargs = procform->pronargs;
1119                 FuncCandidateList clist;
1120
1121                 visible = false;
1122
1123                 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1124                                                                           nargs, NIL, false, false);
1125
1126                 for (; clist; clist = clist->next)
1127                 {
1128                         if (memcmp(clist->args, procform->proargtypes.values,
1129                                            nargs * sizeof(Oid)) == 0)
1130                         {
1131                                 /* Found the expected entry; is it the right proc? */
1132                                 visible = (clist->oid == funcid);
1133                                 break;
1134                         }
1135                 }
1136         }
1137
1138         ReleaseSysCache(proctup);
1139
1140         return visible;
1141 }
1142
1143
1144 /*
1145  * OpernameGetOprid
1146  *              Given a possibly-qualified operator name and exact input datatypes,
1147  *              look up the operator.  Returns InvalidOid if not found.
1148  *
1149  * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1150  * a postfix op.
1151  *
1152  * If the operator name is not schema-qualified, it is sought in the current
1153  * namespace search path.
1154  */
1155 Oid
1156 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1157 {
1158         char       *schemaname;
1159         char       *opername;
1160         CatCList   *catlist;
1161         ListCell   *l;
1162
1163         /* deconstruct the name list */
1164         DeconstructQualifiedName(names, &schemaname, &opername);
1165
1166         if (schemaname)
1167         {
1168                 /* search only in exact schema given */
1169                 Oid                     namespaceId;
1170                 HeapTuple       opertup;
1171
1172                 namespaceId = LookupExplicitNamespace(schemaname);
1173                 opertup = SearchSysCache4(OPERNAMENSP,
1174                                                                   CStringGetDatum(opername),
1175                                                                   ObjectIdGetDatum(oprleft),
1176                                                                   ObjectIdGetDatum(oprright),
1177                                                                   ObjectIdGetDatum(namespaceId));
1178                 if (HeapTupleIsValid(opertup))
1179                 {
1180                         Oid                     result = HeapTupleGetOid(opertup);
1181
1182                         ReleaseSysCache(opertup);
1183                         return result;
1184                 }
1185                 return InvalidOid;
1186         }
1187
1188         /* Search syscache by name and argument types */
1189         catlist = SearchSysCacheList3(OPERNAMENSP,
1190                                                                   CStringGetDatum(opername),
1191                                                                   ObjectIdGetDatum(oprleft),
1192                                                                   ObjectIdGetDatum(oprright));
1193
1194         if (catlist->n_members == 0)
1195         {
1196                 /* no hope, fall out early */
1197                 ReleaseSysCacheList(catlist);
1198                 return InvalidOid;
1199         }
1200
1201         /*
1202          * We have to find the list member that is first in the search path, if
1203          * there's more than one.  This doubly-nested loop looks ugly, but in
1204          * practice there should usually be few catlist members.
1205          */
1206         recomputeNamespacePath();
1207
1208         foreach(l, activeSearchPath)
1209         {
1210                 Oid                     namespaceId = lfirst_oid(l);
1211                 int                     i;
1212
1213                 if (namespaceId == myTempNamespace)
1214                         continue;                       /* do not look in temp namespace */
1215
1216                 for (i = 0; i < catlist->n_members; i++)
1217                 {
1218                         HeapTuple       opertup = &catlist->members[i]->tuple;
1219                         Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1220
1221                         if (operform->oprnamespace == namespaceId)
1222                         {
1223                                 Oid                     result = HeapTupleGetOid(opertup);
1224
1225                                 ReleaseSysCacheList(catlist);
1226                                 return result;
1227                         }
1228                 }
1229         }
1230
1231         ReleaseSysCacheList(catlist);
1232         return InvalidOid;
1233 }
1234
1235 /*
1236  * OpernameGetCandidates
1237  *              Given a possibly-qualified operator name and operator kind,
1238  *              retrieve a list of the possible matches.
1239  *
1240  * If oprkind is '\0', we return all operators matching the given name,
1241  * regardless of arguments.
1242  *
1243  * We search a single namespace if the operator name is qualified, else
1244  * all namespaces in the search path.  The return list will never contain
1245  * multiple entries with identical argument lists --- in the multiple-
1246  * namespace case, we arrange for entries in earlier namespaces to mask
1247  * identical entries in later namespaces.
1248  *
1249  * The returned items always have two args[] entries --- one or the other
1250  * will be InvalidOid for a prefix or postfix oprkind.  nargs is 2, too.
1251  */
1252 FuncCandidateList
1253 OpernameGetCandidates(List *names, char oprkind)
1254 {
1255         FuncCandidateList resultList = NULL;
1256         char       *resultSpace = NULL;
1257         int                     nextResult = 0;
1258         char       *schemaname;
1259         char       *opername;
1260         Oid                     namespaceId;
1261         CatCList   *catlist;
1262         int                     i;
1263
1264         /* deconstruct the name list */
1265         DeconstructQualifiedName(names, &schemaname, &opername);
1266
1267         if (schemaname)
1268         {
1269                 /* use exact schema given */
1270                 namespaceId = LookupExplicitNamespace(schemaname);
1271         }
1272         else
1273         {
1274                 /* flag to indicate we need namespace search */
1275                 namespaceId = InvalidOid;
1276                 recomputeNamespacePath();
1277         }
1278
1279         /* Search syscache by name only */
1280         catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1281
1282         /*
1283          * In typical scenarios, most if not all of the operators found by the
1284          * catcache search will end up getting returned; and there can be quite a
1285          * few, for common operator names such as '=' or '+'.  To reduce the time
1286          * spent in palloc, we allocate the result space as an array large enough
1287          * to hold all the operators.  The original coding of this routine did a
1288          * separate palloc for each operator, but profiling revealed that the
1289          * pallocs used an unreasonably large fraction of parsing time.
1290          */
1291 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1292
1293         if (catlist->n_members > 0)
1294                 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1295
1296         for (i = 0; i < catlist->n_members; i++)
1297         {
1298                 HeapTuple       opertup = &catlist->members[i]->tuple;
1299                 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1300                 int                     pathpos = 0;
1301                 FuncCandidateList newResult;
1302
1303                 /* Ignore operators of wrong kind, if specific kind requested */
1304                 if (oprkind && operform->oprkind != oprkind)
1305                         continue;
1306
1307                 if (OidIsValid(namespaceId))
1308                 {
1309                         /* Consider only opers in specified namespace */
1310                         if (operform->oprnamespace != namespaceId)
1311                                 continue;
1312                         /* No need to check args, they must all be different */
1313                 }
1314                 else
1315                 {
1316                         /*
1317                          * Consider only opers that are in the search path and are not in
1318                          * the temp namespace.
1319                          */
1320                         ListCell   *nsp;
1321
1322                         foreach(nsp, activeSearchPath)
1323                         {
1324                                 if (operform->oprnamespace == lfirst_oid(nsp) &&
1325                                         operform->oprnamespace != myTempNamespace)
1326                                         break;
1327                                 pathpos++;
1328                         }
1329                         if (nsp == NULL)
1330                                 continue;               /* oper is not in search path */
1331
1332                         /*
1333                          * Okay, it's in the search path, but does it have the same
1334                          * arguments as something we already accepted?  If so, keep only
1335                          * the one that appears earlier in the search path.
1336                          *
1337                          * If we have an ordered list from SearchSysCacheList (the normal
1338                          * case), then any conflicting oper must immediately adjoin this
1339                          * one in the list, so we only need to look at the newest result
1340                          * item.  If we have an unordered list, we have to scan the whole
1341                          * result list.
1342                          */
1343                         if (resultList)
1344                         {
1345                                 FuncCandidateList prevResult;
1346
1347                                 if (catlist->ordered)
1348                                 {
1349                                         if (operform->oprleft == resultList->args[0] &&
1350                                                 operform->oprright == resultList->args[1])
1351                                                 prevResult = resultList;
1352                                         else
1353                                                 prevResult = NULL;
1354                                 }
1355                                 else
1356                                 {
1357                                         for (prevResult = resultList;
1358                                                  prevResult;
1359                                                  prevResult = prevResult->next)
1360                                         {
1361                                                 if (operform->oprleft == prevResult->args[0] &&
1362                                                         operform->oprright == prevResult->args[1])
1363                                                         break;
1364                                         }
1365                                 }
1366                                 if (prevResult)
1367                                 {
1368                                         /* We have a match with a previous result */
1369                                         Assert(pathpos != prevResult->pathpos);
1370                                         if (pathpos > prevResult->pathpos)
1371                                                 continue;               /* keep previous result */
1372                                         /* replace previous result */
1373                                         prevResult->pathpos = pathpos;
1374                                         prevResult->oid = HeapTupleGetOid(opertup);
1375                                         continue;       /* args are same, of course */
1376                                 }
1377                         }
1378                 }
1379
1380                 /*
1381                  * Okay to add it to result list
1382                  */
1383                 newResult = (FuncCandidateList) (resultSpace + nextResult);
1384                 nextResult += SPACE_PER_OP;
1385
1386                 newResult->pathpos = pathpos;
1387                 newResult->oid = HeapTupleGetOid(opertup);
1388                 newResult->nargs = 2;
1389                 newResult->nvargs = 0;
1390                 newResult->ndargs = 0;
1391                 newResult->argnumbers = NULL;
1392                 newResult->args[0] = operform->oprleft;
1393                 newResult->args[1] = operform->oprright;
1394                 newResult->next = resultList;
1395                 resultList = newResult;
1396         }
1397
1398         ReleaseSysCacheList(catlist);
1399
1400         return resultList;
1401 }
1402
1403 /*
1404  * OperatorIsVisible
1405  *              Determine whether an operator (identified by OID) is visible in the
1406  *              current search path.  Visible means "would be found by searching
1407  *              for the unqualified operator name with exact argument matches".
1408  */
1409 bool
1410 OperatorIsVisible(Oid oprid)
1411 {
1412         HeapTuple       oprtup;
1413         Form_pg_operator oprform;
1414         Oid                     oprnamespace;
1415         bool            visible;
1416
1417         oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1418         if (!HeapTupleIsValid(oprtup))
1419                 elog(ERROR, "cache lookup failed for operator %u", oprid);
1420         oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1421
1422         recomputeNamespacePath();
1423
1424         /*
1425          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1426          * the system namespace are surely in the path and so we needn't even do
1427          * list_member_oid() for them.
1428          */
1429         oprnamespace = oprform->oprnamespace;
1430         if (oprnamespace != PG_CATALOG_NAMESPACE &&
1431                 !list_member_oid(activeSearchPath, oprnamespace))
1432                 visible = false;
1433         else
1434         {
1435                 /*
1436                  * If it is in the path, it might still not be visible; it could be
1437                  * hidden by another operator of the same name and arguments earlier
1438                  * in the path.  So we must do a slow check to see if this is the same
1439                  * operator that would be found by OpernameGetOprId.
1440                  */
1441                 char       *oprname = NameStr(oprform->oprname);
1442
1443                 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1444                                                                         oprform->oprleft, oprform->oprright)
1445                                    == oprid);
1446         }
1447
1448         ReleaseSysCache(oprtup);
1449
1450         return visible;
1451 }
1452
1453
1454 /*
1455  * OpclassnameGetOpcid
1456  *              Try to resolve an unqualified index opclass name.
1457  *              Returns OID if opclass found in search path, else InvalidOid.
1458  *
1459  * This is essentially the same as TypenameGetTypid, but we have to have
1460  * an extra argument for the index AM OID.
1461  */
1462 Oid
1463 OpclassnameGetOpcid(Oid amid, const char *opcname)
1464 {
1465         Oid                     opcid;
1466         ListCell   *l;
1467
1468         recomputeNamespacePath();
1469
1470         foreach(l, activeSearchPath)
1471         {
1472                 Oid                     namespaceId = lfirst_oid(l);
1473
1474                 if (namespaceId == myTempNamespace)
1475                         continue;                       /* do not look in temp namespace */
1476
1477                 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1478                                                                 ObjectIdGetDatum(amid),
1479                                                                 PointerGetDatum(opcname),
1480                                                                 ObjectIdGetDatum(namespaceId));
1481                 if (OidIsValid(opcid))
1482                         return opcid;
1483         }
1484
1485         /* Not found in path */
1486         return InvalidOid;
1487 }
1488
1489 /*
1490  * OpclassIsVisible
1491  *              Determine whether an opclass (identified by OID) is visible in the
1492  *              current search path.  Visible means "would be found by searching
1493  *              for the unqualified opclass name".
1494  */
1495 bool
1496 OpclassIsVisible(Oid opcid)
1497 {
1498         HeapTuple       opctup;
1499         Form_pg_opclass opcform;
1500         Oid                     opcnamespace;
1501         bool            visible;
1502
1503         opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1504         if (!HeapTupleIsValid(opctup))
1505                 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1506         opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1507
1508         recomputeNamespacePath();
1509
1510         /*
1511          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1512          * the system namespace are surely in the path and so we needn't even do
1513          * list_member_oid() for them.
1514          */
1515         opcnamespace = opcform->opcnamespace;
1516         if (opcnamespace != PG_CATALOG_NAMESPACE &&
1517                 !list_member_oid(activeSearchPath, opcnamespace))
1518                 visible = false;
1519         else
1520         {
1521                 /*
1522                  * If it is in the path, it might still not be visible; it could be
1523                  * hidden by another opclass of the same name earlier in the path. So
1524                  * we must do a slow check to see if this opclass would be found by
1525                  * OpclassnameGetOpcid.
1526                  */
1527                 char       *opcname = NameStr(opcform->opcname);
1528
1529                 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1530         }
1531
1532         ReleaseSysCache(opctup);
1533
1534         return visible;
1535 }
1536
1537 /*
1538  * OpfamilynameGetOpfid
1539  *              Try to resolve an unqualified index opfamily name.
1540  *              Returns OID if opfamily found in search path, else InvalidOid.
1541  *
1542  * This is essentially the same as TypenameGetTypid, but we have to have
1543  * an extra argument for the index AM OID.
1544  */
1545 Oid
1546 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1547 {
1548         Oid                     opfid;
1549         ListCell   *l;
1550
1551         recomputeNamespacePath();
1552
1553         foreach(l, activeSearchPath)
1554         {
1555                 Oid                     namespaceId = lfirst_oid(l);
1556
1557                 if (namespaceId == myTempNamespace)
1558                         continue;                       /* do not look in temp namespace */
1559
1560                 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1561                                                                 ObjectIdGetDatum(amid),
1562                                                                 PointerGetDatum(opfname),
1563                                                                 ObjectIdGetDatum(namespaceId));
1564                 if (OidIsValid(opfid))
1565                         return opfid;
1566         }
1567
1568         /* Not found in path */
1569         return InvalidOid;
1570 }
1571
1572 /*
1573  * OpfamilyIsVisible
1574  *              Determine whether an opfamily (identified by OID) is visible in the
1575  *              current search path.  Visible means "would be found by searching
1576  *              for the unqualified opfamily name".
1577  */
1578 bool
1579 OpfamilyIsVisible(Oid opfid)
1580 {
1581         HeapTuple       opftup;
1582         Form_pg_opfamily opfform;
1583         Oid                     opfnamespace;
1584         bool            visible;
1585
1586         opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1587         if (!HeapTupleIsValid(opftup))
1588                 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1589         opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1590
1591         recomputeNamespacePath();
1592
1593         /*
1594          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1595          * the system namespace are surely in the path and so we needn't even do
1596          * list_member_oid() for them.
1597          */
1598         opfnamespace = opfform->opfnamespace;
1599         if (opfnamespace != PG_CATALOG_NAMESPACE &&
1600                 !list_member_oid(activeSearchPath, opfnamespace))
1601                 visible = false;
1602         else
1603         {
1604                 /*
1605                  * If it is in the path, it might still not be visible; it could be
1606                  * hidden by another opfamily of the same name earlier in the path. So
1607                  * we must do a slow check to see if this opfamily would be found by
1608                  * OpfamilynameGetOpfid.
1609                  */
1610                 char       *opfname = NameStr(opfform->opfname);
1611
1612                 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1613         }
1614
1615         ReleaseSysCache(opftup);
1616
1617         return visible;
1618 }
1619
1620 /*
1621  * ConversionGetConid
1622  *              Try to resolve an unqualified conversion name.
1623  *              Returns OID if conversion found in search path, else InvalidOid.
1624  *
1625  * This is essentially the same as RelnameGetRelid.
1626  */
1627 Oid
1628 ConversionGetConid(const char *conname)
1629 {
1630         Oid                     conid;
1631         ListCell   *l;
1632
1633         recomputeNamespacePath();
1634
1635         foreach(l, activeSearchPath)
1636         {
1637                 Oid                     namespaceId = lfirst_oid(l);
1638
1639                 if (namespaceId == myTempNamespace)
1640                         continue;                       /* do not look in temp namespace */
1641
1642                 conid = GetSysCacheOid2(CONNAMENSP,
1643                                                                 PointerGetDatum(conname),
1644                                                                 ObjectIdGetDatum(namespaceId));
1645                 if (OidIsValid(conid))
1646                         return conid;
1647         }
1648
1649         /* Not found in path */
1650         return InvalidOid;
1651 }
1652
1653 /*
1654  * ConversionIsVisible
1655  *              Determine whether a conversion (identified by OID) is visible in the
1656  *              current search path.  Visible means "would be found by searching
1657  *              for the unqualified conversion name".
1658  */
1659 bool
1660 ConversionIsVisible(Oid conid)
1661 {
1662         HeapTuple       contup;
1663         Form_pg_conversion conform;
1664         Oid                     connamespace;
1665         bool            visible;
1666
1667         contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1668         if (!HeapTupleIsValid(contup))
1669                 elog(ERROR, "cache lookup failed for conversion %u", conid);
1670         conform = (Form_pg_conversion) GETSTRUCT(contup);
1671
1672         recomputeNamespacePath();
1673
1674         /*
1675          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1676          * the system namespace are surely in the path and so we needn't even do
1677          * list_member_oid() for them.
1678          */
1679         connamespace = conform->connamespace;
1680         if (connamespace != PG_CATALOG_NAMESPACE &&
1681                 !list_member_oid(activeSearchPath, connamespace))
1682                 visible = false;
1683         else
1684         {
1685                 /*
1686                  * If it is in the path, it might still not be visible; it could be
1687                  * hidden by another conversion of the same name earlier in the path.
1688                  * So we must do a slow check to see if this conversion would be found
1689                  * by ConversionGetConid.
1690                  */
1691                 char       *conname = NameStr(conform->conname);
1692
1693                 visible = (ConversionGetConid(conname) == conid);
1694         }
1695
1696         ReleaseSysCache(contup);
1697
1698         return visible;
1699 }
1700
1701 /*
1702  * TSParserGetPrsid - find a TS parser by possibly qualified name
1703  *
1704  * If not found, returns InvalidOid if failOK, else throws error
1705  */
1706 Oid
1707 TSParserGetPrsid(List *names, bool failOK)
1708 {
1709         char       *schemaname;
1710         char       *parser_name;
1711         Oid                     namespaceId;
1712         Oid                     prsoid = InvalidOid;
1713         ListCell   *l;
1714
1715         /* deconstruct the name list */
1716         DeconstructQualifiedName(names, &schemaname, &parser_name);
1717
1718         if (schemaname)
1719         {
1720                 /* use exact schema given */
1721                 namespaceId = LookupExplicitNamespace(schemaname);
1722                 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1723                                                                  PointerGetDatum(parser_name),
1724                                                                  ObjectIdGetDatum(namespaceId));
1725         }
1726         else
1727         {
1728                 /* search for it in search path */
1729                 recomputeNamespacePath();
1730
1731                 foreach(l, activeSearchPath)
1732                 {
1733                         namespaceId = lfirst_oid(l);
1734
1735                         if (namespaceId == myTempNamespace)
1736                                 continue;               /* do not look in temp namespace */
1737
1738                         prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1739                                                                          PointerGetDatum(parser_name),
1740                                                                          ObjectIdGetDatum(namespaceId));
1741                         if (OidIsValid(prsoid))
1742                                 break;
1743                 }
1744         }
1745
1746         if (!OidIsValid(prsoid) && !failOK)
1747                 ereport(ERROR,
1748                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1749                                  errmsg("text search parser \"%s\" does not exist",
1750                                                 NameListToString(names))));
1751
1752         return prsoid;
1753 }
1754
1755 /*
1756  * TSParserIsVisible
1757  *              Determine whether a parser (identified by OID) is visible in the
1758  *              current search path.  Visible means "would be found by searching
1759  *              for the unqualified parser name".
1760  */
1761 bool
1762 TSParserIsVisible(Oid prsId)
1763 {
1764         HeapTuple       tup;
1765         Form_pg_ts_parser form;
1766         Oid                     namespace;
1767         bool            visible;
1768
1769         tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1770         if (!HeapTupleIsValid(tup))
1771                 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1772         form = (Form_pg_ts_parser) GETSTRUCT(tup);
1773
1774         recomputeNamespacePath();
1775
1776         /*
1777          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1778          * the system namespace are surely in the path and so we needn't even do
1779          * list_member_oid() for them.
1780          */
1781         namespace = form->prsnamespace;
1782         if (namespace != PG_CATALOG_NAMESPACE &&
1783                 !list_member_oid(activeSearchPath, namespace))
1784                 visible = false;
1785         else
1786         {
1787                 /*
1788                  * If it is in the path, it might still not be visible; it could be
1789                  * hidden by another parser of the same name earlier in the path. So
1790                  * we must do a slow check for conflicting parsers.
1791                  */
1792                 char       *name = NameStr(form->prsname);
1793                 ListCell   *l;
1794
1795                 visible = false;
1796                 foreach(l, activeSearchPath)
1797                 {
1798                         Oid                     namespaceId = lfirst_oid(l);
1799
1800                         if (namespaceId == myTempNamespace)
1801                                 continue;               /* do not look in temp namespace */
1802
1803                         if (namespaceId == namespace)
1804                         {
1805                                 /* Found it first in path */
1806                                 visible = true;
1807                                 break;
1808                         }
1809                         if (SearchSysCacheExists2(TSPARSERNAMENSP,
1810                                                                           PointerGetDatum(name),
1811                                                                           ObjectIdGetDatum(namespaceId)))
1812                         {
1813                                 /* Found something else first in path */
1814                                 break;
1815                         }
1816                 }
1817         }
1818
1819         ReleaseSysCache(tup);
1820
1821         return visible;
1822 }
1823
1824 /*
1825  * TSDictionaryGetDictid - find a TS dictionary by possibly qualified name
1826  *
1827  * If not found, returns InvalidOid if failOK, else throws error
1828  */
1829 Oid
1830 TSDictionaryGetDictid(List *names, bool failOK)
1831 {
1832         char       *schemaname;
1833         char       *dict_name;
1834         Oid                     namespaceId;
1835         Oid                     dictoid = InvalidOid;
1836         ListCell   *l;
1837
1838         /* deconstruct the name list */
1839         DeconstructQualifiedName(names, &schemaname, &dict_name);
1840
1841         if (schemaname)
1842         {
1843                 /* use exact schema given */
1844                 namespaceId = LookupExplicitNamespace(schemaname);
1845                 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1846                                                                   PointerGetDatum(dict_name),
1847                                                                   ObjectIdGetDatum(namespaceId));
1848         }
1849         else
1850         {
1851                 /* search for it in search path */
1852                 recomputeNamespacePath();
1853
1854                 foreach(l, activeSearchPath)
1855                 {
1856                         namespaceId = lfirst_oid(l);
1857
1858                         if (namespaceId == myTempNamespace)
1859                                 continue;               /* do not look in temp namespace */
1860
1861                         dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1862                                                                           PointerGetDatum(dict_name),
1863                                                                           ObjectIdGetDatum(namespaceId));
1864                         if (OidIsValid(dictoid))
1865                                 break;
1866                 }
1867         }
1868
1869         if (!OidIsValid(dictoid) && !failOK)
1870                 ereport(ERROR,
1871                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1872                                  errmsg("text search dictionary \"%s\" does not exist",
1873                                                 NameListToString(names))));
1874
1875         return dictoid;
1876 }
1877
1878 /*
1879  * TSDictionaryIsVisible
1880  *              Determine whether a dictionary (identified by OID) is visible in the
1881  *              current search path.  Visible means "would be found by searching
1882  *              for the unqualified dictionary name".
1883  */
1884 bool
1885 TSDictionaryIsVisible(Oid dictId)
1886 {
1887         HeapTuple       tup;
1888         Form_pg_ts_dict form;
1889         Oid                     namespace;
1890         bool            visible;
1891
1892         tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
1893         if (!HeapTupleIsValid(tup))
1894                 elog(ERROR, "cache lookup failed for text search dictionary %u",
1895                          dictId);
1896         form = (Form_pg_ts_dict) GETSTRUCT(tup);
1897
1898         recomputeNamespacePath();
1899
1900         /*
1901          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1902          * the system namespace are surely in the path and so we needn't even do
1903          * list_member_oid() for them.
1904          */
1905         namespace = form->dictnamespace;
1906         if (namespace != PG_CATALOG_NAMESPACE &&
1907                 !list_member_oid(activeSearchPath, namespace))
1908                 visible = false;
1909         else
1910         {
1911                 /*
1912                  * If it is in the path, it might still not be visible; it could be
1913                  * hidden by another dictionary of the same name earlier in the path.
1914                  * So we must do a slow check for conflicting dictionaries.
1915                  */
1916                 char       *name = NameStr(form->dictname);
1917                 ListCell   *l;
1918
1919                 visible = false;
1920                 foreach(l, activeSearchPath)
1921                 {
1922                         Oid                     namespaceId = lfirst_oid(l);
1923
1924                         if (namespaceId == myTempNamespace)
1925                                 continue;               /* do not look in temp namespace */
1926
1927                         if (namespaceId == namespace)
1928                         {
1929                                 /* Found it first in path */
1930                                 visible = true;
1931                                 break;
1932                         }
1933                         if (SearchSysCacheExists2(TSDICTNAMENSP,
1934                                                                           PointerGetDatum(name),
1935                                                                           ObjectIdGetDatum(namespaceId)))
1936                         {
1937                                 /* Found something else first in path */
1938                                 break;
1939                         }
1940                 }
1941         }
1942
1943         ReleaseSysCache(tup);
1944
1945         return visible;
1946 }
1947
1948 /*
1949  * TSTemplateGetTmplid - find a TS template by possibly qualified name
1950  *
1951  * If not found, returns InvalidOid if failOK, else throws error
1952  */
1953 Oid
1954 TSTemplateGetTmplid(List *names, bool failOK)
1955 {
1956         char       *schemaname;
1957         char       *template_name;
1958         Oid                     namespaceId;
1959         Oid                     tmploid = InvalidOid;
1960         ListCell   *l;
1961
1962         /* deconstruct the name list */
1963         DeconstructQualifiedName(names, &schemaname, &template_name);
1964
1965         if (schemaname)
1966         {
1967                 /* use exact schema given */
1968                 namespaceId = LookupExplicitNamespace(schemaname);
1969                 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1970                                                                   PointerGetDatum(template_name),
1971                                                                   ObjectIdGetDatum(namespaceId));
1972         }
1973         else
1974         {
1975                 /* search for it in search path */
1976                 recomputeNamespacePath();
1977
1978                 foreach(l, activeSearchPath)
1979                 {
1980                         namespaceId = lfirst_oid(l);
1981
1982                         if (namespaceId == myTempNamespace)
1983                                 continue;               /* do not look in temp namespace */
1984
1985                         tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1986                                                                           PointerGetDatum(template_name),
1987                                                                           ObjectIdGetDatum(namespaceId));
1988                         if (OidIsValid(tmploid))
1989                                 break;
1990                 }
1991         }
1992
1993         if (!OidIsValid(tmploid) && !failOK)
1994                 ereport(ERROR,
1995                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1996                                  errmsg("text search template \"%s\" does not exist",
1997                                                 NameListToString(names))));
1998
1999         return tmploid;
2000 }
2001
2002 /*
2003  * TSTemplateIsVisible
2004  *              Determine whether a template (identified by OID) is visible in the
2005  *              current search path.  Visible means "would be found by searching
2006  *              for the unqualified template name".
2007  */
2008 bool
2009 TSTemplateIsVisible(Oid tmplId)
2010 {
2011         HeapTuple       tup;
2012         Form_pg_ts_template form;
2013         Oid                     namespace;
2014         bool            visible;
2015
2016         tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2017         if (!HeapTupleIsValid(tup))
2018                 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2019         form = (Form_pg_ts_template) GETSTRUCT(tup);
2020
2021         recomputeNamespacePath();
2022
2023         /*
2024          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2025          * the system namespace are surely in the path and so we needn't even do
2026          * list_member_oid() for them.
2027          */
2028         namespace = form->tmplnamespace;
2029         if (namespace != PG_CATALOG_NAMESPACE &&
2030                 !list_member_oid(activeSearchPath, namespace))
2031                 visible = false;
2032         else
2033         {
2034                 /*
2035                  * If it is in the path, it might still not be visible; it could be
2036                  * hidden by another template of the same name earlier in the path. So
2037                  * we must do a slow check for conflicting templates.
2038                  */
2039                 char       *name = NameStr(form->tmplname);
2040                 ListCell   *l;
2041
2042                 visible = false;
2043                 foreach(l, activeSearchPath)
2044                 {
2045                         Oid                     namespaceId = lfirst_oid(l);
2046
2047                         if (namespaceId == myTempNamespace)
2048                                 continue;               /* do not look in temp namespace */
2049
2050                         if (namespaceId == namespace)
2051                         {
2052                                 /* Found it first in path */
2053                                 visible = true;
2054                                 break;
2055                         }
2056                         if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2057                                                                           PointerGetDatum(name),
2058                                                                           ObjectIdGetDatum(namespaceId)))
2059                         {
2060                                 /* Found something else first in path */
2061                                 break;
2062                         }
2063                 }
2064         }
2065
2066         ReleaseSysCache(tup);
2067
2068         return visible;
2069 }
2070
2071 /*
2072  * TSConfigGetCfgid - find a TS config by possibly qualified name
2073  *
2074  * If not found, returns InvalidOid if failOK, else throws error
2075  */
2076 Oid
2077 TSConfigGetCfgid(List *names, bool failOK)
2078 {
2079         char       *schemaname;
2080         char       *config_name;
2081         Oid                     namespaceId;
2082         Oid                     cfgoid = InvalidOid;
2083         ListCell   *l;
2084
2085         /* deconstruct the name list */
2086         DeconstructQualifiedName(names, &schemaname, &config_name);
2087
2088         if (schemaname)
2089         {
2090                 /* use exact schema given */
2091                 namespaceId = LookupExplicitNamespace(schemaname);
2092                 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2093                                                                  PointerGetDatum(config_name),
2094                                                                  ObjectIdGetDatum(namespaceId));
2095         }
2096         else
2097         {
2098                 /* search for it in search path */
2099                 recomputeNamespacePath();
2100
2101                 foreach(l, activeSearchPath)
2102                 {
2103                         namespaceId = lfirst_oid(l);
2104
2105                         if (namespaceId == myTempNamespace)
2106                                 continue;               /* do not look in temp namespace */
2107
2108                         cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2109                                                                          PointerGetDatum(config_name),
2110                                                                          ObjectIdGetDatum(namespaceId));
2111                         if (OidIsValid(cfgoid))
2112                                 break;
2113                 }
2114         }
2115
2116         if (!OidIsValid(cfgoid) && !failOK)
2117                 ereport(ERROR,
2118                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2119                                  errmsg("text search configuration \"%s\" does not exist",
2120                                                 NameListToString(names))));
2121
2122         return cfgoid;
2123 }
2124
2125 /*
2126  * TSConfigIsVisible
2127  *              Determine whether a text search configuration (identified by OID)
2128  *              is visible in the current search path.  Visible means "would be found
2129  *              by searching for the unqualified text search configuration name".
2130  */
2131 bool
2132 TSConfigIsVisible(Oid cfgid)
2133 {
2134         HeapTuple       tup;
2135         Form_pg_ts_config form;
2136         Oid                     namespace;
2137         bool            visible;
2138
2139         tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2140         if (!HeapTupleIsValid(tup))
2141                 elog(ERROR, "cache lookup failed for text search configuration %u",
2142                          cfgid);
2143         form = (Form_pg_ts_config) GETSTRUCT(tup);
2144
2145         recomputeNamespacePath();
2146
2147         /*
2148          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2149          * the system namespace are surely in the path and so we needn't even do
2150          * list_member_oid() for them.
2151          */
2152         namespace = form->cfgnamespace;
2153         if (namespace != PG_CATALOG_NAMESPACE &&
2154                 !list_member_oid(activeSearchPath, namespace))
2155                 visible = false;
2156         else
2157         {
2158                 /*
2159                  * If it is in the path, it might still not be visible; it could be
2160                  * hidden by another configuration of the same name earlier in the
2161                  * path. So we must do a slow check for conflicting configurations.
2162                  */
2163                 char       *name = NameStr(form->cfgname);
2164                 ListCell   *l;
2165
2166                 visible = false;
2167                 foreach(l, activeSearchPath)
2168                 {
2169                         Oid                     namespaceId = lfirst_oid(l);
2170
2171                         if (namespaceId == myTempNamespace)
2172                                 continue;               /* do not look in temp namespace */
2173
2174                         if (namespaceId == namespace)
2175                         {
2176                                 /* Found it first in path */
2177                                 visible = true;
2178                                 break;
2179                         }
2180                         if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2181                                                                           PointerGetDatum(name),
2182                                                                           ObjectIdGetDatum(namespaceId)))
2183                         {
2184                                 /* Found something else first in path */
2185                                 break;
2186                         }
2187                 }
2188         }
2189
2190         ReleaseSysCache(tup);
2191
2192         return visible;
2193 }
2194
2195
2196 /*
2197  * DeconstructQualifiedName
2198  *              Given a possibly-qualified name expressed as a list of String nodes,
2199  *              extract the schema name and object name.
2200  *
2201  * *nspname_p is set to NULL if there is no explicit schema name.
2202  */
2203 void
2204 DeconstructQualifiedName(List *names,
2205                                                  char **nspname_p,
2206                                                  char **objname_p)
2207 {
2208         char       *catalogname;
2209         char       *schemaname = NULL;
2210         char       *objname = NULL;
2211
2212         switch (list_length(names))
2213         {
2214                 case 1:
2215                         objname = strVal(linitial(names));
2216                         break;
2217                 case 2:
2218                         schemaname = strVal(linitial(names));
2219                         objname = strVal(lsecond(names));
2220                         break;
2221                 case 3:
2222                         catalogname = strVal(linitial(names));
2223                         schemaname = strVal(lsecond(names));
2224                         objname = strVal(lthird(names));
2225
2226                         /*
2227                          * We check the catalog name and then ignore it.
2228                          */
2229                         if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2230                                 ereport(ERROR,
2231                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2232                                   errmsg("cross-database references are not implemented: %s",
2233                                                  NameListToString(names))));
2234                         break;
2235                 default:
2236                         ereport(ERROR,
2237                                         (errcode(ERRCODE_SYNTAX_ERROR),
2238                                 errmsg("improper qualified name (too many dotted names): %s",
2239                                            NameListToString(names))));
2240                         break;
2241         }
2242
2243         *nspname_p = schemaname;
2244         *objname_p = objname;
2245 }
2246
2247 /*
2248  * LookupNamespaceNoError
2249  *              Look up a schema name.
2250  *
2251  * Returns the namespace OID, or InvalidOid if not found.
2252  *
2253  * Note this does NOT perform any permissions check --- callers are
2254  * responsible for being sure that an appropriate check is made.
2255  * In the majority of cases LookupExplicitNamespace is preferable.
2256  */
2257 Oid
2258 LookupNamespaceNoError(const char *nspname)
2259 {
2260         /* check for pg_temp alias */
2261         if (strcmp(nspname, "pg_temp") == 0)
2262         {
2263                 if (OidIsValid(myTempNamespace))
2264                         return myTempNamespace;
2265
2266                 /*
2267                  * Since this is used only for looking up existing objects, there is
2268                  * no point in trying to initialize the temp namespace here; and doing
2269                  * so might create problems for some callers. Just report "not found".
2270                  */
2271                 return InvalidOid;
2272         }
2273
2274         return GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2275 }
2276
2277 /*
2278  * LookupExplicitNamespace
2279  *              Process an explicitly-specified schema name: look up the schema
2280  *              and verify we have USAGE (lookup) rights in it.
2281  *
2282  * Returns the namespace OID.  Raises ereport if any problem.
2283  */
2284 Oid
2285 LookupExplicitNamespace(const char *nspname)
2286 {
2287         Oid                     namespaceId;
2288         AclResult       aclresult;
2289
2290         /* check for pg_temp alias */
2291         if (strcmp(nspname, "pg_temp") == 0)
2292         {
2293                 if (OidIsValid(myTempNamespace))
2294                         return myTempNamespace;
2295
2296                 /*
2297                  * Since this is used only for looking up existing objects, there is
2298                  * no point in trying to initialize the temp namespace here; and doing
2299                  * so might create problems for some callers. Just fall through and
2300                  * give the "does not exist" error.
2301                  */
2302         }
2303
2304         namespaceId = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2305         if (!OidIsValid(namespaceId))
2306                 ereport(ERROR,
2307                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2308                                  errmsg("schema \"%s\" does not exist", nspname)));
2309
2310         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2311         if (aclresult != ACLCHECK_OK)
2312                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2313                                            nspname);
2314
2315         return namespaceId;
2316 }
2317
2318 /*
2319  * LookupCreationNamespace
2320  *              Look up the schema and verify we have CREATE rights on it.
2321  *
2322  * This is just like LookupExplicitNamespace except for the different
2323  * permission check, and that we are willing to create pg_temp if needed.
2324  *
2325  * Note: calling this may result in a CommandCounterIncrement operation,
2326  * if we have to create or clean out the temp namespace.
2327  */
2328 Oid
2329 LookupCreationNamespace(const char *nspname)
2330 {
2331         Oid                     namespaceId;
2332         AclResult       aclresult;
2333
2334         /* check for pg_temp alias */
2335         if (strcmp(nspname, "pg_temp") == 0)
2336         {
2337                 /* Initialize temp namespace if first time through */
2338                 if (!OidIsValid(myTempNamespace))
2339                         InitTempTableNamespace();
2340                 return myTempNamespace;
2341         }
2342
2343         namespaceId = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2344         if (!OidIsValid(namespaceId))
2345                 ereport(ERROR,
2346                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2347                                  errmsg("schema \"%s\" does not exist", nspname)));
2348
2349         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2350         if (aclresult != ACLCHECK_OK)
2351                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2352                                            nspname);
2353
2354         return namespaceId;
2355 }
2356
2357 /*
2358  * QualifiedNameGetCreationNamespace
2359  *              Given a possibly-qualified name for an object (in List-of-Values
2360  *              format), determine what namespace the object should be created in.
2361  *              Also extract and return the object name (last component of list).
2362  *
2363  * Note: this does not apply any permissions check.  Callers must check
2364  * for CREATE rights on the selected namespace when appropriate.
2365  *
2366  * Note: calling this may result in a CommandCounterIncrement operation,
2367  * if we have to create or clean out the temp namespace.
2368  */
2369 Oid
2370 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2371 {
2372         char       *schemaname;
2373         Oid                     namespaceId;
2374
2375         /* deconstruct the name list */
2376         DeconstructQualifiedName(names, &schemaname, objname_p);
2377
2378         if (schemaname)
2379         {
2380                 /* check for pg_temp alias */
2381                 if (strcmp(schemaname, "pg_temp") == 0)
2382                 {
2383                         /* Initialize temp namespace if first time through */
2384                         if (!OidIsValid(myTempNamespace))
2385                                 InitTempTableNamespace();
2386                         return myTempNamespace;
2387                 }
2388                 /* use exact schema given */
2389                 namespaceId = GetSysCacheOid1(NAMESPACENAME,
2390                                                                           CStringGetDatum(schemaname));
2391                 if (!OidIsValid(namespaceId))
2392                         ereport(ERROR,
2393                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
2394                                          errmsg("schema \"%s\" does not exist", schemaname)));
2395                 /* we do not check for USAGE rights here! */
2396         }
2397         else
2398         {
2399                 /* use the default creation namespace */
2400                 recomputeNamespacePath();
2401                 if (activeTempCreationPending)
2402                 {
2403                         /* Need to initialize temp namespace */
2404                         InitTempTableNamespace();
2405                         return myTempNamespace;
2406                 }
2407                 namespaceId = activeCreationNamespace;
2408                 if (!OidIsValid(namespaceId))
2409                         ereport(ERROR,
2410                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
2411                                          errmsg("no schema has been selected to create in")));
2412         }
2413
2414         return namespaceId;
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 = GetSysCacheOid1(NAMESPACENAME,
2902                                                                                           CStringGetDatum(rname));
2903                                 ReleaseSysCache(tuple);
2904                                 if (OidIsValid(namespaceId) &&
2905                                         !list_member_oid(oidlist, namespaceId) &&
2906                                         pg_namespace_aclcheck(namespaceId, roleid,
2907                                                                                   ACL_USAGE) == ACLCHECK_OK)
2908                                         oidlist = lappend_oid(oidlist, namespaceId);
2909                         }
2910                 }
2911                 else if (strcmp(curname, "pg_temp") == 0)
2912                 {
2913                         /* pg_temp --- substitute temp namespace, if any */
2914                         if (OidIsValid(myTempNamespace))
2915                         {
2916                                 if (!list_member_oid(oidlist, myTempNamespace))
2917                                         oidlist = lappend_oid(oidlist, myTempNamespace);
2918                         }
2919                         else
2920                         {
2921                                 /* If it ought to be the creation namespace, set flag */
2922                                 if (oidlist == NIL)
2923                                         temp_missing = true;
2924                         }
2925                 }
2926                 else
2927                 {
2928                         /* normal namespace reference */
2929                         namespaceId = GetSysCacheOid1(NAMESPACENAME,
2930                                                                                   CStringGetDatum(curname));
2931                         if (OidIsValid(namespaceId) &&
2932                                 !list_member_oid(oidlist, namespaceId) &&
2933                                 pg_namespace_aclcheck(namespaceId, roleid,
2934                                                                           ACL_USAGE) == ACLCHECK_OK)
2935                                 oidlist = lappend_oid(oidlist, namespaceId);
2936                 }
2937         }
2938
2939         /*
2940          * Remember the first member of the explicit list.      (Note: this is
2941          * nominally wrong if temp_missing, but we need it anyway to distinguish
2942          * explicit from implicit mention of pg_catalog.)
2943          */
2944         if (oidlist == NIL)
2945                 firstNS = InvalidOid;
2946         else
2947                 firstNS = linitial_oid(oidlist);
2948
2949         /*
2950          * Add any implicitly-searched namespaces to the list.  Note these go on
2951          * the front, not the back; also notice that we do not check USAGE
2952          * permissions for these.
2953          */
2954         if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
2955                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2956
2957         if (OidIsValid(myTempNamespace) &&
2958                 !list_member_oid(oidlist, myTempNamespace))
2959                 oidlist = lcons_oid(myTempNamespace, oidlist);
2960
2961         /*
2962          * Now that we've successfully built the new list of namespace OIDs, save
2963          * it in permanent storage.
2964          */
2965         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2966         newpath = list_copy(oidlist);
2967         MemoryContextSwitchTo(oldcxt);
2968
2969         /* Now safe to assign to state variables. */
2970         list_free(baseSearchPath);
2971         baseSearchPath = newpath;
2972         baseCreationNamespace = firstNS;
2973         baseTempCreationPending = temp_missing;
2974
2975         /* Mark the path valid. */
2976         baseSearchPathValid = true;
2977         namespaceUser = roleid;
2978
2979         /* And make it active. */
2980         activeSearchPath = baseSearchPath;
2981         activeCreationNamespace = baseCreationNamespace;
2982         activeTempCreationPending = baseTempCreationPending;
2983
2984         /* Clean up. */
2985         pfree(rawname);
2986         list_free(namelist);
2987         list_free(oidlist);
2988 }
2989
2990 /*
2991  * InitTempTableNamespace
2992  *              Initialize temp table namespace on first use in a particular backend
2993  */
2994 static void
2995 InitTempTableNamespace(void)
2996 {
2997         char            namespaceName[NAMEDATALEN];
2998         Oid                     namespaceId;
2999         Oid                     toastspaceId;
3000
3001         Assert(!OidIsValid(myTempNamespace));
3002
3003         /*
3004          * First, do permission check to see if we are authorized to make temp
3005          * tables.      We use a nonstandard error message here since "databasename:
3006          * permission denied" might be a tad cryptic.
3007          *
3008          * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3009          * that's necessary since current user ID could change during the session.
3010          * But there's no need to make the namespace in the first place until a
3011          * temp table creation request is made by someone with appropriate rights.
3012          */
3013         if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3014                                                          ACL_CREATE_TEMP) != ACLCHECK_OK)
3015                 ereport(ERROR,
3016                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3017                                  errmsg("permission denied to create temporary tables in database \"%s\"",
3018                                                 get_database_name(MyDatabaseId))));
3019
3020         snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3021
3022         namespaceId = GetSysCacheOid1(NAMESPACENAME,
3023                                                                   CStringGetDatum(namespaceName));
3024         if (!OidIsValid(namespaceId))
3025         {
3026                 /*
3027                  * First use of this temp namespace in this database; create it. The
3028                  * temp namespaces are always owned by the superuser.  We leave their
3029                  * permissions at default --- i.e., no access except to superuser ---
3030                  * to ensure that unprivileged users can't peek at other backends'
3031                  * temp tables.  This works because the places that access the temp
3032                  * namespace for my own backend skip permissions checks on it.
3033                  */
3034                 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3035                 /* Advance command counter to make namespace visible */
3036                 CommandCounterIncrement();
3037         }
3038         else
3039         {
3040                 /*
3041                  * If the namespace already exists, clean it out (in case the former
3042                  * owner crashed without doing so).
3043                  */
3044                 RemoveTempRelations(namespaceId);
3045         }
3046
3047         /*
3048          * If the corresponding toast-table namespace doesn't exist yet, create
3049          * it. (We assume there is no need to clean it out if it does exist, since
3050          * dropping a parent table should make its toast table go away.)
3051          */
3052         snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3053                          MyBackendId);
3054
3055         toastspaceId = GetSysCacheOid1(NAMESPACENAME,
3056                                                                    CStringGetDatum(namespaceName));
3057         if (!OidIsValid(toastspaceId))
3058         {
3059                 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3060                 /* Advance command counter to make namespace visible */
3061                 CommandCounterIncrement();
3062         }
3063
3064         /*
3065          * Okay, we've prepared the temp namespace ... but it's not committed yet,
3066          * so all our work could be undone by transaction rollback.  Set flag for
3067          * AtEOXact_Namespace to know what to do.
3068          */
3069         myTempNamespace = namespaceId;
3070         myTempToastNamespace = toastspaceId;
3071
3072         /* It should not be done already. */
3073         AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3074         myTempNamespaceSubID = GetCurrentSubTransactionId();
3075
3076         baseSearchPathValid = false;    /* need to rebuild list */
3077 }
3078
3079 /*
3080  * End-of-transaction cleanup for namespaces.
3081  */
3082 void
3083 AtEOXact_Namespace(bool isCommit)
3084 {
3085         /*
3086          * If we abort the transaction in which a temp namespace was selected,
3087          * we'll have to do any creation or cleanout work over again.  So, just
3088          * forget the namespace entirely until next time.  On the other hand, if
3089          * we commit then register an exit callback to clean out the temp tables
3090          * at backend shutdown.  (We only want to register the callback once per
3091          * session, so this is a good place to do it.)
3092          */
3093         if (myTempNamespaceSubID != InvalidSubTransactionId)
3094         {
3095                 if (isCommit)
3096                         on_shmem_exit(RemoveTempRelationsCallback, 0);
3097                 else
3098                 {
3099                         myTempNamespace = InvalidOid;
3100                         myTempToastNamespace = InvalidOid;
3101                         baseSearchPathValid = false;            /* need to rebuild list */
3102                 }
3103                 myTempNamespaceSubID = InvalidSubTransactionId;
3104         }
3105
3106         /*
3107          * Clean up if someone failed to do PopOverrideSearchPath
3108          */
3109         if (overrideStack)
3110         {
3111                 if (isCommit)
3112                         elog(WARNING, "leaked override search path");
3113                 while (overrideStack)
3114                 {
3115                         OverrideStackEntry *entry;
3116
3117                         entry = (OverrideStackEntry *) linitial(overrideStack);
3118                         overrideStack = list_delete_first(overrideStack);
3119                         list_free(entry->searchPath);
3120                         pfree(entry);
3121                 }
3122                 /* If not baseSearchPathValid, this is useless but harmless */
3123                 activeSearchPath = baseSearchPath;
3124                 activeCreationNamespace = baseCreationNamespace;
3125                 activeTempCreationPending = baseTempCreationPending;
3126         }
3127 }
3128
3129 /*
3130  * AtEOSubXact_Namespace
3131  *
3132  * At subtransaction commit, propagate the temp-namespace-creation
3133  * flag to the parent subtransaction.
3134  *
3135  * At subtransaction abort, forget the flag if we set it up.
3136  */
3137 void
3138 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3139                                           SubTransactionId parentSubid)
3140 {
3141         OverrideStackEntry *entry;
3142
3143         if (myTempNamespaceSubID == mySubid)
3144         {
3145                 if (isCommit)
3146                         myTempNamespaceSubID = parentSubid;
3147                 else
3148                 {
3149                         myTempNamespaceSubID = InvalidSubTransactionId;
3150                         /* TEMP namespace creation failed, so reset state */
3151                         myTempNamespace = InvalidOid;
3152                         myTempToastNamespace = InvalidOid;
3153                         baseSearchPathValid = false;            /* need to rebuild list */
3154                 }
3155         }
3156
3157         /*
3158          * Clean up if someone failed to do PopOverrideSearchPath
3159          */
3160         while (overrideStack)
3161         {
3162                 entry = (OverrideStackEntry *) linitial(overrideStack);
3163                 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3164                         break;
3165                 if (isCommit)
3166                         elog(WARNING, "leaked override search path");
3167                 overrideStack = list_delete_first(overrideStack);
3168                 list_free(entry->searchPath);
3169                 pfree(entry);
3170         }
3171
3172         /* Activate the next level down. */
3173         if (overrideStack)
3174         {
3175                 entry = (OverrideStackEntry *) linitial(overrideStack);
3176                 activeSearchPath = entry->searchPath;
3177                 activeCreationNamespace = entry->creationNamespace;
3178                 activeTempCreationPending = false;              /* XXX is this OK? */
3179         }
3180         else
3181         {
3182                 /* If not baseSearchPathValid, this is useless but harmless */
3183                 activeSearchPath = baseSearchPath;
3184                 activeCreationNamespace = baseCreationNamespace;
3185                 activeTempCreationPending = baseTempCreationPending;
3186         }
3187 }
3188
3189 /*
3190  * Remove all relations in the specified temp namespace.
3191  *
3192  * This is called at backend shutdown (if we made any temp relations).
3193  * It is also called when we begin using a pre-existing temp namespace,
3194  * in order to clean out any relations that might have been created by
3195  * a crashed backend.
3196  */
3197 static void
3198 RemoveTempRelations(Oid tempNamespaceId)
3199 {
3200         ObjectAddress object;
3201
3202         /*
3203          * We want to get rid of everything in the target namespace, but not the
3204          * namespace itself (deleting it only to recreate it later would be a
3205          * waste of cycles).  We do this by finding everything that has a
3206          * dependency on the namespace.
3207          */
3208         object.classId = NamespaceRelationId;
3209         object.objectId = tempNamespaceId;
3210         object.objectSubId = 0;
3211
3212         deleteWhatDependsOn(&object, false);
3213 }
3214
3215 /*
3216  * Callback to remove temp relations at backend exit.
3217  */
3218 static void
3219 RemoveTempRelationsCallback(int code, Datum arg)
3220 {
3221         if (OidIsValid(myTempNamespace))        /* should always be true */
3222         {
3223                 /* Need to ensure we have a usable transaction. */
3224                 AbortOutOfAnyTransaction();
3225                 StartTransactionCommand();
3226
3227                 RemoveTempRelations(myTempNamespace);
3228
3229                 CommitTransactionCommand();
3230         }
3231 }
3232
3233 /*
3234  * Remove all temp tables from the temporary namespace.
3235  */
3236 void
3237 ResetTempTableNamespace(void)
3238 {
3239         if (OidIsValid(myTempNamespace))
3240                 RemoveTempRelations(myTempNamespace);
3241 }
3242
3243
3244 /*
3245  * Routines for handling the GUC variable 'search_path'.
3246  */
3247
3248 /* assign_hook: validate new search_path, do extra actions as needed */
3249 const char *
3250 assign_search_path(const char *newval, bool doit, GucSource source)
3251 {
3252         char       *rawname;
3253         List       *namelist;
3254         ListCell   *l;
3255
3256         /* Need a modifiable copy of string */
3257         rawname = pstrdup(newval);
3258
3259         /* Parse string into list of identifiers */
3260         if (!SplitIdentifierString(rawname, ',', &namelist))
3261         {
3262                 /* syntax error in name list */
3263                 pfree(rawname);
3264                 list_free(namelist);
3265                 return NULL;
3266         }
3267
3268         /*
3269          * If we aren't inside a transaction, we cannot do database access so
3270          * cannot verify the individual names.  Must accept the list on faith.
3271          */
3272         if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3273         {
3274                 /*
3275                  * Verify that all the names are either valid namespace names or
3276                  * "$user" or "pg_temp".  We do not require $user to correspond to a
3277                  * valid namespace, and pg_temp might not exist yet.  We do not check
3278                  * for USAGE rights, either; should we?
3279                  *
3280                  * When source == PGC_S_TEST, we are checking the argument of an ALTER
3281                  * DATABASE SET or ALTER USER SET command.      It could be that the
3282                  * intended use of the search path is for some other database, so we
3283                  * should not error out if it mentions schemas not present in the
3284                  * current database.  We reduce the message to NOTICE instead.
3285                  */
3286                 foreach(l, namelist)
3287                 {
3288                         char       *curname = (char *) lfirst(l);
3289
3290                         if (strcmp(curname, "$user") == 0)
3291                                 continue;
3292                         if (strcmp(curname, "pg_temp") == 0)
3293                                 continue;
3294                         if (!SearchSysCacheExists1(NAMESPACENAME,
3295                                                                            CStringGetDatum(curname)))
3296                                 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3297                                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3298                                                  errmsg("schema \"%s\" does not exist", curname)));
3299                 }
3300         }
3301
3302         pfree(rawname);
3303         list_free(namelist);
3304
3305         /*
3306          * We mark the path as needing recomputation, but don't do anything until
3307          * it's needed.  This avoids trying to do database access during GUC
3308          * initialization.
3309          */
3310         if (doit)
3311                 baseSearchPathValid = false;
3312
3313         return newval;
3314 }
3315
3316 /*
3317  * InitializeSearchPath: initialize module during InitPostgres.
3318  *
3319  * This is called after we are up enough to be able to do catalog lookups.
3320  */
3321 void
3322 InitializeSearchPath(void)
3323 {
3324         if (IsBootstrapProcessingMode())
3325         {
3326                 /*
3327                  * In bootstrap mode, the search path must be 'pg_catalog' so that
3328                  * tables are created in the proper namespace; ignore the GUC setting.
3329                  */
3330                 MemoryContext oldcxt;
3331
3332                 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3333                 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3334                 MemoryContextSwitchTo(oldcxt);
3335                 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3336                 baseTempCreationPending = false;
3337                 baseSearchPathValid = true;
3338                 namespaceUser = GetUserId();
3339                 activeSearchPath = baseSearchPath;
3340                 activeCreationNamespace = baseCreationNamespace;
3341                 activeTempCreationPending = baseTempCreationPending;
3342         }
3343         else
3344         {
3345                 /*
3346                  * In normal mode, arrange for a callback on any syscache invalidation
3347                  * of pg_namespace rows.
3348                  */
3349                 CacheRegisterSyscacheCallback(NAMESPACEOID,
3350                                                                           NamespaceCallback,
3351                                                                           (Datum) 0);
3352                 /* Force search path to be recomputed on next use */
3353                 baseSearchPathValid = false;
3354         }
3355 }
3356
3357 /*
3358  * NamespaceCallback
3359  *              Syscache inval callback function
3360  */
3361 static void
3362 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3363 {
3364         /* Force search path to be recomputed on next use */
3365         baseSearchPathValid = false;
3366 }
3367
3368 /*
3369  * Fetch the active search path. The return value is a palloc'ed list
3370  * of OIDs; the caller is responsible for freeing this storage as
3371  * appropriate.
3372  *
3373  * The returned list includes the implicitly-prepended namespaces only if
3374  * includeImplicit is true.
3375  *
3376  * Note: calling this may result in a CommandCounterIncrement operation,
3377  * if we have to create or clean out the temp namespace.
3378  */
3379 List *
3380 fetch_search_path(bool includeImplicit)
3381 {
3382         List       *result;
3383
3384         recomputeNamespacePath();
3385
3386         /*
3387          * If the temp namespace should be first, force it to exist.  This is so
3388          * that callers can trust the result to reflect the actual default
3389          * creation namespace.  It's a bit bogus to do this here, since
3390          * current_schema() is supposedly a stable function without side-effects,
3391          * but the alternatives seem worse.
3392          */
3393         if (activeTempCreationPending)
3394         {
3395                 InitTempTableNamespace();
3396                 recomputeNamespacePath();
3397         }
3398
3399         result = list_copy(activeSearchPath);
3400         if (!includeImplicit)
3401         {
3402                 while (result && linitial_oid(result) != activeCreationNamespace)
3403                         result = list_delete_first(result);
3404         }
3405
3406         return result;
3407 }
3408
3409 /*
3410  * Fetch the active search path into a caller-allocated array of OIDs.
3411  * Returns the number of path entries.  (If this is more than sarray_len,
3412  * then the data didn't fit and is not all stored.)
3413  *
3414  * The returned list always includes the implicitly-prepended namespaces,
3415  * but never includes the temp namespace.  (This is suitable for existing
3416  * users, which would want to ignore the temp namespace anyway.)  This
3417  * definition allows us to not worry about initializing the temp namespace.
3418  */
3419 int
3420 fetch_search_path_array(Oid *sarray, int sarray_len)
3421 {
3422         int                     count = 0;
3423         ListCell   *l;
3424
3425         recomputeNamespacePath();
3426
3427         foreach(l, activeSearchPath)
3428         {
3429                 Oid                     namespaceId = lfirst_oid(l);
3430
3431                 if (namespaceId == myTempNamespace)
3432                         continue;                       /* do not include temp namespace */
3433
3434                 if (count < sarray_len)
3435                         sarray[count] = namespaceId;
3436                 count++;
3437         }
3438
3439         return count;
3440 }
3441
3442
3443 /*
3444  * Export the FooIsVisible functions as SQL-callable functions.
3445  *
3446  * Note: as of Postgres 8.4, these will silently return NULL if called on
3447  * a nonexistent object OID, rather than failing.  This is to avoid race
3448  * condition errors when a query that's scanning a catalog using an MVCC
3449  * snapshot uses one of these functions.  The underlying IsVisible functions
3450  * operate on SnapshotNow semantics and so might see the object as already
3451  * gone when it's still visible to the MVCC snapshot.  (There is no race
3452  * condition in the current coding because we don't accept sinval messages
3453  * between the SearchSysCacheExists test and the subsequent lookup.)
3454  */
3455
3456 Datum
3457 pg_table_is_visible(PG_FUNCTION_ARGS)
3458 {
3459         Oid                     oid = PG_GETARG_OID(0);
3460
3461         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3462                 PG_RETURN_NULL();
3463
3464         PG_RETURN_BOOL(RelationIsVisible(oid));
3465 }
3466
3467 Datum
3468 pg_type_is_visible(PG_FUNCTION_ARGS)
3469 {
3470         Oid                     oid = PG_GETARG_OID(0);
3471
3472         if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3473                 PG_RETURN_NULL();
3474
3475         PG_RETURN_BOOL(TypeIsVisible(oid));
3476 }
3477
3478 Datum
3479 pg_function_is_visible(PG_FUNCTION_ARGS)
3480 {
3481         Oid                     oid = PG_GETARG_OID(0);
3482
3483         if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3484                 PG_RETURN_NULL();
3485
3486         PG_RETURN_BOOL(FunctionIsVisible(oid));
3487 }
3488
3489 Datum
3490 pg_operator_is_visible(PG_FUNCTION_ARGS)
3491 {
3492         Oid                     oid = PG_GETARG_OID(0);
3493
3494         if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3495                 PG_RETURN_NULL();
3496
3497         PG_RETURN_BOOL(OperatorIsVisible(oid));
3498 }
3499
3500 Datum
3501 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3502 {
3503         Oid                     oid = PG_GETARG_OID(0);
3504
3505         if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3506                 PG_RETURN_NULL();
3507
3508         PG_RETURN_BOOL(OpclassIsVisible(oid));
3509 }
3510
3511 Datum
3512 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3513 {
3514         Oid                     oid = PG_GETARG_OID(0);
3515
3516         if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3517                 PG_RETURN_NULL();
3518
3519         PG_RETURN_BOOL(ConversionIsVisible(oid));
3520 }
3521
3522 Datum
3523 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3524 {
3525         Oid                     oid = PG_GETARG_OID(0);
3526
3527         if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3528                 PG_RETURN_NULL();
3529
3530         PG_RETURN_BOOL(TSParserIsVisible(oid));
3531 }
3532
3533 Datum
3534 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3535 {
3536         Oid                     oid = PG_GETARG_OID(0);
3537
3538         if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3539                 PG_RETURN_NULL();
3540
3541         PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3542 }
3543
3544 Datum
3545 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3546 {
3547         Oid                     oid = PG_GETARG_OID(0);
3548
3549         if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3550                 PG_RETURN_NULL();
3551
3552         PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3553 }
3554
3555 Datum
3556 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3557 {
3558         Oid                     oid = PG_GETARG_OID(0);
3559
3560         if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3561                 PG_RETURN_NULL();
3562
3563         PG_RETURN_BOOL(TSConfigIsVisible(oid));
3564 }
3565
3566 Datum
3567 pg_my_temp_schema(PG_FUNCTION_ARGS)
3568 {
3569         PG_RETURN_OID(myTempNamespace);
3570 }
3571
3572 Datum
3573 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3574 {
3575         Oid                     oid = PG_GETARG_OID(0);
3576
3577         PG_RETURN_BOOL(isOtherTempNamespace(oid));
3578 }