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