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