]> granicus.if.org Git - postgresql/blob - src/backend/catalog/namespace.c
pgindent run for 9.4
[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, bool missing_schema_ok)
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, missing_schema_ok);
1577                 if (missing_schema_ok && !OidIsValid(namespaceId))
1578                         return NULL;
1579         }
1580         else
1581         {
1582                 /* flag to indicate we need namespace search */
1583                 namespaceId = InvalidOid;
1584                 recomputeNamespacePath();
1585         }
1586
1587         /* Search syscache by name only */
1588         catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1589
1590         /*
1591          * In typical scenarios, most if not all of the operators found by the
1592          * catcache search will end up getting returned; and there can be quite a
1593          * few, for common operator names such as '=' or '+'.  To reduce the time
1594          * spent in palloc, we allocate the result space as an array large enough
1595          * to hold all the operators.  The original coding of this routine did a
1596          * separate palloc for each operator, but profiling revealed that the
1597          * pallocs used an unreasonably large fraction of parsing time.
1598          */
1599 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1600
1601         if (catlist->n_members > 0)
1602                 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1603
1604         for (i = 0; i < catlist->n_members; i++)
1605         {
1606                 HeapTuple       opertup = &catlist->members[i]->tuple;
1607                 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1608                 int                     pathpos = 0;
1609                 FuncCandidateList newResult;
1610
1611                 /* Ignore operators of wrong kind, if specific kind requested */
1612                 if (oprkind && operform->oprkind != oprkind)
1613                         continue;
1614
1615                 if (OidIsValid(namespaceId))
1616                 {
1617                         /* Consider only opers in specified namespace */
1618                         if (operform->oprnamespace != namespaceId)
1619                                 continue;
1620                         /* No need to check args, they must all be different */
1621                 }
1622                 else
1623                 {
1624                         /*
1625                          * Consider only opers that are in the search path and are not in
1626                          * the temp namespace.
1627                          */
1628                         ListCell   *nsp;
1629
1630                         foreach(nsp, activeSearchPath)
1631                         {
1632                                 if (operform->oprnamespace == lfirst_oid(nsp) &&
1633                                         operform->oprnamespace != myTempNamespace)
1634                                         break;
1635                                 pathpos++;
1636                         }
1637                         if (nsp == NULL)
1638                                 continue;               /* oper is not in search path */
1639
1640                         /*
1641                          * Okay, it's in the search path, but does it have the same
1642                          * arguments as something we already accepted?  If so, keep only
1643                          * the one that appears earlier in the search path.
1644                          *
1645                          * If we have an ordered list from SearchSysCacheList (the normal
1646                          * case), then any conflicting oper must immediately adjoin this
1647                          * one in the list, so we only need to look at the newest result
1648                          * item.  If we have an unordered list, we have to scan the whole
1649                          * result list.
1650                          */
1651                         if (resultList)
1652                         {
1653                                 FuncCandidateList prevResult;
1654
1655                                 if (catlist->ordered)
1656                                 {
1657                                         if (operform->oprleft == resultList->args[0] &&
1658                                                 operform->oprright == resultList->args[1])
1659                                                 prevResult = resultList;
1660                                         else
1661                                                 prevResult = NULL;
1662                                 }
1663                                 else
1664                                 {
1665                                         for (prevResult = resultList;
1666                                                  prevResult;
1667                                                  prevResult = prevResult->next)
1668                                         {
1669                                                 if (operform->oprleft == prevResult->args[0] &&
1670                                                         operform->oprright == prevResult->args[1])
1671                                                         break;
1672                                         }
1673                                 }
1674                                 if (prevResult)
1675                                 {
1676                                         /* We have a match with a previous result */
1677                                         Assert(pathpos != prevResult->pathpos);
1678                                         if (pathpos > prevResult->pathpos)
1679                                                 continue;               /* keep previous result */
1680                                         /* replace previous result */
1681                                         prevResult->pathpos = pathpos;
1682                                         prevResult->oid = HeapTupleGetOid(opertup);
1683                                         continue;       /* args are same, of course */
1684                                 }
1685                         }
1686                 }
1687
1688                 /*
1689                  * Okay to add it to result list
1690                  */
1691                 newResult = (FuncCandidateList) (resultSpace + nextResult);
1692                 nextResult += SPACE_PER_OP;
1693
1694                 newResult->pathpos = pathpos;
1695                 newResult->oid = HeapTupleGetOid(opertup);
1696                 newResult->nargs = 2;
1697                 newResult->nvargs = 0;
1698                 newResult->ndargs = 0;
1699                 newResult->argnumbers = NULL;
1700                 newResult->args[0] = operform->oprleft;
1701                 newResult->args[1] = operform->oprright;
1702                 newResult->next = resultList;
1703                 resultList = newResult;
1704         }
1705
1706         ReleaseSysCacheList(catlist);
1707
1708         return resultList;
1709 }
1710
1711 /*
1712  * OperatorIsVisible
1713  *              Determine whether an operator (identified by OID) is visible in the
1714  *              current search path.  Visible means "would be found by searching
1715  *              for the unqualified operator name with exact argument matches".
1716  */
1717 bool
1718 OperatorIsVisible(Oid oprid)
1719 {
1720         HeapTuple       oprtup;
1721         Form_pg_operator oprform;
1722         Oid                     oprnamespace;
1723         bool            visible;
1724
1725         oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1726         if (!HeapTupleIsValid(oprtup))
1727                 elog(ERROR, "cache lookup failed for operator %u", oprid);
1728         oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1729
1730         recomputeNamespacePath();
1731
1732         /*
1733          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1734          * the system namespace are surely in the path and so we needn't even do
1735          * list_member_oid() for them.
1736          */
1737         oprnamespace = oprform->oprnamespace;
1738         if (oprnamespace != PG_CATALOG_NAMESPACE &&
1739                 !list_member_oid(activeSearchPath, oprnamespace))
1740                 visible = false;
1741         else
1742         {
1743                 /*
1744                  * If it is in the path, it might still not be visible; it could be
1745                  * hidden by another operator of the same name and arguments earlier
1746                  * in the path.  So we must do a slow check to see if this is the same
1747                  * operator that would be found by OpernameGetOprid.
1748                  */
1749                 char       *oprname = NameStr(oprform->oprname);
1750
1751                 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1752                                                                         oprform->oprleft, oprform->oprright)
1753                                    == oprid);
1754         }
1755
1756         ReleaseSysCache(oprtup);
1757
1758         return visible;
1759 }
1760
1761
1762 /*
1763  * OpclassnameGetOpcid
1764  *              Try to resolve an unqualified index opclass name.
1765  *              Returns OID if opclass found in search path, else InvalidOid.
1766  *
1767  * This is essentially the same as TypenameGetTypid, but we have to have
1768  * an extra argument for the index AM OID.
1769  */
1770 Oid
1771 OpclassnameGetOpcid(Oid amid, const char *opcname)
1772 {
1773         Oid                     opcid;
1774         ListCell   *l;
1775
1776         recomputeNamespacePath();
1777
1778         foreach(l, activeSearchPath)
1779         {
1780                 Oid                     namespaceId = lfirst_oid(l);
1781
1782                 if (namespaceId == myTempNamespace)
1783                         continue;                       /* do not look in temp namespace */
1784
1785                 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1786                                                                 ObjectIdGetDatum(amid),
1787                                                                 PointerGetDatum(opcname),
1788                                                                 ObjectIdGetDatum(namespaceId));
1789                 if (OidIsValid(opcid))
1790                         return opcid;
1791         }
1792
1793         /* Not found in path */
1794         return InvalidOid;
1795 }
1796
1797 /*
1798  * OpclassIsVisible
1799  *              Determine whether an opclass (identified by OID) is visible in the
1800  *              current search path.  Visible means "would be found by searching
1801  *              for the unqualified opclass name".
1802  */
1803 bool
1804 OpclassIsVisible(Oid opcid)
1805 {
1806         HeapTuple       opctup;
1807         Form_pg_opclass opcform;
1808         Oid                     opcnamespace;
1809         bool            visible;
1810
1811         opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1812         if (!HeapTupleIsValid(opctup))
1813                 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1814         opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1815
1816         recomputeNamespacePath();
1817
1818         /*
1819          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1820          * the system namespace are surely in the path and so we needn't even do
1821          * list_member_oid() for them.
1822          */
1823         opcnamespace = opcform->opcnamespace;
1824         if (opcnamespace != PG_CATALOG_NAMESPACE &&
1825                 !list_member_oid(activeSearchPath, opcnamespace))
1826                 visible = false;
1827         else
1828         {
1829                 /*
1830                  * If it is in the path, it might still not be visible; it could be
1831                  * hidden by another opclass of the same name earlier in the path. So
1832                  * we must do a slow check to see if this opclass would be found by
1833                  * OpclassnameGetOpcid.
1834                  */
1835                 char       *opcname = NameStr(opcform->opcname);
1836
1837                 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1838         }
1839
1840         ReleaseSysCache(opctup);
1841
1842         return visible;
1843 }
1844
1845 /*
1846  * OpfamilynameGetOpfid
1847  *              Try to resolve an unqualified index opfamily name.
1848  *              Returns OID if opfamily found in search path, else InvalidOid.
1849  *
1850  * This is essentially the same as TypenameGetTypid, but we have to have
1851  * an extra argument for the index AM OID.
1852  */
1853 Oid
1854 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1855 {
1856         Oid                     opfid;
1857         ListCell   *l;
1858
1859         recomputeNamespacePath();
1860
1861         foreach(l, activeSearchPath)
1862         {
1863                 Oid                     namespaceId = lfirst_oid(l);
1864
1865                 if (namespaceId == myTempNamespace)
1866                         continue;                       /* do not look in temp namespace */
1867
1868                 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1869                                                                 ObjectIdGetDatum(amid),
1870                                                                 PointerGetDatum(opfname),
1871                                                                 ObjectIdGetDatum(namespaceId));
1872                 if (OidIsValid(opfid))
1873                         return opfid;
1874         }
1875
1876         /* Not found in path */
1877         return InvalidOid;
1878 }
1879
1880 /*
1881  * OpfamilyIsVisible
1882  *              Determine whether an opfamily (identified by OID) is visible in the
1883  *              current search path.  Visible means "would be found by searching
1884  *              for the unqualified opfamily name".
1885  */
1886 bool
1887 OpfamilyIsVisible(Oid opfid)
1888 {
1889         HeapTuple       opftup;
1890         Form_pg_opfamily opfform;
1891         Oid                     opfnamespace;
1892         bool            visible;
1893
1894         opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1895         if (!HeapTupleIsValid(opftup))
1896                 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1897         opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1898
1899         recomputeNamespacePath();
1900
1901         /*
1902          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1903          * the system namespace are surely in the path and so we needn't even do
1904          * list_member_oid() for them.
1905          */
1906         opfnamespace = opfform->opfnamespace;
1907         if (opfnamespace != PG_CATALOG_NAMESPACE &&
1908                 !list_member_oid(activeSearchPath, opfnamespace))
1909                 visible = false;
1910         else
1911         {
1912                 /*
1913                  * If it is in the path, it might still not be visible; it could be
1914                  * hidden by another opfamily of the same name earlier in the path. So
1915                  * we must do a slow check to see if this opfamily would be found by
1916                  * OpfamilynameGetOpfid.
1917                  */
1918                 char       *opfname = NameStr(opfform->opfname);
1919
1920                 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1921         }
1922
1923         ReleaseSysCache(opftup);
1924
1925         return visible;
1926 }
1927
1928 /*
1929  * CollationGetCollid
1930  *              Try to resolve an unqualified collation name.
1931  *              Returns OID if collation found in search path, else InvalidOid.
1932  */
1933 Oid
1934 CollationGetCollid(const char *collname)
1935 {
1936         int32           dbencoding = GetDatabaseEncoding();
1937         ListCell   *l;
1938
1939         recomputeNamespacePath();
1940
1941         foreach(l, activeSearchPath)
1942         {
1943                 Oid                     namespaceId = lfirst_oid(l);
1944                 Oid                     collid;
1945
1946                 if (namespaceId == myTempNamespace)
1947                         continue;                       /* do not look in temp namespace */
1948
1949                 /* Check for database-encoding-specific entry */
1950                 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1951                                                                  PointerGetDatum(collname),
1952                                                                  Int32GetDatum(dbencoding),
1953                                                                  ObjectIdGetDatum(namespaceId));
1954                 if (OidIsValid(collid))
1955                         return collid;
1956
1957                 /* Check for any-encoding entry */
1958                 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1959                                                                  PointerGetDatum(collname),
1960                                                                  Int32GetDatum(-1),
1961                                                                  ObjectIdGetDatum(namespaceId));
1962                 if (OidIsValid(collid))
1963                         return collid;
1964         }
1965
1966         /* Not found in path */
1967         return InvalidOid;
1968 }
1969
1970 /*
1971  * CollationIsVisible
1972  *              Determine whether a collation (identified by OID) is visible in the
1973  *              current search path.  Visible means "would be found by searching
1974  *              for the unqualified collation name".
1975  */
1976 bool
1977 CollationIsVisible(Oid collid)
1978 {
1979         HeapTuple       colltup;
1980         Form_pg_collation collform;
1981         Oid                     collnamespace;
1982         bool            visible;
1983
1984         colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1985         if (!HeapTupleIsValid(colltup))
1986                 elog(ERROR, "cache lookup failed for collation %u", collid);
1987         collform = (Form_pg_collation) GETSTRUCT(colltup);
1988
1989         recomputeNamespacePath();
1990
1991         /*
1992          * Quick check: if it ain't in the path at all, it ain't visible. Items in
1993          * the system namespace are surely in the path and so we needn't even do
1994          * list_member_oid() for them.
1995          */
1996         collnamespace = collform->collnamespace;
1997         if (collnamespace != PG_CATALOG_NAMESPACE &&
1998                 !list_member_oid(activeSearchPath, collnamespace))
1999                 visible = false;
2000         else
2001         {
2002                 /*
2003                  * If it is in the path, it might still not be visible; it could be
2004                  * hidden by another conversion of the same name earlier in the path.
2005                  * So we must do a slow check to see if this conversion would be found
2006                  * by CollationGetCollid.
2007                  */
2008                 char       *collname = NameStr(collform->collname);
2009
2010                 visible = (CollationGetCollid(collname) == collid);
2011         }
2012
2013         ReleaseSysCache(colltup);
2014
2015         return visible;
2016 }
2017
2018
2019 /*
2020  * ConversionGetConid
2021  *              Try to resolve an unqualified conversion name.
2022  *              Returns OID if conversion found in search path, else InvalidOid.
2023  *
2024  * This is essentially the same as RelnameGetRelid.
2025  */
2026 Oid
2027 ConversionGetConid(const char *conname)
2028 {
2029         Oid                     conid;
2030         ListCell   *l;
2031
2032         recomputeNamespacePath();
2033
2034         foreach(l, activeSearchPath)
2035         {
2036                 Oid                     namespaceId = lfirst_oid(l);
2037
2038                 if (namespaceId == myTempNamespace)
2039                         continue;                       /* do not look in temp namespace */
2040
2041                 conid = GetSysCacheOid2(CONNAMENSP,
2042                                                                 PointerGetDatum(conname),
2043                                                                 ObjectIdGetDatum(namespaceId));
2044                 if (OidIsValid(conid))
2045                         return conid;
2046         }
2047
2048         /* Not found in path */
2049         return InvalidOid;
2050 }
2051
2052 /*
2053  * ConversionIsVisible
2054  *              Determine whether a conversion (identified by OID) is visible in the
2055  *              current search path.  Visible means "would be found by searching
2056  *              for the unqualified conversion name".
2057  */
2058 bool
2059 ConversionIsVisible(Oid conid)
2060 {
2061         HeapTuple       contup;
2062         Form_pg_conversion conform;
2063         Oid                     connamespace;
2064         bool            visible;
2065
2066         contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2067         if (!HeapTupleIsValid(contup))
2068                 elog(ERROR, "cache lookup failed for conversion %u", conid);
2069         conform = (Form_pg_conversion) GETSTRUCT(contup);
2070
2071         recomputeNamespacePath();
2072
2073         /*
2074          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2075          * the system namespace are surely in the path and so we needn't even do
2076          * list_member_oid() for them.
2077          */
2078         connamespace = conform->connamespace;
2079         if (connamespace != PG_CATALOG_NAMESPACE &&
2080                 !list_member_oid(activeSearchPath, connamespace))
2081                 visible = false;
2082         else
2083         {
2084                 /*
2085                  * If it is in the path, it might still not be visible; it could be
2086                  * hidden by another conversion of the same name earlier in the path.
2087                  * So we must do a slow check to see if this conversion would be found
2088                  * by ConversionGetConid.
2089                  */
2090                 char       *conname = NameStr(conform->conname);
2091
2092                 visible = (ConversionGetConid(conname) == conid);
2093         }
2094
2095         ReleaseSysCache(contup);
2096
2097         return visible;
2098 }
2099
2100 /*
2101  * get_ts_parser_oid - find a TS parser by possibly qualified name
2102  *
2103  * If not found, returns InvalidOid if missing_ok, else throws error
2104  */
2105 Oid
2106 get_ts_parser_oid(List *names, bool missing_ok)
2107 {
2108         char       *schemaname;
2109         char       *parser_name;
2110         Oid                     namespaceId;
2111         Oid                     prsoid = InvalidOid;
2112         ListCell   *l;
2113
2114         /* deconstruct the name list */
2115         DeconstructQualifiedName(names, &schemaname, &parser_name);
2116
2117         if (schemaname)
2118         {
2119                 /* use exact schema given */
2120                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2121                 if (missing_ok && !OidIsValid(namespaceId))
2122                         prsoid = InvalidOid;
2123                 else
2124                         prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2125                                                                          PointerGetDatum(parser_name),
2126                                                                          ObjectIdGetDatum(namespaceId));
2127         }
2128         else
2129         {
2130                 /* search for it in search path */
2131                 recomputeNamespacePath();
2132
2133                 foreach(l, activeSearchPath)
2134                 {
2135                         namespaceId = lfirst_oid(l);
2136
2137                         if (namespaceId == myTempNamespace)
2138                                 continue;               /* do not look in temp namespace */
2139
2140                         prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2141                                                                          PointerGetDatum(parser_name),
2142                                                                          ObjectIdGetDatum(namespaceId));
2143                         if (OidIsValid(prsoid))
2144                                 break;
2145                 }
2146         }
2147
2148         if (!OidIsValid(prsoid) && !missing_ok)
2149                 ereport(ERROR,
2150                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2151                                  errmsg("text search parser \"%s\" does not exist",
2152                                                 NameListToString(names))));
2153
2154         return prsoid;
2155 }
2156
2157 /*
2158  * TSParserIsVisible
2159  *              Determine whether a parser (identified by OID) is visible in the
2160  *              current search path.  Visible means "would be found by searching
2161  *              for the unqualified parser name".
2162  */
2163 bool
2164 TSParserIsVisible(Oid prsId)
2165 {
2166         HeapTuple       tup;
2167         Form_pg_ts_parser form;
2168         Oid                     namespace;
2169         bool            visible;
2170
2171         tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2172         if (!HeapTupleIsValid(tup))
2173                 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2174         form = (Form_pg_ts_parser) GETSTRUCT(tup);
2175
2176         recomputeNamespacePath();
2177
2178         /*
2179          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2180          * the system namespace are surely in the path and so we needn't even do
2181          * list_member_oid() for them.
2182          */
2183         namespace = form->prsnamespace;
2184         if (namespace != PG_CATALOG_NAMESPACE &&
2185                 !list_member_oid(activeSearchPath, namespace))
2186                 visible = false;
2187         else
2188         {
2189                 /*
2190                  * If it is in the path, it might still not be visible; it could be
2191                  * hidden by another parser of the same name earlier in the path. So
2192                  * we must do a slow check for conflicting parsers.
2193                  */
2194                 char       *name = NameStr(form->prsname);
2195                 ListCell   *l;
2196
2197                 visible = false;
2198                 foreach(l, activeSearchPath)
2199                 {
2200                         Oid                     namespaceId = lfirst_oid(l);
2201
2202                         if (namespaceId == myTempNamespace)
2203                                 continue;               /* do not look in temp namespace */
2204
2205                         if (namespaceId == namespace)
2206                         {
2207                                 /* Found it first in path */
2208                                 visible = true;
2209                                 break;
2210                         }
2211                         if (SearchSysCacheExists2(TSPARSERNAMENSP,
2212                                                                           PointerGetDatum(name),
2213                                                                           ObjectIdGetDatum(namespaceId)))
2214                         {
2215                                 /* Found something else first in path */
2216                                 break;
2217                         }
2218                 }
2219         }
2220
2221         ReleaseSysCache(tup);
2222
2223         return visible;
2224 }
2225
2226 /*
2227  * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2228  *
2229  * If not found, returns InvalidOid if failOK, else throws error
2230  */
2231 Oid
2232 get_ts_dict_oid(List *names, bool missing_ok)
2233 {
2234         char       *schemaname;
2235         char       *dict_name;
2236         Oid                     namespaceId;
2237         Oid                     dictoid = InvalidOid;
2238         ListCell   *l;
2239
2240         /* deconstruct the name list */
2241         DeconstructQualifiedName(names, &schemaname, &dict_name);
2242
2243         if (schemaname)
2244         {
2245                 /* use exact schema given */
2246                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2247                 if (missing_ok && !OidIsValid(namespaceId))
2248                         dictoid = InvalidOid;
2249                 else
2250                         dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2251                                                                           PointerGetDatum(dict_name),
2252                                                                           ObjectIdGetDatum(namespaceId));
2253         }
2254         else
2255         {
2256                 /* search for it in search path */
2257                 recomputeNamespacePath();
2258
2259                 foreach(l, activeSearchPath)
2260                 {
2261                         namespaceId = lfirst_oid(l);
2262
2263                         if (namespaceId == myTempNamespace)
2264                                 continue;               /* do not look in temp namespace */
2265
2266                         dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2267                                                                           PointerGetDatum(dict_name),
2268                                                                           ObjectIdGetDatum(namespaceId));
2269                         if (OidIsValid(dictoid))
2270                                 break;
2271                 }
2272         }
2273
2274         if (!OidIsValid(dictoid) && !missing_ok)
2275                 ereport(ERROR,
2276                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2277                                  errmsg("text search dictionary \"%s\" does not exist",
2278                                                 NameListToString(names))));
2279
2280         return dictoid;
2281 }
2282
2283 /*
2284  * TSDictionaryIsVisible
2285  *              Determine whether a dictionary (identified by OID) is visible in the
2286  *              current search path.  Visible means "would be found by searching
2287  *              for the unqualified dictionary name".
2288  */
2289 bool
2290 TSDictionaryIsVisible(Oid dictId)
2291 {
2292         HeapTuple       tup;
2293         Form_pg_ts_dict form;
2294         Oid                     namespace;
2295         bool            visible;
2296
2297         tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2298         if (!HeapTupleIsValid(tup))
2299                 elog(ERROR, "cache lookup failed for text search dictionary %u",
2300                          dictId);
2301         form = (Form_pg_ts_dict) GETSTRUCT(tup);
2302
2303         recomputeNamespacePath();
2304
2305         /*
2306          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2307          * the system namespace are surely in the path and so we needn't even do
2308          * list_member_oid() for them.
2309          */
2310         namespace = form->dictnamespace;
2311         if (namespace != PG_CATALOG_NAMESPACE &&
2312                 !list_member_oid(activeSearchPath, namespace))
2313                 visible = false;
2314         else
2315         {
2316                 /*
2317                  * If it is in the path, it might still not be visible; it could be
2318                  * hidden by another dictionary of the same name earlier in the path.
2319                  * So we must do a slow check for conflicting dictionaries.
2320                  */
2321                 char       *name = NameStr(form->dictname);
2322                 ListCell   *l;
2323
2324                 visible = false;
2325                 foreach(l, activeSearchPath)
2326                 {
2327                         Oid                     namespaceId = lfirst_oid(l);
2328
2329                         if (namespaceId == myTempNamespace)
2330                                 continue;               /* do not look in temp namespace */
2331
2332                         if (namespaceId == namespace)
2333                         {
2334                                 /* Found it first in path */
2335                                 visible = true;
2336                                 break;
2337                         }
2338                         if (SearchSysCacheExists2(TSDICTNAMENSP,
2339                                                                           PointerGetDatum(name),
2340                                                                           ObjectIdGetDatum(namespaceId)))
2341                         {
2342                                 /* Found something else first in path */
2343                                 break;
2344                         }
2345                 }
2346         }
2347
2348         ReleaseSysCache(tup);
2349
2350         return visible;
2351 }
2352
2353 /*
2354  * get_ts_template_oid - find a TS template by possibly qualified name
2355  *
2356  * If not found, returns InvalidOid if missing_ok, else throws error
2357  */
2358 Oid
2359 get_ts_template_oid(List *names, bool missing_ok)
2360 {
2361         char       *schemaname;
2362         char       *template_name;
2363         Oid                     namespaceId;
2364         Oid                     tmploid = InvalidOid;
2365         ListCell   *l;
2366
2367         /* deconstruct the name list */
2368         DeconstructQualifiedName(names, &schemaname, &template_name);
2369
2370         if (schemaname)
2371         {
2372                 /* use exact schema given */
2373                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2374                 if (missing_ok && !OidIsValid(namespaceId))
2375                         tmploid = InvalidOid;
2376                 else
2377                         tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2378                                                                           PointerGetDatum(template_name),
2379                                                                           ObjectIdGetDatum(namespaceId));
2380         }
2381         else
2382         {
2383                 /* search for it in search path */
2384                 recomputeNamespacePath();
2385
2386                 foreach(l, activeSearchPath)
2387                 {
2388                         namespaceId = lfirst_oid(l);
2389
2390                         if (namespaceId == myTempNamespace)
2391                                 continue;               /* do not look in temp namespace */
2392
2393                         tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2394                                                                           PointerGetDatum(template_name),
2395                                                                           ObjectIdGetDatum(namespaceId));
2396                         if (OidIsValid(tmploid))
2397                                 break;
2398                 }
2399         }
2400
2401         if (!OidIsValid(tmploid) && !missing_ok)
2402                 ereport(ERROR,
2403                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2404                                  errmsg("text search template \"%s\" does not exist",
2405                                                 NameListToString(names))));
2406
2407         return tmploid;
2408 }
2409
2410 /*
2411  * TSTemplateIsVisible
2412  *              Determine whether a template (identified by OID) is visible in the
2413  *              current search path.  Visible means "would be found by searching
2414  *              for the unqualified template name".
2415  */
2416 bool
2417 TSTemplateIsVisible(Oid tmplId)
2418 {
2419         HeapTuple       tup;
2420         Form_pg_ts_template form;
2421         Oid                     namespace;
2422         bool            visible;
2423
2424         tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2425         if (!HeapTupleIsValid(tup))
2426                 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2427         form = (Form_pg_ts_template) GETSTRUCT(tup);
2428
2429         recomputeNamespacePath();
2430
2431         /*
2432          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2433          * the system namespace are surely in the path and so we needn't even do
2434          * list_member_oid() for them.
2435          */
2436         namespace = form->tmplnamespace;
2437         if (namespace != PG_CATALOG_NAMESPACE &&
2438                 !list_member_oid(activeSearchPath, namespace))
2439                 visible = false;
2440         else
2441         {
2442                 /*
2443                  * If it is in the path, it might still not be visible; it could be
2444                  * hidden by another template of the same name earlier in the path. So
2445                  * we must do a slow check for conflicting templates.
2446                  */
2447                 char       *name = NameStr(form->tmplname);
2448                 ListCell   *l;
2449
2450                 visible = false;
2451                 foreach(l, activeSearchPath)
2452                 {
2453                         Oid                     namespaceId = lfirst_oid(l);
2454
2455                         if (namespaceId == myTempNamespace)
2456                                 continue;               /* do not look in temp namespace */
2457
2458                         if (namespaceId == namespace)
2459                         {
2460                                 /* Found it first in path */
2461                                 visible = true;
2462                                 break;
2463                         }
2464                         if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2465                                                                           PointerGetDatum(name),
2466                                                                           ObjectIdGetDatum(namespaceId)))
2467                         {
2468                                 /* Found something else first in path */
2469                                 break;
2470                         }
2471                 }
2472         }
2473
2474         ReleaseSysCache(tup);
2475
2476         return visible;
2477 }
2478
2479 /*
2480  * get_ts_config_oid - find a TS config by possibly qualified name
2481  *
2482  * If not found, returns InvalidOid if missing_ok, else throws error
2483  */
2484 Oid
2485 get_ts_config_oid(List *names, bool missing_ok)
2486 {
2487         char       *schemaname;
2488         char       *config_name;
2489         Oid                     namespaceId;
2490         Oid                     cfgoid = InvalidOid;
2491         ListCell   *l;
2492
2493         /* deconstruct the name list */
2494         DeconstructQualifiedName(names, &schemaname, &config_name);
2495
2496         if (schemaname)
2497         {
2498                 /* use exact schema given */
2499                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2500                 if (missing_ok && !OidIsValid(namespaceId))
2501                         cfgoid = InvalidOid;
2502                 else
2503                         cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2504                                                                          PointerGetDatum(config_name),
2505                                                                          ObjectIdGetDatum(namespaceId));
2506         }
2507         else
2508         {
2509                 /* search for it in search path */
2510                 recomputeNamespacePath();
2511
2512                 foreach(l, activeSearchPath)
2513                 {
2514                         namespaceId = lfirst_oid(l);
2515
2516                         if (namespaceId == myTempNamespace)
2517                                 continue;               /* do not look in temp namespace */
2518
2519                         cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2520                                                                          PointerGetDatum(config_name),
2521                                                                          ObjectIdGetDatum(namespaceId));
2522                         if (OidIsValid(cfgoid))
2523                                 break;
2524                 }
2525         }
2526
2527         if (!OidIsValid(cfgoid) && !missing_ok)
2528                 ereport(ERROR,
2529                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
2530                                  errmsg("text search configuration \"%s\" does not exist",
2531                                                 NameListToString(names))));
2532
2533         return cfgoid;
2534 }
2535
2536 /*
2537  * TSConfigIsVisible
2538  *              Determine whether a text search configuration (identified by OID)
2539  *              is visible in the current search path.  Visible means "would be found
2540  *              by searching for the unqualified text search configuration name".
2541  */
2542 bool
2543 TSConfigIsVisible(Oid cfgid)
2544 {
2545         HeapTuple       tup;
2546         Form_pg_ts_config form;
2547         Oid                     namespace;
2548         bool            visible;
2549
2550         tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2551         if (!HeapTupleIsValid(tup))
2552                 elog(ERROR, "cache lookup failed for text search configuration %u",
2553                          cfgid);
2554         form = (Form_pg_ts_config) GETSTRUCT(tup);
2555
2556         recomputeNamespacePath();
2557
2558         /*
2559          * Quick check: if it ain't in the path at all, it ain't visible. Items in
2560          * the system namespace are surely in the path and so we needn't even do
2561          * list_member_oid() for them.
2562          */
2563         namespace = form->cfgnamespace;
2564         if (namespace != PG_CATALOG_NAMESPACE &&
2565                 !list_member_oid(activeSearchPath, namespace))
2566                 visible = false;
2567         else
2568         {
2569                 /*
2570                  * If it is in the path, it might still not be visible; it could be
2571                  * hidden by another configuration of the same name earlier in the
2572                  * path. So we must do a slow check for conflicting configurations.
2573                  */
2574                 char       *name = NameStr(form->cfgname);
2575                 ListCell   *l;
2576
2577                 visible = false;
2578                 foreach(l, activeSearchPath)
2579                 {
2580                         Oid                     namespaceId = lfirst_oid(l);
2581
2582                         if (namespaceId == myTempNamespace)
2583                                 continue;               /* do not look in temp namespace */
2584
2585                         if (namespaceId == namespace)
2586                         {
2587                                 /* Found it first in path */
2588                                 visible = true;
2589                                 break;
2590                         }
2591                         if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2592                                                                           PointerGetDatum(name),
2593                                                                           ObjectIdGetDatum(namespaceId)))
2594                         {
2595                                 /* Found something else first in path */
2596                                 break;
2597                         }
2598                 }
2599         }
2600
2601         ReleaseSysCache(tup);
2602
2603         return visible;
2604 }
2605
2606
2607 /*
2608  * DeconstructQualifiedName
2609  *              Given a possibly-qualified name expressed as a list of String nodes,
2610  *              extract the schema name and object name.
2611  *
2612  * *nspname_p is set to NULL if there is no explicit schema name.
2613  */
2614 void
2615 DeconstructQualifiedName(List *names,
2616                                                  char **nspname_p,
2617                                                  char **objname_p)
2618 {
2619         char       *catalogname;
2620         char       *schemaname = NULL;
2621         char       *objname = NULL;
2622
2623         switch (list_length(names))
2624         {
2625                 case 1:
2626                         objname = strVal(linitial(names));
2627                         break;
2628                 case 2:
2629                         schemaname = strVal(linitial(names));
2630                         objname = strVal(lsecond(names));
2631                         break;
2632                 case 3:
2633                         catalogname = strVal(linitial(names));
2634                         schemaname = strVal(lsecond(names));
2635                         objname = strVal(lthird(names));
2636
2637                         /*
2638                          * We check the catalog name and then ignore it.
2639                          */
2640                         if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2641                                 ereport(ERROR,
2642                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2643                                   errmsg("cross-database references are not implemented: %s",
2644                                                  NameListToString(names))));
2645                         break;
2646                 default:
2647                         ereport(ERROR,
2648                                         (errcode(ERRCODE_SYNTAX_ERROR),
2649                                 errmsg("improper qualified name (too many dotted names): %s",
2650                                            NameListToString(names))));
2651                         break;
2652         }
2653
2654         *nspname_p = schemaname;
2655         *objname_p = objname;
2656 }
2657
2658 /*
2659  * LookupNamespaceNoError
2660  *              Look up a schema name.
2661  *
2662  * Returns the namespace OID, or InvalidOid if not found.
2663  *
2664  * Note this does NOT perform any permissions check --- callers are
2665  * responsible for being sure that an appropriate check is made.
2666  * In the majority of cases LookupExplicitNamespace is preferable.
2667  */
2668 Oid
2669 LookupNamespaceNoError(const char *nspname)
2670 {
2671         /* check for pg_temp alias */
2672         if (strcmp(nspname, "pg_temp") == 0)
2673         {
2674                 if (OidIsValid(myTempNamespace))
2675                 {
2676                         InvokeNamespaceSearchHook(myTempNamespace, true);
2677                         return myTempNamespace;
2678                 }
2679
2680                 /*
2681                  * Since this is used only for looking up existing objects, there is
2682                  * no point in trying to initialize the temp namespace here; and doing
2683                  * so might create problems for some callers. Just report "not found".
2684                  */
2685                 return InvalidOid;
2686         }
2687
2688         return get_namespace_oid(nspname, true);
2689 }
2690
2691 /*
2692  * LookupExplicitNamespace
2693  *              Process an explicitly-specified schema name: look up the schema
2694  *              and verify we have USAGE (lookup) rights in it.
2695  *
2696  * Returns the namespace OID
2697  */
2698 Oid
2699 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2700 {
2701         Oid                     namespaceId;
2702         AclResult       aclresult;
2703
2704         /* check for pg_temp alias */
2705         if (strcmp(nspname, "pg_temp") == 0)
2706         {
2707                 if (OidIsValid(myTempNamespace))
2708                         return myTempNamespace;
2709
2710                 /*
2711                  * Since this is used only for looking up existing objects, there is
2712                  * no point in trying to initialize the temp namespace here; and doing
2713                  * so might create problems for some callers --- just fall through.
2714                  */
2715         }
2716
2717         namespaceId = get_namespace_oid(nspname, missing_ok);
2718         if (missing_ok && !OidIsValid(namespaceId))
2719                 return InvalidOid;
2720
2721         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2722         if (aclresult != ACLCHECK_OK)
2723                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2724                                            nspname);
2725         /* Schema search hook for this lookup */
2726         InvokeNamespaceSearchHook(namespaceId, true);
2727
2728         return namespaceId;
2729 }
2730
2731 /*
2732  * LookupCreationNamespace
2733  *              Look up the schema and verify we have CREATE rights on it.
2734  *
2735  * This is just like LookupExplicitNamespace except for the different
2736  * permission check, and that we are willing to create pg_temp if needed.
2737  *
2738  * Note: calling this may result in a CommandCounterIncrement operation,
2739  * if we have to create or clean out the temp namespace.
2740  */
2741 Oid
2742 LookupCreationNamespace(const char *nspname)
2743 {
2744         Oid                     namespaceId;
2745         AclResult       aclresult;
2746
2747         /* check for pg_temp alias */
2748         if (strcmp(nspname, "pg_temp") == 0)
2749         {
2750                 /* Initialize temp namespace if first time through */
2751                 if (!OidIsValid(myTempNamespace))
2752                         InitTempTableNamespace();
2753                 return myTempNamespace;
2754         }
2755
2756         namespaceId = get_namespace_oid(nspname, false);
2757
2758         aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2759         if (aclresult != ACLCHECK_OK)
2760                 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2761                                            nspname);
2762
2763         return namespaceId;
2764 }
2765
2766 /*
2767  * Common checks on switching namespaces.
2768  *
2769  * We complain if (1) the old and new namespaces are the same, (2) either the
2770  * old or new namespaces is a temporary schema (or temporary toast schema), or
2771  * (3) either the old or new namespaces is the TOAST schema.
2772  */
2773 void
2774 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2775 {
2776         if (oldNspOid == nspOid)
2777                 ereport(ERROR,
2778                                 (classid == RelationRelationId ?
2779                                  errcode(ERRCODE_DUPLICATE_TABLE) :
2780                                  classid == ProcedureRelationId ?
2781                                  errcode(ERRCODE_DUPLICATE_FUNCTION) :
2782                                  errcode(ERRCODE_DUPLICATE_OBJECT),
2783                                  errmsg("%s is already in schema \"%s\"",
2784                                                 getObjectDescriptionOids(classid, objid),
2785                                                 get_namespace_name(nspOid))));
2786
2787         /* disallow renaming into or out of temp schemas */
2788         if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2789                 ereport(ERROR,
2790                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2791                         errmsg("cannot move objects into or out of temporary schemas")));
2792
2793         /* same for TOAST schema */
2794         if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2795                 ereport(ERROR,
2796                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2797                                  errmsg("cannot move objects into or out of TOAST schema")));
2798 }
2799
2800 /*
2801  * QualifiedNameGetCreationNamespace
2802  *              Given a possibly-qualified name for an object (in List-of-Values
2803  *              format), determine what namespace the object should be created in.
2804  *              Also extract and return the object name (last component of list).
2805  *
2806  * Note: this does not apply any permissions check.  Callers must check
2807  * for CREATE rights on the selected namespace when appropriate.
2808  *
2809  * Note: calling this may result in a CommandCounterIncrement operation,
2810  * if we have to create or clean out the temp namespace.
2811  */
2812 Oid
2813 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2814 {
2815         char       *schemaname;
2816         Oid                     namespaceId;
2817
2818         /* deconstruct the name list */
2819         DeconstructQualifiedName(names, &schemaname, objname_p);
2820
2821         if (schemaname)
2822         {
2823                 /* check for pg_temp alias */
2824                 if (strcmp(schemaname, "pg_temp") == 0)
2825                 {
2826                         /* Initialize temp namespace if first time through */
2827                         if (!OidIsValid(myTempNamespace))
2828                                 InitTempTableNamespace();
2829                         return myTempNamespace;
2830                 }
2831                 /* use exact schema given */
2832                 namespaceId = get_namespace_oid(schemaname, false);
2833                 /* we do not check for USAGE rights here! */
2834         }
2835         else
2836         {
2837                 /* use the default creation namespace */
2838                 recomputeNamespacePath();
2839                 if (activeTempCreationPending)
2840                 {
2841                         /* Need to initialize temp namespace */
2842                         InitTempTableNamespace();
2843                         return myTempNamespace;
2844                 }
2845                 namespaceId = activeCreationNamespace;
2846                 if (!OidIsValid(namespaceId))
2847                         ereport(ERROR,
2848                                         (errcode(ERRCODE_UNDEFINED_SCHEMA),
2849                                          errmsg("no schema has been selected to create in")));
2850         }
2851
2852         return namespaceId;
2853 }
2854
2855 /*
2856  * get_namespace_oid - given a namespace name, look up the OID
2857  *
2858  * If missing_ok is false, throw an error if namespace name not found.  If
2859  * true, just return InvalidOid.
2860  */
2861 Oid
2862 get_namespace_oid(const char *nspname, bool missing_ok)
2863 {
2864         Oid                     oid;
2865
2866         oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2867         if (!OidIsValid(oid) && !missing_ok)
2868                 ereport(ERROR,
2869                                 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2870                                  errmsg("schema \"%s\" does not exist", nspname)));
2871
2872         return oid;
2873 }
2874
2875 /*
2876  * makeRangeVarFromNameList
2877  *              Utility routine to convert a qualified-name list into RangeVar form.
2878  */
2879 RangeVar *
2880 makeRangeVarFromNameList(List *names)
2881 {
2882         RangeVar   *rel = makeRangeVar(NULL, NULL, -1);
2883
2884         switch (list_length(names))
2885         {
2886                 case 1:
2887                         rel->relname = strVal(linitial(names));
2888                         break;
2889                 case 2:
2890                         rel->schemaname = strVal(linitial(names));
2891                         rel->relname = strVal(lsecond(names));
2892                         break;
2893                 case 3:
2894                         rel->catalogname = strVal(linitial(names));
2895                         rel->schemaname = strVal(lsecond(names));
2896                         rel->relname = strVal(lthird(names));
2897                         break;
2898                 default:
2899                         ereport(ERROR,
2900                                         (errcode(ERRCODE_SYNTAX_ERROR),
2901                                  errmsg("improper relation name (too many dotted names): %s",
2902                                                 NameListToString(names))));
2903                         break;
2904         }
2905
2906         return rel;
2907 }
2908
2909 /*
2910  * NameListToString
2911  *              Utility routine to convert a qualified-name list into a string.
2912  *
2913  * This is used primarily to form error messages, and so we do not quote
2914  * the list elements, for the sake of legibility.
2915  *
2916  * In most scenarios the list elements should always be Value strings,
2917  * but we also allow A_Star for the convenience of ColumnRef processing.
2918  */
2919 char *
2920 NameListToString(List *names)
2921 {
2922         StringInfoData string;
2923         ListCell   *l;
2924
2925         initStringInfo(&string);
2926
2927         foreach(l, names)
2928         {
2929                 Node       *name = (Node *) lfirst(l);
2930
2931                 if (l != list_head(names))
2932                         appendStringInfoChar(&string, '.');
2933
2934                 if (IsA(name, String))
2935                         appendStringInfoString(&string, strVal(name));
2936                 else if (IsA(name, A_Star))
2937                         appendStringInfoString(&string, "*");
2938                 else
2939                         elog(ERROR, "unexpected node type in name list: %d",
2940                                  (int) nodeTag(name));
2941         }
2942
2943         return string.data;
2944 }
2945
2946 /*
2947  * NameListToQuotedString
2948  *              Utility routine to convert a qualified-name list into a string.
2949  *
2950  * Same as above except that names will be double-quoted where necessary,
2951  * so the string could be re-parsed (eg, by textToQualifiedNameList).
2952  */
2953 char *
2954 NameListToQuotedString(List *names)
2955 {
2956         StringInfoData string;
2957         ListCell   *l;
2958
2959         initStringInfo(&string);
2960
2961         foreach(l, names)
2962         {
2963                 if (l != list_head(names))
2964                         appendStringInfoChar(&string, '.');
2965                 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2966         }
2967
2968         return string.data;
2969 }
2970
2971 /*
2972  * isTempNamespace - is the given namespace my temporary-table namespace?
2973  */
2974 bool
2975 isTempNamespace(Oid namespaceId)
2976 {
2977         if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2978                 return true;
2979         return false;
2980 }
2981
2982 /*
2983  * isTempToastNamespace - is the given namespace my temporary-toast-table
2984  *              namespace?
2985  */
2986 bool
2987 isTempToastNamespace(Oid namespaceId)
2988 {
2989         if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2990                 return true;
2991         return false;
2992 }
2993
2994 /*
2995  * isTempOrToastNamespace - is the given namespace my temporary-table
2996  *              namespace or my temporary-toast-table namespace?
2997  */
2998 bool
2999 isTempOrToastNamespace(Oid namespaceId)
3000 {
3001         if (OidIsValid(myTempNamespace) &&
3002          (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3003                 return true;
3004         return false;
3005 }
3006
3007 /*
3008  * isAnyTempNamespace - is the given namespace a temporary-table namespace
3009  * (either my own, or another backend's)?  Temporary-toast-table namespaces
3010  * are included, too.
3011  */
3012 bool
3013 isAnyTempNamespace(Oid namespaceId)
3014 {
3015         bool            result;
3016         char       *nspname;
3017
3018         /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3019         nspname = get_namespace_name(namespaceId);
3020         if (!nspname)
3021                 return false;                   /* no such namespace? */
3022         result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3023                 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3024         pfree(nspname);
3025         return result;
3026 }
3027
3028 /*
3029  * isOtherTempNamespace - is the given namespace some other backend's
3030  * temporary-table namespace (including temporary-toast-table namespaces)?
3031  *
3032  * Note: for most purposes in the C code, this function is obsolete.  Use
3033  * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3034  */
3035 bool
3036 isOtherTempNamespace(Oid namespaceId)
3037 {
3038         /* If it's my own temp namespace, say "false" */
3039         if (isTempOrToastNamespace(namespaceId))
3040                 return false;
3041         /* Else, if it's any temp namespace, say "true" */
3042         return isAnyTempNamespace(namespaceId);
3043 }
3044
3045 /*
3046  * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3047  * namespace (either my own, or another backend's), return the BackendId
3048  * that owns it.  Temporary-toast-table namespaces are included, too.
3049  * If it isn't a temp namespace, return InvalidBackendId.
3050  */
3051 int
3052 GetTempNamespaceBackendId(Oid namespaceId)
3053 {
3054         int                     result;
3055         char       *nspname;
3056
3057         /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3058         nspname = get_namespace_name(namespaceId);
3059         if (!nspname)
3060                 return InvalidBackendId;        /* no such namespace? */
3061         if (strncmp(nspname, "pg_temp_", 8) == 0)
3062                 result = atoi(nspname + 8);
3063         else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3064                 result = atoi(nspname + 14);
3065         else
3066                 result = InvalidBackendId;
3067         pfree(nspname);
3068         return result;
3069 }
3070
3071 /*
3072  * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3073  * which must already be assigned.  (This is only used when creating a toast
3074  * table for a temp table, so we must have already done InitTempTableNamespace)
3075  */
3076 Oid
3077 GetTempToastNamespace(void)
3078 {
3079         Assert(OidIsValid(myTempToastNamespace));
3080         return myTempToastNamespace;
3081 }
3082
3083
3084 /*
3085  * GetOverrideSearchPath - fetch current search path definition in form
3086  * used by PushOverrideSearchPath.
3087  *
3088  * The result structure is allocated in the specified memory context
3089  * (which might or might not be equal to CurrentMemoryContext); but any
3090  * junk created by revalidation calculations will be in CurrentMemoryContext.
3091  */
3092 OverrideSearchPath *
3093 GetOverrideSearchPath(MemoryContext context)
3094 {
3095         OverrideSearchPath *result;
3096         List       *schemas;
3097         MemoryContext oldcxt;
3098
3099         recomputeNamespacePath();
3100
3101         oldcxt = MemoryContextSwitchTo(context);
3102
3103         result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3104         schemas = list_copy(activeSearchPath);
3105         while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3106         {
3107                 if (linitial_oid(schemas) == myTempNamespace)
3108                         result->addTemp = true;
3109                 else
3110                 {
3111                         Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3112                         result->addCatalog = true;
3113                 }
3114                 schemas = list_delete_first(schemas);
3115         }
3116         result->schemas = schemas;
3117
3118         MemoryContextSwitchTo(oldcxt);
3119
3120         return result;
3121 }
3122
3123 /*
3124  * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3125  *
3126  * The result structure is allocated in CurrentMemoryContext.
3127  */
3128 OverrideSearchPath *
3129 CopyOverrideSearchPath(OverrideSearchPath *path)
3130 {
3131         OverrideSearchPath *result;
3132
3133         result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3134         result->schemas = list_copy(path->schemas);
3135         result->addCatalog = path->addCatalog;
3136         result->addTemp = path->addTemp;
3137
3138         return result;
3139 }
3140
3141 /*
3142  * OverrideSearchPathMatchesCurrent - does path match current setting?
3143  */
3144 bool
3145 OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
3146 {
3147         /* Easiest way to do this is GetOverrideSearchPath() and compare */
3148         bool            result;
3149         OverrideSearchPath *cur;
3150
3151         cur = GetOverrideSearchPath(CurrentMemoryContext);
3152         if (path->addCatalog == cur->addCatalog &&
3153                 path->addTemp == cur->addTemp &&
3154                 equal(path->schemas, cur->schemas))
3155                 result = true;
3156         else
3157                 result = false;
3158         list_free(cur->schemas);
3159         pfree(cur);
3160         return result;
3161 }
3162
3163 /*
3164  * PushOverrideSearchPath - temporarily override the search path
3165  *
3166  * We allow nested overrides, hence the push/pop terminology.  The GUC
3167  * search_path variable is ignored while an override is active.
3168  *
3169  * It's possible that newpath->useTemp is set but there is no longer any
3170  * active temp namespace, if the path was saved during a transaction that
3171  * created a temp namespace and was later rolled back.  In that case we just
3172  * ignore useTemp.  A plausible alternative would be to create a new temp
3173  * namespace, but for existing callers that's not necessary because an empty
3174  * temp namespace wouldn't affect their results anyway.
3175  *
3176  * It's also worth noting that other schemas listed in newpath might not
3177  * exist anymore either.  We don't worry about this because OIDs that match
3178  * no existing namespace will simply not produce any hits during searches.
3179  */
3180 void
3181 PushOverrideSearchPath(OverrideSearchPath *newpath)
3182 {
3183         OverrideStackEntry *entry;
3184         List       *oidlist;
3185         Oid                     firstNS;
3186         MemoryContext oldcxt;
3187
3188         /*
3189          * Copy the list for safekeeping, and insert implicitly-searched
3190          * namespaces as needed.  This code should track recomputeNamespacePath.
3191          */
3192         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3193
3194         oidlist = list_copy(newpath->schemas);
3195
3196         /*
3197          * Remember the first member of the explicit list.
3198          */
3199         if (oidlist == NIL)
3200                 firstNS = InvalidOid;
3201         else
3202                 firstNS = linitial_oid(oidlist);
3203
3204         /*
3205          * Add any implicitly-searched namespaces to the list.  Note these go on
3206          * the front, not the back; also notice that we do not check USAGE
3207          * permissions for these.
3208          */
3209         if (newpath->addCatalog)
3210                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3211
3212         if (newpath->addTemp && OidIsValid(myTempNamespace))
3213                 oidlist = lcons_oid(myTempNamespace, oidlist);
3214
3215         /*
3216          * Build the new stack entry, then insert it at the head of the list.
3217          */
3218         entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3219         entry->searchPath = oidlist;
3220         entry->creationNamespace = firstNS;
3221         entry->nestLevel = GetCurrentTransactionNestLevel();
3222
3223         overrideStack = lcons(entry, overrideStack);
3224
3225         /* And make it active. */
3226         activeSearchPath = entry->searchPath;
3227         activeCreationNamespace = entry->creationNamespace;
3228         activeTempCreationPending = false;      /* XXX is this OK? */
3229
3230         MemoryContextSwitchTo(oldcxt);
3231 }
3232
3233 /*
3234  * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3235  *
3236  * Any push during a (sub)transaction will be popped automatically at abort.
3237  * But it's caller error if a push isn't popped in normal control flow.
3238  */
3239 void
3240 PopOverrideSearchPath(void)
3241 {
3242         OverrideStackEntry *entry;
3243
3244         /* Sanity checks. */
3245         if (overrideStack == NIL)
3246                 elog(ERROR, "bogus PopOverrideSearchPath call");
3247         entry = (OverrideStackEntry *) linitial(overrideStack);
3248         if (entry->nestLevel != GetCurrentTransactionNestLevel())
3249                 elog(ERROR, "bogus PopOverrideSearchPath call");
3250
3251         /* Pop the stack and free storage. */
3252         overrideStack = list_delete_first(overrideStack);
3253         list_free(entry->searchPath);
3254         pfree(entry);
3255
3256         /* Activate the next level down. */
3257         if (overrideStack)
3258         {
3259                 entry = (OverrideStackEntry *) linitial(overrideStack);
3260                 activeSearchPath = entry->searchPath;
3261                 activeCreationNamespace = entry->creationNamespace;
3262                 activeTempCreationPending = false;              /* XXX is this OK? */
3263         }
3264         else
3265         {
3266                 /* If not baseSearchPathValid, this is useless but harmless */
3267                 activeSearchPath = baseSearchPath;
3268                 activeCreationNamespace = baseCreationNamespace;
3269                 activeTempCreationPending = baseTempCreationPending;
3270         }
3271 }
3272
3273
3274 /*
3275  * get_collation_oid - find a collation by possibly qualified name
3276  */
3277 Oid
3278 get_collation_oid(List *name, bool missing_ok)
3279 {
3280         char       *schemaname;
3281         char       *collation_name;
3282         int32           dbencoding = GetDatabaseEncoding();
3283         Oid                     namespaceId;
3284         Oid                     colloid;
3285         ListCell   *l;
3286
3287         /* deconstruct the name list */
3288         DeconstructQualifiedName(name, &schemaname, &collation_name);
3289
3290         if (schemaname)
3291         {
3292                 /* use exact schema given */
3293                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3294                 if (missing_ok && !OidIsValid(namespaceId))
3295                         return InvalidOid;
3296
3297                 /* first try for encoding-specific entry, then any-encoding */
3298                 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3299                                                                   PointerGetDatum(collation_name),
3300                                                                   Int32GetDatum(dbencoding),
3301                                                                   ObjectIdGetDatum(namespaceId));
3302                 if (OidIsValid(colloid))
3303                         return colloid;
3304                 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3305                                                                   PointerGetDatum(collation_name),
3306                                                                   Int32GetDatum(-1),
3307                                                                   ObjectIdGetDatum(namespaceId));
3308                 if (OidIsValid(colloid))
3309                         return colloid;
3310         }
3311         else
3312         {
3313                 /* search for it in search path */
3314                 recomputeNamespacePath();
3315
3316                 foreach(l, activeSearchPath)
3317                 {
3318                         namespaceId = lfirst_oid(l);
3319
3320                         if (namespaceId == myTempNamespace)
3321                                 continue;               /* do not look in temp namespace */
3322
3323                         colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3324                                                                           PointerGetDatum(collation_name),
3325                                                                           Int32GetDatum(dbencoding),
3326                                                                           ObjectIdGetDatum(namespaceId));
3327                         if (OidIsValid(colloid))
3328                                 return colloid;
3329                         colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3330                                                                           PointerGetDatum(collation_name),
3331                                                                           Int32GetDatum(-1),
3332                                                                           ObjectIdGetDatum(namespaceId));
3333                         if (OidIsValid(colloid))
3334                                 return colloid;
3335                 }
3336         }
3337
3338         /* Not found in path */
3339         if (!missing_ok)
3340                 ereport(ERROR,
3341                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
3342                                  errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3343                                                 NameListToString(name), GetDatabaseEncodingName())));
3344         return InvalidOid;
3345 }
3346
3347 /*
3348  * get_conversion_oid - find a conversion by possibly qualified name
3349  */
3350 Oid
3351 get_conversion_oid(List *name, bool missing_ok)
3352 {
3353         char       *schemaname;
3354         char       *conversion_name;
3355         Oid                     namespaceId;
3356         Oid                     conoid = InvalidOid;
3357         ListCell   *l;
3358
3359         /* deconstruct the name list */
3360         DeconstructQualifiedName(name, &schemaname, &conversion_name);
3361
3362         if (schemaname)
3363         {
3364                 /* use exact schema given */
3365                 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3366                 if (missing_ok && !OidIsValid(namespaceId))
3367                         conoid = InvalidOid;
3368                 else
3369                         conoid = GetSysCacheOid2(CONNAMENSP,
3370                                                                          PointerGetDatum(conversion_name),
3371                                                                          ObjectIdGetDatum(namespaceId));
3372         }
3373         else
3374         {
3375                 /* search for it in search path */
3376                 recomputeNamespacePath();
3377
3378                 foreach(l, activeSearchPath)
3379                 {
3380                         namespaceId = lfirst_oid(l);
3381
3382                         if (namespaceId == myTempNamespace)
3383                                 continue;               /* do not look in temp namespace */
3384
3385                         conoid = GetSysCacheOid2(CONNAMENSP,
3386                                                                          PointerGetDatum(conversion_name),
3387                                                                          ObjectIdGetDatum(namespaceId));
3388                         if (OidIsValid(conoid))
3389                                 return conoid;
3390                 }
3391         }
3392
3393         /* Not found in path */
3394         if (!OidIsValid(conoid) && !missing_ok)
3395                 ereport(ERROR,
3396                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
3397                                  errmsg("conversion \"%s\" does not exist",
3398                                                 NameListToString(name))));
3399         return conoid;
3400 }
3401
3402 /*
3403  * FindDefaultConversionProc - find default encoding conversion proc
3404  */
3405 Oid
3406 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3407 {
3408         Oid                     proc;
3409         ListCell   *l;
3410
3411         recomputeNamespacePath();
3412
3413         foreach(l, activeSearchPath)
3414         {
3415                 Oid                     namespaceId = lfirst_oid(l);
3416
3417                 if (namespaceId == myTempNamespace)
3418                         continue;                       /* do not look in temp namespace */
3419
3420                 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3421                 if (OidIsValid(proc))
3422                         return proc;
3423         }
3424
3425         /* Not found in path */
3426         return InvalidOid;
3427 }
3428
3429 /*
3430  * recomputeNamespacePath - recompute path derived variables if needed.
3431  */
3432 static void
3433 recomputeNamespacePath(void)
3434 {
3435         Oid                     roleid = GetUserId();
3436         char       *rawname;
3437         List       *namelist;
3438         List       *oidlist;
3439         List       *newpath;
3440         ListCell   *l;
3441         bool            temp_missing;
3442         Oid                     firstNS;
3443         MemoryContext oldcxt;
3444
3445         /* Do nothing if an override search spec is active. */
3446         if (overrideStack)
3447                 return;
3448
3449         /* Do nothing if path is already valid. */
3450         if (baseSearchPathValid && namespaceUser == roleid)
3451                 return;
3452
3453         /* Need a modifiable copy of namespace_search_path string */
3454         rawname = pstrdup(namespace_search_path);
3455
3456         /* Parse string into list of identifiers */
3457         if (!SplitIdentifierString(rawname, ',', &namelist))
3458         {
3459                 /* syntax error in name list */
3460                 /* this should not happen if GUC checked check_search_path */
3461                 elog(ERROR, "invalid list syntax");
3462         }
3463
3464         /*
3465          * Convert the list of names to a list of OIDs.  If any names are not
3466          * recognizable or we don't have read access, just leave them out of the
3467          * list.  (We can't raise an error, since the search_path setting has
3468          * already been accepted.)      Don't make duplicate entries, either.
3469          */
3470         oidlist = NIL;
3471         temp_missing = false;
3472         foreach(l, namelist)
3473         {
3474                 char       *curname = (char *) lfirst(l);
3475                 Oid                     namespaceId;
3476
3477                 if (strcmp(curname, "$user") == 0)
3478                 {
3479                         /* $user --- substitute namespace matching user name, if any */
3480                         HeapTuple       tuple;
3481
3482                         tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3483                         if (HeapTupleIsValid(tuple))
3484                         {
3485                                 char       *rname;
3486
3487                                 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3488                                 namespaceId = get_namespace_oid(rname, true);
3489                                 ReleaseSysCache(tuple);
3490                                 if (OidIsValid(namespaceId) &&
3491                                         !list_member_oid(oidlist, namespaceId) &&
3492                                         pg_namespace_aclcheck(namespaceId, roleid,
3493                                                                                   ACL_USAGE) == ACLCHECK_OK &&
3494                                         InvokeNamespaceSearchHook(namespaceId, false))
3495                                         oidlist = lappend_oid(oidlist, namespaceId);
3496                         }
3497                 }
3498                 else if (strcmp(curname, "pg_temp") == 0)
3499                 {
3500                         /* pg_temp --- substitute temp namespace, if any */
3501                         if (OidIsValid(myTempNamespace))
3502                         {
3503                                 if (!list_member_oid(oidlist, myTempNamespace) &&
3504                                         InvokeNamespaceSearchHook(myTempNamespace, false))
3505                                         oidlist = lappend_oid(oidlist, myTempNamespace);
3506                         }
3507                         else
3508                         {
3509                                 /* If it ought to be the creation namespace, set flag */
3510                                 if (oidlist == NIL)
3511                                         temp_missing = true;
3512                         }
3513                 }
3514                 else
3515                 {
3516                         /* normal namespace reference */
3517                         namespaceId = get_namespace_oid(curname, true);
3518                         if (OidIsValid(namespaceId) &&
3519                                 !list_member_oid(oidlist, namespaceId) &&
3520                                 pg_namespace_aclcheck(namespaceId, roleid,
3521                                                                           ACL_USAGE) == ACLCHECK_OK &&
3522                                 InvokeNamespaceSearchHook(namespaceId, false))
3523                                 oidlist = lappend_oid(oidlist, namespaceId);
3524                 }
3525         }
3526
3527         /*
3528          * Remember the first member of the explicit list.  (Note: this is
3529          * nominally wrong if temp_missing, but we need it anyway to distinguish
3530          * explicit from implicit mention of pg_catalog.)
3531          */
3532         if (oidlist == NIL)
3533                 firstNS = InvalidOid;
3534         else
3535                 firstNS = linitial_oid(oidlist);
3536
3537         /*
3538          * Add any implicitly-searched namespaces to the list.  Note these go on
3539          * the front, not the back; also notice that we do not check USAGE
3540          * permissions for these.
3541          */
3542         if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3543                 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3544
3545         if (OidIsValid(myTempNamespace) &&
3546                 !list_member_oid(oidlist, myTempNamespace))
3547                 oidlist = lcons_oid(myTempNamespace, oidlist);
3548
3549         /*
3550          * Now that we've successfully built the new list of namespace OIDs, save
3551          * it in permanent storage.
3552          */
3553         oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3554         newpath = list_copy(oidlist);
3555         MemoryContextSwitchTo(oldcxt);
3556
3557         /* Now safe to assign to state variables. */
3558         list_free(baseSearchPath);
3559         baseSearchPath = newpath;
3560         baseCreationNamespace = firstNS;
3561         baseTempCreationPending = temp_missing;
3562
3563         /* Mark the path valid. */
3564         baseSearchPathValid = true;
3565         namespaceUser = roleid;
3566
3567         /* And make it active. */
3568         activeSearchPath = baseSearchPath;
3569         activeCreationNamespace = baseCreationNamespace;
3570         activeTempCreationPending = baseTempCreationPending;
3571
3572         /* Clean up. */
3573         pfree(rawname);
3574         list_free(namelist);
3575         list_free(oidlist);
3576 }
3577
3578 /*
3579  * InitTempTableNamespace
3580  *              Initialize temp table namespace on first use in a particular backend
3581  */
3582 static void
3583 InitTempTableNamespace(void)
3584 {
3585         char            namespaceName[NAMEDATALEN];
3586         Oid                     namespaceId;
3587         Oid                     toastspaceId;
3588
3589         Assert(!OidIsValid(myTempNamespace));
3590
3591         /*
3592          * First, do permission check to see if we are authorized to make temp
3593          * tables.  We use a nonstandard error message here since "databasename:
3594          * permission denied" might be a tad cryptic.
3595          *
3596          * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3597          * that's necessary since current user ID could change during the session.
3598          * But there's no need to make the namespace in the first place until a
3599          * temp table creation request is made by someone with appropriate rights.
3600          */
3601         if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3602                                                          ACL_CREATE_TEMP) != ACLCHECK_OK)
3603                 ereport(ERROR,
3604                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3605                                  errmsg("permission denied to create temporary tables in database \"%s\"",
3606                                                 get_database_name(MyDatabaseId))));
3607
3608         /*
3609          * Do not allow a Hot Standby slave session to make temp tables.  Aside
3610          * from problems with modifying the system catalogs, there is a naming
3611          * conflict: pg_temp_N belongs to the session with BackendId N on the
3612          * master, not to a slave session with the same BackendId.  We should not
3613          * be able to get here anyway due to XactReadOnly checks, but let's just
3614          * make real sure.  Note that this also backstops various operations that
3615          * allow XactReadOnly transactions to modify temp tables; they'd need
3616          * RecoveryInProgress checks if not for this.
3617          */
3618         if (RecoveryInProgress())
3619                 ereport(ERROR,
3620                                 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3621                                  errmsg("cannot create temporary tables during recovery")));
3622
3623         snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3624
3625         namespaceId = get_namespace_oid(namespaceName, true);
3626         if (!OidIsValid(namespaceId))
3627         {
3628                 /*
3629                  * First use of this temp namespace in this database; create it. The
3630                  * temp namespaces are always owned by the superuser.  We leave their
3631                  * permissions at default --- i.e., no access except to superuser ---
3632                  * to ensure that unprivileged users can't peek at other backends'
3633                  * temp tables.  This works because the places that access the temp
3634                  * namespace for my own backend skip permissions checks on it.
3635                  */
3636                 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3637                                                                           true);
3638                 /* Advance command counter to make namespace visible */
3639                 CommandCounterIncrement();
3640         }
3641         else
3642         {
3643                 /*
3644                  * If the namespace already exists, clean it out (in case the former
3645                  * owner crashed without doing so).
3646                  */
3647                 RemoveTempRelations(namespaceId);
3648         }
3649
3650         /*
3651          * If the corresponding toast-table namespace doesn't exist yet, create
3652          * it. (We assume there is no need to clean it out if it does exist, since
3653          * dropping a parent table should make its toast table go away.)
3654          */
3655         snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3656                          MyBackendId);
3657
3658         toastspaceId = get_namespace_oid(namespaceName, true);
3659         if (!OidIsValid(toastspaceId))
3660         {
3661                 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3662                                                                            true);
3663                 /* Advance command counter to make namespace visible */
3664                 CommandCounterIncrement();
3665         }
3666
3667         /*
3668          * Okay, we've prepared the temp namespace ... but it's not committed yet,
3669          * so all our work could be undone by transaction rollback.  Set flag for
3670          * AtEOXact_Namespace to know what to do.
3671          */
3672         myTempNamespace = namespaceId;
3673         myTempToastNamespace = toastspaceId;
3674
3675         /* It should not be done already. */
3676         AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3677         myTempNamespaceSubID = GetCurrentSubTransactionId();
3678
3679         baseSearchPathValid = false;    /* need to rebuild list */
3680 }
3681
3682 /*
3683  * End-of-transaction cleanup for namespaces.
3684  */
3685 void
3686 AtEOXact_Namespace(bool isCommit)
3687 {
3688         /*
3689          * If we abort the transaction in which a temp namespace was selected,
3690          * we'll have to do any creation or cleanout work over again.  So, just
3691          * forget the namespace entirely until next time.  On the other hand, if
3692          * we commit then register an exit callback to clean out the temp tables
3693          * at backend shutdown.  (We only want to register the callback once per
3694          * session, so this is a good place to do it.)
3695          */
3696         if (myTempNamespaceSubID != InvalidSubTransactionId)
3697         {
3698                 if (isCommit)
3699                         before_shmem_exit(RemoveTempRelationsCallback, 0);
3700                 else
3701                 {
3702                         myTempNamespace = InvalidOid;
3703                         myTempToastNamespace = InvalidOid;
3704                         baseSearchPathValid = false;            /* need to rebuild list */
3705                 }
3706                 myTempNamespaceSubID = InvalidSubTransactionId;
3707         }
3708
3709         /*
3710          * Clean up if someone failed to do PopOverrideSearchPath
3711          */
3712         if (overrideStack)
3713         {
3714                 if (isCommit)
3715                         elog(WARNING, "leaked override search path");
3716                 while (overrideStack)
3717                 {
3718                         OverrideStackEntry *entry;
3719
3720                         entry = (OverrideStackEntry *) linitial(overrideStack);
3721                         overrideStack = list_delete_first(overrideStack);
3722                         list_free(entry->searchPath);
3723                         pfree(entry);
3724                 }
3725                 /* If not baseSearchPathValid, this is useless but harmless */
3726                 activeSearchPath = baseSearchPath;
3727                 activeCreationNamespace = baseCreationNamespace;
3728                 activeTempCreationPending = baseTempCreationPending;
3729         }
3730 }
3731
3732 /*
3733  * AtEOSubXact_Namespace
3734  *
3735  * At subtransaction commit, propagate the temp-namespace-creation
3736  * flag to the parent subtransaction.
3737  *
3738  * At subtransaction abort, forget the flag if we set it up.
3739  */
3740 void
3741 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3742                                           SubTransactionId parentSubid)
3743 {
3744         OverrideStackEntry *entry;
3745
3746         if (myTempNamespaceSubID == mySubid)
3747         {
3748                 if (isCommit)
3749                         myTempNamespaceSubID = parentSubid;
3750                 else
3751                 {
3752                         myTempNamespaceSubID = InvalidSubTransactionId;
3753                         /* TEMP namespace creation failed, so reset state */
3754                         myTempNamespace = InvalidOid;
3755                         myTempToastNamespace = InvalidOid;
3756                         baseSearchPathValid = false;            /* need to rebuild list */
3757                 }
3758         }
3759
3760         /*
3761          * Clean up if someone failed to do PopOverrideSearchPath
3762          */
3763         while (overrideStack)
3764         {
3765                 entry = (OverrideStackEntry *) linitial(overrideStack);
3766                 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3767                         break;
3768                 if (isCommit)
3769                         elog(WARNING, "leaked override search path");
3770                 overrideStack = list_delete_first(overrideStack);
3771                 list_free(entry->searchPath);
3772                 pfree(entry);
3773         }
3774
3775         /* Activate the next level down. */
3776         if (overrideStack)
3777         {
3778                 entry = (OverrideStackEntry *) linitial(overrideStack);
3779                 activeSearchPath = entry->searchPath;
3780                 activeCreationNamespace = entry->creationNamespace;
3781                 activeTempCreationPending = false;              /* XXX is this OK? */
3782         }
3783         else
3784         {
3785                 /* If not baseSearchPathValid, this is useless but harmless */
3786                 activeSearchPath = baseSearchPath;
3787                 activeCreationNamespace = baseCreationNamespace;
3788                 activeTempCreationPending = baseTempCreationPending;
3789         }
3790 }
3791
3792 /*
3793  * Remove all relations in the specified temp namespace.
3794  *
3795  * This is called at backend shutdown (if we made any temp relations).
3796  * It is also called when we begin using a pre-existing temp namespace,
3797  * in order to clean out any relations that might have been created by
3798  * a crashed backend.
3799  */
3800 static void
3801 RemoveTempRelations(Oid tempNamespaceId)
3802 {
3803         ObjectAddress object;
3804
3805         /*
3806          * We want to get rid of everything in the target namespace, but not the
3807          * namespace itself (deleting it only to recreate it later would be a
3808          * waste of cycles).  We do this by finding everything that has a
3809          * dependency on the namespace.
3810          */
3811         object.classId = NamespaceRelationId;
3812         object.objectId = tempNamespaceId;
3813         object.objectSubId = 0;
3814
3815         deleteWhatDependsOn(&object, false);
3816 }
3817
3818 /*
3819  * Callback to remove temp relations at backend exit.
3820  */
3821 static void
3822 RemoveTempRelationsCallback(int code, Datum arg)
3823 {
3824         if (OidIsValid(myTempNamespace))        /* should always be true */
3825         {
3826                 /* Need to ensure we have a usable transaction. */
3827                 AbortOutOfAnyTransaction();
3828                 StartTransactionCommand();
3829
3830                 RemoveTempRelations(myTempNamespace);
3831
3832                 CommitTransactionCommand();
3833         }
3834 }
3835
3836 /*
3837  * Remove all temp tables from the temporary namespace.
3838  */
3839 void
3840 ResetTempTableNamespace(void)
3841 {
3842         if (OidIsValid(myTempNamespace))
3843                 RemoveTempRelations(myTempNamespace);
3844 }
3845
3846
3847 /*
3848  * Routines for handling the GUC variable 'search_path'.
3849  */
3850
3851 /* check_hook: validate new search_path value */
3852 bool
3853 check_search_path(char **newval, void **extra, GucSource source)
3854 {
3855         char       *rawname;
3856         List       *namelist;
3857
3858         /* Need a modifiable copy of string */
3859         rawname = pstrdup(*newval);
3860
3861         /* Parse string into list of identifiers */
3862         if (!SplitIdentifierString(rawname, ',', &namelist))
3863         {
3864                 /* syntax error in name list */
3865                 GUC_check_errdetail("List syntax is invalid.");
3866                 pfree(rawname);
3867                 list_free(namelist);
3868                 return false;
3869         }
3870
3871         /*
3872          * We used to try to check that the named schemas exist, but there are
3873          * many valid use-cases for having search_path settings that include
3874          * schemas that don't exist; and often, we are not inside a transaction
3875          * here and so can't consult the system catalogs anyway.  So now, the only
3876          * requirement is syntactic validity of the identifier list.
3877          */
3878
3879         pfree(rawname);
3880         list_free(namelist);
3881
3882         return true;
3883 }
3884
3885 /* assign_hook: do extra actions as needed */
3886 void
3887 assign_search_path(const char *newval, void *extra)
3888 {
3889         /*
3890          * We mark the path as needing recomputation, but don't do anything until
3891          * it's needed.  This avoids trying to do database access during GUC
3892          * initialization, or outside a transaction.
3893          */
3894         baseSearchPathValid = false;
3895 }
3896
3897 /*
3898  * InitializeSearchPath: initialize module during InitPostgres.
3899  *
3900  * This is called after we are up enough to be able to do catalog lookups.
3901  */
3902 void
3903 InitializeSearchPath(void)
3904 {
3905         if (IsBootstrapProcessingMode())
3906         {
3907                 /*
3908                  * In bootstrap mode, the search path must be 'pg_catalog' so that
3909                  * tables are created in the proper namespace; ignore the GUC setting.
3910                  */
3911                 MemoryContext oldcxt;
3912
3913                 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3914                 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3915                 MemoryContextSwitchTo(oldcxt);
3916                 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3917                 baseTempCreationPending = false;
3918                 baseSearchPathValid = true;
3919                 namespaceUser = GetUserId();
3920                 activeSearchPath = baseSearchPath;
3921                 activeCreationNamespace = baseCreationNamespace;
3922                 activeTempCreationPending = baseTempCreationPending;
3923         }
3924         else
3925         {
3926                 /*
3927                  * In normal mode, arrange for a callback on any syscache invalidation
3928                  * of pg_namespace rows.
3929                  */
3930                 CacheRegisterSyscacheCallback(NAMESPACEOID,
3931                                                                           NamespaceCallback,
3932                                                                           (Datum) 0);
3933                 /* Force search path to be recomputed on next use */
3934                 baseSearchPathValid = false;
3935         }
3936 }
3937
3938 /*
3939  * NamespaceCallback
3940  *              Syscache inval callback function
3941  */
3942 static void
3943 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3944 {
3945         /* Force search path to be recomputed on next use */
3946         baseSearchPathValid = false;
3947 }
3948
3949 /*
3950  * Fetch the active search path. The return value is a palloc'ed list
3951  * of OIDs; the caller is responsible for freeing this storage as
3952  * appropriate.
3953  *
3954  * The returned list includes the implicitly-prepended namespaces only if
3955  * includeImplicit is true.
3956  *
3957  * Note: calling this may result in a CommandCounterIncrement operation,
3958  * if we have to create or clean out the temp namespace.
3959  */
3960 List *
3961 fetch_search_path(bool includeImplicit)
3962 {
3963         List       *result;
3964
3965         recomputeNamespacePath();
3966
3967         /*
3968          * If the temp namespace should be first, force it to exist.  This is so
3969          * that callers can trust the result to reflect the actual default
3970          * creation namespace.  It's a bit bogus to do this here, since
3971          * current_schema() is supposedly a stable function without side-effects,
3972          * but the alternatives seem worse.
3973          */
3974         if (activeTempCreationPending)
3975         {
3976                 InitTempTableNamespace();
3977                 recomputeNamespacePath();
3978         }
3979
3980         result = list_copy(activeSearchPath);
3981         if (!includeImplicit)
3982         {
3983                 while (result && linitial_oid(result) != activeCreationNamespace)
3984                         result = list_delete_first(result);
3985         }
3986
3987         return result;
3988 }
3989
3990 /*
3991  * Fetch the active search path into a caller-allocated array of OIDs.
3992  * Returns the number of path entries.  (If this is more than sarray_len,
3993  * then the data didn't fit and is not all stored.)
3994  *
3995  * The returned list always includes the implicitly-prepended namespaces,
3996  * but never includes the temp namespace.  (This is suitable for existing
3997  * users, which would want to ignore the temp namespace anyway.)  This
3998  * definition allows us to not worry about initializing the temp namespace.
3999  */
4000 int
4001 fetch_search_path_array(Oid *sarray, int sarray_len)
4002 {
4003         int                     count = 0;
4004         ListCell   *l;
4005
4006         recomputeNamespacePath();
4007
4008         foreach(l, activeSearchPath)
4009         {
4010                 Oid                     namespaceId = lfirst_oid(l);
4011
4012                 if (namespaceId == myTempNamespace)
4013                         continue;                       /* do not include temp namespace */
4014
4015                 if (count < sarray_len)
4016                         sarray[count] = namespaceId;
4017                 count++;
4018         }
4019
4020         return count;
4021 }
4022
4023
4024 /*
4025  * Export the FooIsVisible functions as SQL-callable functions.
4026  *
4027  * Note: as of Postgres 8.4, these will silently return NULL if called on
4028  * a nonexistent object OID, rather than failing.  This is to avoid race
4029  * condition errors when a query that's scanning a catalog using an MVCC
4030  * snapshot uses one of these functions.  The underlying IsVisible functions
4031  * always use an up-to-date snapshot and so might see the object as already
4032  * gone when it's still visible to the transaction snapshot.  (There is no race
4033  * condition in the current coding because we don't accept sinval messages
4034  * between the SearchSysCacheExists test and the subsequent lookup.)
4035  */
4036
4037 Datum
4038 pg_table_is_visible(PG_FUNCTION_ARGS)
4039 {
4040         Oid                     oid = PG_GETARG_OID(0);
4041
4042         if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
4043                 PG_RETURN_NULL();
4044
4045         PG_RETURN_BOOL(RelationIsVisible(oid));
4046 }
4047
4048 Datum
4049 pg_type_is_visible(PG_FUNCTION_ARGS)
4050 {
4051         Oid                     oid = PG_GETARG_OID(0);
4052
4053         if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
4054                 PG_RETURN_NULL();
4055
4056         PG_RETURN_BOOL(TypeIsVisible(oid));
4057 }
4058
4059 Datum
4060 pg_function_is_visible(PG_FUNCTION_ARGS)
4061 {
4062         Oid                     oid = PG_GETARG_OID(0);
4063
4064         if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
4065                 PG_RETURN_NULL();
4066
4067         PG_RETURN_BOOL(FunctionIsVisible(oid));
4068 }
4069
4070 Datum
4071 pg_operator_is_visible(PG_FUNCTION_ARGS)
4072 {
4073         Oid                     oid = PG_GETARG_OID(0);
4074
4075         if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4076                 PG_RETURN_NULL();
4077
4078         PG_RETURN_BOOL(OperatorIsVisible(oid));
4079 }
4080
4081 Datum
4082 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4083 {
4084         Oid                     oid = PG_GETARG_OID(0);
4085
4086         if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4087                 PG_RETURN_NULL();
4088
4089         PG_RETURN_BOOL(OpclassIsVisible(oid));
4090 }
4091
4092 Datum
4093 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4094 {
4095         Oid                     oid = PG_GETARG_OID(0);
4096
4097         if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4098                 PG_RETURN_NULL();
4099
4100         PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4101 }
4102
4103 Datum
4104 pg_collation_is_visible(PG_FUNCTION_ARGS)
4105 {
4106         Oid                     oid = PG_GETARG_OID(0);
4107
4108         if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4109                 PG_RETURN_NULL();
4110
4111         PG_RETURN_BOOL(CollationIsVisible(oid));
4112 }
4113
4114 Datum
4115 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4116 {
4117         Oid                     oid = PG_GETARG_OID(0);
4118
4119         if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4120                 PG_RETURN_NULL();
4121
4122         PG_RETURN_BOOL(ConversionIsVisible(oid));
4123 }
4124
4125 Datum
4126 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4127 {
4128         Oid                     oid = PG_GETARG_OID(0);
4129
4130         if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4131                 PG_RETURN_NULL();
4132
4133         PG_RETURN_BOOL(TSParserIsVisible(oid));
4134 }
4135
4136 Datum
4137 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4138 {
4139         Oid                     oid = PG_GETARG_OID(0);
4140
4141         if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4142                 PG_RETURN_NULL();
4143
4144         PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4145 }
4146
4147 Datum
4148 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4149 {
4150         Oid                     oid = PG_GETARG_OID(0);
4151
4152         if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4153                 PG_RETURN_NULL();
4154
4155         PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4156 }
4157
4158 Datum
4159 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4160 {
4161         Oid                     oid = PG_GETARG_OID(0);
4162
4163         if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4164                 PG_RETURN_NULL();
4165
4166         PG_RETURN_BOOL(TSConfigIsVisible(oid));
4167 }
4168
4169 Datum
4170 pg_my_temp_schema(PG_FUNCTION_ARGS)
4171 {
4172         PG_RETURN_OID(myTempNamespace);
4173 }
4174
4175 Datum
4176 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4177 {
4178         Oid                     oid = PG_GETARG_OID(0);
4179
4180         PG_RETURN_BOOL(isOtherTempNamespace(oid));
4181 }