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