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