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