1 /*-------------------------------------------------------------------------
4 * code to support accessing and searching namespaces
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.
12 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
16 * src/backend/catalog/namespace.c
18 *-------------------------------------------------------------------------
22 #include "access/htup_details.h"
23 #include "access/parallel.h"
24 #include "access/xact.h"
25 #include "access/xlog.h"
26 #include "catalog/dependency.h"
27 #include "catalog/objectaccess.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_collation.h"
30 #include "catalog/pg_conversion.h"
31 #include "catalog/pg_conversion_fn.h"
32 #include "catalog/pg_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_operator.h"
35 #include "catalog/pg_opfamily.h"
36 #include "catalog/pg_proc.h"
37 #include "catalog/pg_ts_config.h"
38 #include "catalog/pg_ts_dict.h"
39 #include "catalog/pg_ts_parser.h"
40 #include "catalog/pg_ts_template.h"
41 #include "catalog/pg_type.h"
42 #include "commands/dbcommands.h"
44 #include "mb/pg_wchar.h"
45 #include "miscadmin.h"
46 #include "nodes/makefuncs.h"
47 #include "parser/parse_func.h"
48 #include "storage/ipc.h"
49 #include "storage/lmgr.h"
50 #include "storage/sinval.h"
51 #include "utils/acl.h"
52 #include "utils/builtins.h"
53 #include "utils/catcache.h"
54 #include "utils/guc.h"
55 #include "utils/inval.h"
56 #include "utils/lsyscache.h"
57 #include "utils/memutils.h"
58 #include "utils/syscache.h"
62 * The namespace search path is a possibly-empty list of namespace OIDs.
63 * In addition to the explicit list, implicitly-searched namespaces
66 * 1. If a TEMP table namespace has been initialized in this session, it
67 * is implicitly searched first. (The only time this doesn't happen is
68 * when we are obeying an override search path spec that says not to use the
69 * temp namespace, or the temp namespace is included in the explicit list.)
71 * 2. The system catalog namespace is always searched. If the system
72 * namespace is present in the explicit path then it will be searched in
73 * the specified order; otherwise it will be searched after TEMP tables and
74 * *before* the explicit list. (It might seem that the system namespace
75 * should be implicitly last, but this behavior appears to be required by
76 * SQL99. Also, this provides a way to search the system namespace first
77 * without thereby making it the default creation target namespace.)
79 * For security reasons, searches using the search path will ignore the temp
80 * namespace when searching for any object type other than relations and
81 * types. (We must allow types since temp tables have rowtypes.)
83 * The default creation target namespace is always the first element of the
84 * explicit list. If the explicit list is empty, there is no default target.
86 * The textual specification of search_path can include "$user" to refer to
87 * the namespace named the same as the current user, if any. (This is just
88 * ignored if there is no such namespace.) Also, it can include "pg_temp"
89 * to refer to the current backend's temp namespace. This is usually also
90 * ignorable if the temp namespace hasn't been set up, but there's a special
91 * case: if "pg_temp" appears first then it should be the default creation
92 * target. We kluge this case a little bit so that the temp namespace isn't
93 * set up until the first attempt to create something in it. (The reason for
94 * klugery is that we can't create the temp namespace outside a transaction,
95 * but initial GUC processing of search_path happens outside a transaction.)
96 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
97 * but is not reflected in activeCreationNamespace because the namespace isn't
100 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
101 * the system namespace is the only one searched or inserted into.
102 * initdb is also careful to set search_path to "pg_catalog" for its
103 * post-bootstrap standalone backend runs. Otherwise the default search
104 * path is determined by GUC. The factory default path contains the PUBLIC
105 * namespace (if it exists), preceded by the user's personal namespace
108 * We support a stack of "override" search path settings for use within
109 * specific sections of backend code. namespace_search_path is ignored
110 * whenever the override stack is nonempty. activeSearchPath is always
111 * the actually active path; it points either to the search list of the
112 * topmost stack entry, or to baseSearchPath which is the list derived
113 * from namespace_search_path.
115 * If baseSearchPathValid is false, then baseSearchPath (and other
116 * derived variables) need to be recomputed from namespace_search_path.
117 * We mark it invalid upon an assignment to namespace_search_path or receipt
118 * of a syscache invalidation event for pg_namespace. The recomputation
119 * is done during the next non-overridden lookup attempt. Note that an
120 * override spec is never subject to recomputation.
122 * Any namespaces mentioned in namespace_search_path that are not readable
123 * by the current user ID are simply left out of baseSearchPath; so
124 * we have to be willing to recompute the path when current userid changes.
125 * namespaceUser is the userid the path has been computed for.
127 * Note: all data pointed to by these List variables is in TopMemoryContext.
130 /* These variables define the actually active state: */
132 static List *activeSearchPath = NIL;
134 /* default place to create stuff; if InvalidOid, no default */
135 static Oid activeCreationNamespace = InvalidOid;
137 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
138 static bool activeTempCreationPending = false;
140 /* These variables are the values last derived from namespace_search_path: */
142 static List *baseSearchPath = NIL;
144 static Oid baseCreationNamespace = InvalidOid;
146 static bool baseTempCreationPending = false;
148 static Oid namespaceUser = InvalidOid;
150 /* The above four values are valid only if baseSearchPathValid */
151 static bool baseSearchPathValid = true;
153 /* Override requests are remembered in a stack of OverrideStackEntry structs */
157 List *searchPath; /* the desired search path */
158 Oid creationNamespace; /* the desired creation namespace */
159 int nestLevel; /* subtransaction nesting level */
160 } OverrideStackEntry;
162 static List *overrideStack = NIL;
165 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
166 * in a particular backend session (this happens when a CREATE TEMP TABLE
167 * command is first executed). Thereafter it's the OID of the temp namespace.
169 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
170 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
172 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
173 * current subtransaction. The flag propagates up the subtransaction tree,
174 * so the main transaction will correctly recognize the flag if all
175 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
176 * we either haven't made the TEMP namespace yet, or have successfully
177 * committed its creation, depending on whether myTempNamespace is valid.
179 static Oid myTempNamespace = InvalidOid;
181 static Oid myTempToastNamespace = InvalidOid;
183 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
186 * This is the user's textual search path specification --- it's the value
187 * of the GUC variable 'search_path'.
189 char *namespace_search_path = NULL;
192 /* Local functions */
193 static void recomputeNamespacePath(void);
194 static void InitTempTableNamespace(void);
195 static void RemoveTempRelations(Oid tempNamespaceId);
196 static void RemoveTempRelationsCallback(int code, Datum arg);
197 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
198 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
201 /* These don't really need to appear in any header file */
202 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
210 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
211 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
212 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
213 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
214 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
215 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
220 * Given a RangeVar describing an existing relation,
221 * select the proper namespace and look up the relation OID.
223 * If the schema or relation is not found, return InvalidOid if missing_ok
224 * = true, otherwise raise an error.
226 * If nowait = true, throw an error if we'd have to wait for a lock.
228 * Callback allows caller to check permissions or acquire additional locks
229 * prior to grabbing the relation lock.
232 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
233 bool missing_ok, bool nowait,
234 RangeVarGetRelidCallback callback, void *callback_arg)
238 Oid oldRelId = InvalidOid;
242 * We check the catalog name and then ignore it.
244 if (relation->catalogname)
246 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
248 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
249 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
250 relation->catalogname, relation->schemaname,
251 relation->relname)));
255 * DDL operations can change the results of a name lookup. Since all such
256 * operations will generate invalidation messages, we keep track of
257 * whether any such messages show up while we're performing the operation,
258 * and retry until either (1) no more invalidation messages show up or (2)
259 * the answer doesn't change.
261 * But if lockmode = NoLock, then we assume that either the caller is OK
262 * with the answer changing under them, or that they already hold some
263 * appropriate lock, and therefore return the first answer we get without
264 * checking for invalidation messages. Also, if the requested lock is
265 * already held, LockRelationOid will not AcceptInvalidationMessages, so
266 * we may fail to notice a change. We could protect against that case by
267 * calling AcceptInvalidationMessages() before beginning this loop, but
268 * that would add a significant amount overhead, so for now we don't.
273 * Remember this value, so that, after looking up the relation name
274 * and locking its OID, we can check whether any invalidation messages
275 * have been processed that might require a do-over.
277 inval_count = SharedInvalidMessageCounter;
280 * Some non-default relpersistence value may have been specified. The
281 * parser never generates such a RangeVar in simple DML, but it can
282 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
283 * KEY)". Such a command will generate an added CREATE INDEX
284 * operation, which must be careful to find the temp table, even when
285 * pg_temp is not first in the search path.
287 if (relation->relpersistence == RELPERSISTENCE_TEMP)
289 if (!OidIsValid(myTempNamespace))
290 relId = InvalidOid; /* this probably can't happen? */
293 if (relation->schemaname)
297 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
300 * For missing_ok, allow a non-existant schema name to
303 if (namespaceId != myTempNamespace)
305 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
306 errmsg("temporary tables cannot specify a schema name")));
309 relId = get_relname_relid(relation->relname, myTempNamespace);
312 else if (relation->schemaname)
316 /* use exact schema given */
317 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
318 if (missing_ok && !OidIsValid(namespaceId))
321 relId = get_relname_relid(relation->relname, namespaceId);
325 /* search the namespace path */
326 relId = RelnameGetRelid(relation->relname);
330 * Invoke caller-supplied callback, if any.
332 * This callback is a good place to check permissions: we haven't
333 * taken the table lock yet (and it's really best to check permissions
334 * before locking anything!), but we've gotten far enough to know what
335 * OID we think we should lock. Of course, concurrent DDL might
336 * change things while we're waiting for the lock, but in that case
337 * the callback will be invoked again for the new OID.
340 callback(relation, relId, oldRelId, callback_arg);
343 * If no lock requested, we assume the caller knows what they're
344 * doing. They should have already acquired a heavyweight lock on
345 * this relation earlier in the processing of this same statement, so
346 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
347 * that might pull the rug out from under them.
349 if (lockmode == NoLock)
353 * If, upon retry, we get back the same OID we did last time, then the
354 * invalidation messages we processed did not change the final answer.
357 * If we got a different OID, we've locked the relation that used to
358 * have this name rather than the one that does now. So release the
363 if (relId == oldRelId)
365 if (OidIsValid(oldRelId))
366 UnlockRelationOid(oldRelId, lockmode);
370 * Lock relation. This will also accept any pending invalidation
371 * messages. If we got back InvalidOid, indicating not found, then
372 * there's nothing to lock, but we accept invalidation messages
373 * anyway, to flush any negative catcache entries that may be
376 if (!OidIsValid(relId))
377 AcceptInvalidationMessages();
379 LockRelationOid(relId, lockmode);
380 else if (!ConditionalLockRelationOid(relId, lockmode))
382 if (relation->schemaname)
384 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
385 errmsg("could not obtain lock on relation \"%s.%s\"",
386 relation->schemaname, relation->relname)));
389 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
390 errmsg("could not obtain lock on relation \"%s\"",
391 relation->relname)));
395 * If no invalidation message were processed, we're done!
397 if (inval_count == SharedInvalidMessageCounter)
401 * Something may have changed. Let's repeat the name lookup, to make
402 * sure this name still references the same relation it did
409 if (!OidIsValid(relId) && !missing_ok)
411 if (relation->schemaname)
413 (errcode(ERRCODE_UNDEFINED_TABLE),
414 errmsg("relation \"%s.%s\" does not exist",
415 relation->schemaname, relation->relname)));
418 (errcode(ERRCODE_UNDEFINED_TABLE),
419 errmsg("relation \"%s\" does not exist",
420 relation->relname)));
426 * RangeVarGetCreationNamespace
427 * Given a RangeVar describing a to-be-created relation,
428 * choose which namespace to create it in.
430 * Note: calling this may result in a CommandCounterIncrement operation.
431 * That will happen on the first request for a temp table in any particular
432 * backend run; we will need to either create or clean out the temp schema.
435 RangeVarGetCreationNamespace(const RangeVar *newRelation)
440 * We check the catalog name and then ignore it.
442 if (newRelation->catalogname)
444 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
446 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
447 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
448 newRelation->catalogname, newRelation->schemaname,
449 newRelation->relname)));
452 if (newRelation->schemaname)
454 /* check for pg_temp alias */
455 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
457 /* Initialize temp namespace if first time through */
458 if (!OidIsValid(myTempNamespace))
459 InitTempTableNamespace();
460 return myTempNamespace;
462 /* use exact schema given */
463 namespaceId = get_namespace_oid(newRelation->schemaname, false);
464 /* we do not check for USAGE rights here! */
466 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
468 /* Initialize temp namespace if first time through */
469 if (!OidIsValid(myTempNamespace))
470 InitTempTableNamespace();
471 return myTempNamespace;
475 /* use the default creation namespace */
476 recomputeNamespacePath();
477 if (activeTempCreationPending)
479 /* Need to initialize temp namespace */
480 InitTempTableNamespace();
481 return myTempNamespace;
483 namespaceId = activeCreationNamespace;
484 if (!OidIsValid(namespaceId))
486 (errcode(ERRCODE_UNDEFINED_SCHEMA),
487 errmsg("no schema has been selected to create in")));
490 /* Note: callers will check for CREATE rights when appropriate */
496 * RangeVarGetAndCheckCreationNamespace
498 * This function returns the OID of the namespace in which a new relation
499 * with a given name should be created. If the user does not have CREATE
500 * permission on the target namespace, this function will instead signal
503 * If non-NULL, *existing_oid is set to the OID of any existing relation with
504 * the same name which already exists in that namespace, or to InvalidOid if
505 * no such relation exists.
507 * If lockmode != NoLock, the specified lock mode is acquired on the existing
508 * relation, if any, provided that the current user owns the target relation.
509 * However, if lockmode != NoLock and the user does not own the target
510 * relation, we throw an ERROR, as we must not try to lock relations the
511 * user does not have permissions on.
513 * As a side effect, this function acquires AccessShareLock on the target
514 * namespace. Without this, the namespace could be dropped before our
515 * transaction commits, leaving behind relations with relnamespace pointing
516 * to a no-longer-exstant namespace.
518 * As a further side-effect, if the select namespace is a temporary namespace,
519 * we mark the RangeVar as RELPERSISTENCE_TEMP.
522 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
524 Oid *existing_relation_id)
528 Oid oldrelid = InvalidOid;
530 Oid oldnspid = InvalidOid;
534 * We check the catalog name and then ignore it.
536 if (relation->catalogname)
538 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
540 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
541 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
542 relation->catalogname, relation->schemaname,
543 relation->relname)));
547 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
548 * operations by tracking whether any invalidation messages are processed
549 * while we're doing the name lookups and acquiring locks. See comments
550 * in that function for a more detailed explanation of this logic.
556 inval_count = SharedInvalidMessageCounter;
558 /* Look up creation namespace and check for existing relation. */
559 nspid = RangeVarGetCreationNamespace(relation);
560 Assert(OidIsValid(nspid));
561 if (existing_relation_id != NULL)
562 relid = get_relname_relid(relation->relname, nspid);
567 * In bootstrap processing mode, we don't bother with permissions or
568 * locking. Permissions might not be working yet, and locking is
571 if (IsBootstrapProcessingMode())
574 /* Check namespace permissions. */
575 aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
576 if (aclresult != ACLCHECK_OK)
577 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
578 get_namespace_name(nspid));
582 /* If nothing changed, we're done. */
583 if (relid == oldrelid && nspid == oldnspid)
585 /* If creation namespace has changed, give up old lock. */
586 if (nspid != oldnspid)
587 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
589 /* If name points to something different, give up old lock. */
590 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
591 UnlockRelationOid(oldrelid, lockmode);
594 /* Lock namespace. */
595 if (nspid != oldnspid)
596 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
598 /* Lock relation, if required if and we have permission. */
599 if (lockmode != NoLock && OidIsValid(relid))
601 if (!pg_class_ownercheck(relid, GetUserId()))
602 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
604 if (relid != oldrelid)
605 LockRelationOid(relid, lockmode);
608 /* If no invalidation message were processed, we're done! */
609 if (inval_count == SharedInvalidMessageCounter)
612 /* Something may have changed, so recheck our work. */
618 RangeVarAdjustRelationPersistence(relation, nspid);
619 if (existing_relation_id != NULL)
620 *existing_relation_id = relid;
625 * Adjust the relpersistence for an about-to-be-created relation based on the
626 * creation namespace, and throw an error for invalid combinations.
629 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
631 switch (newRelation->relpersistence)
633 case RELPERSISTENCE_TEMP:
634 if (!isTempOrTempToastNamespace(nspid))
636 if (isAnyTempNamespace(nspid))
638 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
639 errmsg("cannot create relations in temporary schemas of other sessions")));
642 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
643 errmsg("cannot create temporary relation in non-temporary schema")));
646 case RELPERSISTENCE_PERMANENT:
647 if (isTempOrTempToastNamespace(nspid))
648 newRelation->relpersistence = RELPERSISTENCE_TEMP;
649 else if (isAnyTempNamespace(nspid))
651 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
652 errmsg("cannot create relations in temporary schemas of other sessions")));
655 if (isAnyTempNamespace(nspid))
657 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
658 errmsg("only temporary relations may be created in temporary schemas")));
664 * Try to resolve an unqualified relation name.
665 * Returns OID if relation found in search path, else InvalidOid.
668 RelnameGetRelid(const char *relname)
673 recomputeNamespacePath();
675 foreach(l, activeSearchPath)
677 Oid namespaceId = lfirst_oid(l);
679 relid = get_relname_relid(relname, namespaceId);
680 if (OidIsValid(relid))
684 /* Not found in path */
691 * Determine whether a relation (identified by OID) is visible in the
692 * current search path. Visible means "would be found by searching
693 * for the unqualified relation name".
696 RelationIsVisible(Oid relid)
699 Form_pg_class relform;
703 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
704 if (!HeapTupleIsValid(reltup))
705 elog(ERROR, "cache lookup failed for relation %u", relid);
706 relform = (Form_pg_class) GETSTRUCT(reltup);
708 recomputeNamespacePath();
711 * Quick check: if it ain't in the path at all, it ain't visible. Items in
712 * the system namespace are surely in the path and so we needn't even do
713 * list_member_oid() for them.
715 relnamespace = relform->relnamespace;
716 if (relnamespace != PG_CATALOG_NAMESPACE &&
717 !list_member_oid(activeSearchPath, relnamespace))
722 * If it is in the path, it might still not be visible; it could be
723 * hidden by another relation of the same name earlier in the path. So
724 * we must do a slow check for conflicting relations.
726 char *relname = NameStr(relform->relname);
730 foreach(l, activeSearchPath)
732 Oid namespaceId = lfirst_oid(l);
734 if (namespaceId == relnamespace)
736 /* Found it first in path */
740 if (OidIsValid(get_relname_relid(relname, namespaceId)))
742 /* Found something else first in path */
748 ReleaseSysCache(reltup);
756 * Try to resolve an unqualified datatype name.
757 * Returns OID if type found in search path, else InvalidOid.
759 * This is essentially the same as RelnameGetRelid.
762 TypenameGetTypid(const char *typname)
767 recomputeNamespacePath();
769 foreach(l, activeSearchPath)
771 Oid namespaceId = lfirst_oid(l);
773 typid = GetSysCacheOid2(TYPENAMENSP,
774 PointerGetDatum(typname),
775 ObjectIdGetDatum(namespaceId));
776 if (OidIsValid(typid))
780 /* Not found in path */
786 * Determine whether a type (identified by OID) is visible in the
787 * current search path. Visible means "would be found by searching
788 * for the unqualified type name".
791 TypeIsVisible(Oid typid)
794 Form_pg_type typform;
798 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
799 if (!HeapTupleIsValid(typtup))
800 elog(ERROR, "cache lookup failed for type %u", typid);
801 typform = (Form_pg_type) GETSTRUCT(typtup);
803 recomputeNamespacePath();
806 * Quick check: if it ain't in the path at all, it ain't visible. Items in
807 * the system namespace are surely in the path and so we needn't even do
808 * list_member_oid() for them.
810 typnamespace = typform->typnamespace;
811 if (typnamespace != PG_CATALOG_NAMESPACE &&
812 !list_member_oid(activeSearchPath, typnamespace))
817 * If it is in the path, it might still not be visible; it could be
818 * hidden by another type of the same name earlier in the path. So we
819 * must do a slow check for conflicting types.
821 char *typname = NameStr(typform->typname);
825 foreach(l, activeSearchPath)
827 Oid namespaceId = lfirst_oid(l);
829 if (namespaceId == typnamespace)
831 /* Found it first in path */
835 if (SearchSysCacheExists2(TYPENAMENSP,
836 PointerGetDatum(typname),
837 ObjectIdGetDatum(namespaceId)))
839 /* Found something else first in path */
845 ReleaseSysCache(typtup);
852 * FuncnameGetCandidates
853 * Given a possibly-qualified function name and argument count,
854 * retrieve a list of the possible matches.
856 * If nargs is -1, we return all functions matching the given name,
857 * regardless of argument count. (argnames must be NIL, and expand_variadic
858 * and expand_defaults must be false, in this case.)
860 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
861 * and only functions having all the listed argument names will be returned.
862 * (We assume that length(argnames) <= nargs and all the passed-in names are
863 * distinct.) The returned structs will include an argnumbers array showing
864 * the actual argument index for each logical argument position.
866 * If expand_variadic is true, then variadic functions having the same number
867 * or fewer arguments will be retrieved, with the variadic argument and any
868 * additional argument positions filled with the variadic element type.
869 * nvargs in the returned struct is set to the number of such arguments.
870 * If expand_variadic is false, variadic arguments are not treated specially,
871 * and the returned nvargs will always be zero.
873 * If expand_defaults is true, functions that could match after insertion of
874 * default argument values will also be retrieved. In this case the returned
875 * structs could have nargs > passed-in nargs, and ndargs is set to the number
876 * of additional args (which can be retrieved from the function's
877 * proargdefaults entry).
879 * It is not possible for nvargs and ndargs to both be nonzero in the same
880 * list entry, since default insertion allows matches to functions with more
881 * than nargs arguments while the variadic transformation requires the same
884 * When argnames isn't NIL, the returned args[] type arrays are not ordered
885 * according to the functions' declarations, but rather according to the call:
886 * first any positional arguments, then the named arguments, then defaulted
887 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
888 * array can be used to map this back to the catalog information.
889 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
891 * We search a single namespace if the function name is qualified, else
892 * all namespaces in the search path. In the multiple-namespace case,
893 * we arrange for entries in earlier namespaces to mask identical entries in
896 * When expanding variadics, we arrange for non-variadic functions to mask
897 * variadic ones if the expanded argument list is the same. It is still
898 * possible for there to be conflicts between different variadic functions,
901 * It is guaranteed that the return list will never contain multiple entries
902 * with identical argument lists. When expand_defaults is true, the entries
903 * could have more than nargs positions, but we still guarantee that they are
904 * distinct in the first nargs positions. However, if argnames isn't NIL or
905 * either expand_variadic or expand_defaults is true, there might be multiple
906 * candidate functions that expand to identical argument lists. Rather than
907 * throw error here, we report such situations by returning a single entry
908 * with oid = 0 that represents a set of such conflicting candidates.
909 * The caller might end up discarding such an entry anyway, but if it selects
910 * such an entry it should react as though the call were ambiguous.
912 * If missing_ok is true, an empty list (NULL) is returned if the name was
913 * schema- qualified with a schema that does not exist. Likewise if no
914 * candidate is found for other reasons.
917 FuncnameGetCandidates(List *names, int nargs, List *argnames,
918 bool expand_variadic, bool expand_defaults,
921 FuncCandidateList resultList = NULL;
922 bool any_special = false;
929 /* check for caller error */
930 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
932 /* deconstruct the name list */
933 DeconstructQualifiedName(names, &schemaname, &funcname);
937 /* use exact schema given */
938 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
939 if (!OidIsValid(namespaceId))
944 /* flag to indicate we need namespace search */
945 namespaceId = InvalidOid;
946 recomputeNamespacePath();
949 /* Search syscache by name only */
950 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
952 for (i = 0; i < catlist->n_members; i++)
954 HeapTuple proctup = &catlist->members[i]->tuple;
955 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
956 int pronargs = procform->pronargs;
962 int *argnumbers = NULL;
963 FuncCandidateList newResult;
965 if (OidIsValid(namespaceId))
967 /* Consider only procs in specified namespace */
968 if (procform->pronamespace != namespaceId)
974 * Consider only procs that are in the search path and are not in
975 * the temp namespace.
979 foreach(nsp, activeSearchPath)
981 if (procform->pronamespace == lfirst_oid(nsp) &&
982 procform->pronamespace != myTempNamespace)
987 continue; /* proc is not in search path */
993 * Call uses named or mixed notation
995 * Named or mixed notation can match a variadic function only if
996 * expand_variadic is off; otherwise there is no way to match the
997 * presumed-nameless parameters expanded from the variadic array.
999 if (OidIsValid(procform->provariadic) && expand_variadic)
1001 va_elem_type = InvalidOid;
1005 * Check argument count.
1007 Assert(nargs >= 0); /* -1 not supported with argnames */
1009 if (pronargs > nargs && expand_defaults)
1011 /* Ignore if not enough default expressions */
1012 if (nargs + procform->pronargdefaults < pronargs)
1014 use_defaults = true;
1017 use_defaults = false;
1019 /* Ignore if it doesn't match requested argument count */
1020 if (pronargs != nargs && !use_defaults)
1023 /* Check for argument name match, generate positional mapping */
1024 if (!MatchNamedCall(proctup, nargs, argnames,
1028 /* Named argument matching is always "special" */
1034 * Call uses positional notation
1036 * Check if function is variadic, and get variadic element type if
1037 * so. If expand_variadic is false, we should just ignore
1040 if (pronargs <= nargs && expand_variadic)
1042 va_elem_type = procform->provariadic;
1043 variadic = OidIsValid(va_elem_type);
1044 any_special |= variadic;
1048 va_elem_type = InvalidOid;
1053 * Check if function can match by using parameter defaults.
1055 if (pronargs > nargs && expand_defaults)
1057 /* Ignore if not enough default expressions */
1058 if (nargs + procform->pronargdefaults < pronargs)
1060 use_defaults = true;
1064 use_defaults = false;
1066 /* Ignore if it doesn't match requested argument count */
1067 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1072 * We must compute the effective argument list so that we can easily
1073 * compare it to earlier results. We waste a palloc cycle if it gets
1074 * masked by an earlier result, but really that's a pretty infrequent
1075 * case so it's not worth worrying about.
1077 effective_nargs = Max(pronargs, nargs);
1078 newResult = (FuncCandidateList)
1079 palloc(offsetof(struct _FuncCandidateList, args) +
1080 effective_nargs * sizeof(Oid));
1081 newResult->pathpos = pathpos;
1082 newResult->oid = HeapTupleGetOid(proctup);
1083 newResult->nargs = effective_nargs;
1084 newResult->argnumbers = argnumbers;
1087 /* Re-order the argument types into call's logical order */
1088 Oid *proargtypes = procform->proargtypes.values;
1091 for (i = 0; i < pronargs; i++)
1092 newResult->args[i] = proargtypes[argnumbers[i]];
1096 /* Simple positional case, just copy proargtypes as-is */
1097 memcpy(newResult->args, procform->proargtypes.values,
1098 pronargs * sizeof(Oid));
1104 newResult->nvargs = effective_nargs - pronargs + 1;
1105 /* Expand variadic argument into N copies of element type */
1106 for (i = pronargs - 1; i < effective_nargs; i++)
1107 newResult->args[i] = va_elem_type;
1110 newResult->nvargs = 0;
1111 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1114 * Does it have the same arguments as something we already accepted?
1115 * If so, decide what to do to avoid returning duplicate argument
1116 * lists. We can skip this check for the single-namespace case if no
1117 * special (named, variadic or defaults) match has been made, since
1118 * then the unique index on pg_proc guarantees all the matches have
1119 * different argument lists.
1121 if (resultList != NULL &&
1122 (any_special || !OidIsValid(namespaceId)))
1125 * If we have an ordered list from SearchSysCacheList (the normal
1126 * case), then any conflicting proc must immediately adjoin this
1127 * one in the list, so we only need to look at the newest result
1128 * item. If we have an unordered list, we have to scan the whole
1129 * result list. Also, if either the current candidate or any
1130 * previous candidate is a special match, we can't assume that
1131 * conflicts are adjacent.
1133 * We ignore defaulted arguments in deciding what is a match.
1135 FuncCandidateList prevResult;
1137 if (catlist->ordered && !any_special)
1139 /* ndargs must be 0 if !any_special */
1140 if (effective_nargs == resultList->nargs &&
1141 memcmp(newResult->args,
1143 effective_nargs * sizeof(Oid)) == 0)
1144 prevResult = resultList;
1150 int cmp_nargs = newResult->nargs - newResult->ndargs;
1152 for (prevResult = resultList;
1154 prevResult = prevResult->next)
1156 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1157 memcmp(newResult->args,
1159 cmp_nargs * sizeof(Oid)) == 0)
1167 * We have a match with a previous result. Decide which one
1168 * to keep, or mark it ambiguous if we can't decide. The
1169 * logic here is preference > 0 means prefer the old result,
1170 * preference < 0 means prefer the new, preference = 0 means
1175 if (pathpos != prevResult->pathpos)
1178 * Prefer the one that's earlier in the search path.
1180 preference = pathpos - prevResult->pathpos;
1182 else if (variadic && prevResult->nvargs == 0)
1185 * With variadic functions we could have, for example,
1186 * both foo(numeric) and foo(variadic numeric[]) in the
1187 * same namespace; if so we prefer the non-variadic match
1188 * on efficiency grounds.
1192 else if (!variadic && prevResult->nvargs > 0)
1199 * We can't decide. This can happen with, for example,
1200 * both foo(numeric, variadic numeric[]) and
1201 * foo(variadic numeric[]) in the same namespace, or
1202 * both foo(int) and foo (int, int default something)
1203 * in the same namespace, or both foo(a int, b text)
1204 * and foo(b text, a int) in the same namespace.
1212 /* keep previous result */
1216 else if (preference < 0)
1218 /* remove previous result from the list */
1219 if (prevResult == resultList)
1220 resultList = prevResult->next;
1223 FuncCandidateList prevPrevResult;
1225 for (prevPrevResult = resultList;
1227 prevPrevResult = prevPrevResult->next)
1229 if (prevResult == prevPrevResult->next)
1231 prevPrevResult->next = prevResult->next;
1235 Assert(prevPrevResult); /* assert we found it */
1238 /* fall through to add newResult to list */
1242 /* mark old result as ambiguous, discard new */
1243 prevResult->oid = InvalidOid;
1251 * Okay to add it to result list
1253 newResult->next = resultList;
1254 resultList = newResult;
1257 ReleaseSysCacheList(catlist);
1264 * Given a pg_proc heap tuple and a call's list of argument names,
1265 * check whether the function could match the call.
1267 * The call could match if all supplied argument names are accepted by
1268 * the function, in positions after the last positional argument, and there
1269 * are defaults for all unsupplied arguments.
1271 * The number of positional arguments is nargs - list_length(argnames).
1272 * Note caller has already done basic checks on argument count.
1274 * On match, return true and fill *argnumbers with a palloc'd array showing
1275 * the mapping from call argument positions to actual function argument
1276 * numbers. Defaulted arguments are included in this map, at positions
1277 * after the last supplied argument.
1280 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1283 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1284 int pronargs = procform->pronargs;
1285 int numposargs = nargs - list_length(argnames);
1290 bool arggiven[FUNC_MAX_ARGS];
1292 int ap; /* call args position */
1293 int pp; /* proargs position */
1296 Assert(argnames != NIL);
1297 Assert(numposargs >= 0);
1298 Assert(nargs <= pronargs);
1300 /* Ignore this function if its proargnames is null */
1301 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1306 /* OK, let's extract the argument names and types */
1307 pronallargs = get_func_arg_info(proctup,
1308 &p_argtypes, &p_argnames, &p_argmodes);
1309 Assert(p_argnames != NULL);
1311 /* initialize state for matching */
1312 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1313 memset(arggiven, false, pronargs * sizeof(bool));
1315 /* there are numposargs positional args before the named args */
1316 for (ap = 0; ap < numposargs; ap++)
1318 (*argnumbers)[ap] = ap;
1319 arggiven[ap] = true;
1322 /* now examine the named args */
1323 foreach(lc, argnames)
1325 char *argname = (char *) lfirst(lc);
1331 for (i = 0; i < pronallargs; i++)
1333 /* consider only input parameters */
1335 (p_argmodes[i] != FUNC_PARAM_IN &&
1336 p_argmodes[i] != FUNC_PARAM_INOUT &&
1337 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1339 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1341 /* fail if argname matches a positional argument */
1344 arggiven[pp] = true;
1345 (*argnumbers)[ap] = pp;
1349 /* increase pp only for input parameters */
1352 /* if name isn't in proargnames, fail */
1358 Assert(ap == nargs); /* processed all actual parameters */
1360 /* Check for default arguments */
1361 if (nargs < pronargs)
1363 int first_arg_with_default = pronargs - procform->pronargdefaults;
1365 for (pp = numposargs; pp < pronargs; pp++)
1369 /* fail if arg not given and no default available */
1370 if (pp < first_arg_with_default)
1372 (*argnumbers)[ap++] = pp;
1376 Assert(ap == pronargs); /* processed all function parameters */
1383 * Determine whether a function (identified by OID) is visible in the
1384 * current search path. Visible means "would be found by searching
1385 * for the unqualified function name with exact argument matches".
1388 FunctionIsVisible(Oid funcid)
1391 Form_pg_proc procform;
1395 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1396 if (!HeapTupleIsValid(proctup))
1397 elog(ERROR, "cache lookup failed for function %u", funcid);
1398 procform = (Form_pg_proc) GETSTRUCT(proctup);
1400 recomputeNamespacePath();
1403 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1404 * the system namespace are surely in the path and so we needn't even do
1405 * list_member_oid() for them.
1407 pronamespace = procform->pronamespace;
1408 if (pronamespace != PG_CATALOG_NAMESPACE &&
1409 !list_member_oid(activeSearchPath, pronamespace))
1414 * If it is in the path, it might still not be visible; it could be
1415 * hidden by another proc of the same name and arguments earlier in
1416 * the path. So we must do a slow check to see if this is the same
1417 * proc that would be found by FuncnameGetCandidates.
1419 char *proname = NameStr(procform->proname);
1420 int nargs = procform->pronargs;
1421 FuncCandidateList clist;
1425 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1426 nargs, NIL, false, false, false);
1428 for (; clist; clist = clist->next)
1430 if (memcmp(clist->args, procform->proargtypes.values,
1431 nargs * sizeof(Oid)) == 0)
1433 /* Found the expected entry; is it the right proc? */
1434 visible = (clist->oid == funcid);
1440 ReleaseSysCache(proctup);
1448 * Given a possibly-qualified operator name and exact input datatypes,
1449 * look up the operator. Returns InvalidOid if not found.
1451 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1454 * If the operator name is not schema-qualified, it is sought in the current
1455 * namespace search path. If the name is schema-qualified and the given
1456 * schema does not exist, InvalidOid is returned.
1459 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1466 /* deconstruct the name list */
1467 DeconstructQualifiedName(names, &schemaname, &opername);
1471 /* search only in exact schema given */
1474 namespaceId = LookupExplicitNamespace(schemaname, true);
1475 if (OidIsValid(namespaceId))
1479 opertup = SearchSysCache4(OPERNAMENSP,
1480 CStringGetDatum(opername),
1481 ObjectIdGetDatum(oprleft),
1482 ObjectIdGetDatum(oprright),
1483 ObjectIdGetDatum(namespaceId));
1484 if (HeapTupleIsValid(opertup))
1486 Oid result = HeapTupleGetOid(opertup);
1488 ReleaseSysCache(opertup);
1496 /* Search syscache by name and argument types */
1497 catlist = SearchSysCacheList3(OPERNAMENSP,
1498 CStringGetDatum(opername),
1499 ObjectIdGetDatum(oprleft),
1500 ObjectIdGetDatum(oprright));
1502 if (catlist->n_members == 0)
1504 /* no hope, fall out early */
1505 ReleaseSysCacheList(catlist);
1510 * We have to find the list member that is first in the search path, if
1511 * there's more than one. This doubly-nested loop looks ugly, but in
1512 * practice there should usually be few catlist members.
1514 recomputeNamespacePath();
1516 foreach(l, activeSearchPath)
1518 Oid namespaceId = lfirst_oid(l);
1521 if (namespaceId == myTempNamespace)
1522 continue; /* do not look in temp namespace */
1524 for (i = 0; i < catlist->n_members; i++)
1526 HeapTuple opertup = &catlist->members[i]->tuple;
1527 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1529 if (operform->oprnamespace == namespaceId)
1531 Oid result = HeapTupleGetOid(opertup);
1533 ReleaseSysCacheList(catlist);
1539 ReleaseSysCacheList(catlist);
1544 * OpernameGetCandidates
1545 * Given a possibly-qualified operator name and operator kind,
1546 * retrieve a list of the possible matches.
1548 * If oprkind is '\0', we return all operators matching the given name,
1549 * regardless of arguments.
1551 * We search a single namespace if the operator name is qualified, else
1552 * all namespaces in the search path. The return list will never contain
1553 * multiple entries with identical argument lists --- in the multiple-
1554 * namespace case, we arrange for entries in earlier namespaces to mask
1555 * identical entries in later namespaces.
1557 * The returned items always have two args[] entries --- one or the other
1558 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1561 OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
1563 FuncCandidateList resultList = NULL;
1564 char *resultSpace = NULL;
1572 /* deconstruct the name list */
1573 DeconstructQualifiedName(names, &schemaname, &opername);
1577 /* use exact schema given */
1578 namespaceId = LookupExplicitNamespace(schemaname, missing_schema_ok);
1579 if (missing_schema_ok && !OidIsValid(namespaceId))
1584 /* flag to indicate we need namespace search */
1585 namespaceId = InvalidOid;
1586 recomputeNamespacePath();
1589 /* Search syscache by name only */
1590 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1593 * In typical scenarios, most if not all of the operators found by the
1594 * catcache search will end up getting returned; and there can be quite a
1595 * few, for common operator names such as '=' or '+'. To reduce the time
1596 * spent in palloc, we allocate the result space as an array large enough
1597 * to hold all the operators. The original coding of this routine did a
1598 * separate palloc for each operator, but profiling revealed that the
1599 * pallocs used an unreasonably large fraction of parsing time.
1601 #define SPACE_PER_OP MAXALIGN(offsetof(struct _FuncCandidateList, args) + \
1604 if (catlist->n_members > 0)
1605 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1607 for (i = 0; i < catlist->n_members; i++)
1609 HeapTuple opertup = &catlist->members[i]->tuple;
1610 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1612 FuncCandidateList newResult;
1614 /* Ignore operators of wrong kind, if specific kind requested */
1615 if (oprkind && operform->oprkind != oprkind)
1618 if (OidIsValid(namespaceId))
1620 /* Consider only opers in specified namespace */
1621 if (operform->oprnamespace != namespaceId)
1623 /* No need to check args, they must all be different */
1628 * Consider only opers that are in the search path and are not in
1629 * the temp namespace.
1633 foreach(nsp, activeSearchPath)
1635 if (operform->oprnamespace == lfirst_oid(nsp) &&
1636 operform->oprnamespace != myTempNamespace)
1641 continue; /* oper is not in search path */
1644 * Okay, it's in the search path, but does it have the same
1645 * arguments as something we already accepted? If so, keep only
1646 * the one that appears earlier in the search path.
1648 * If we have an ordered list from SearchSysCacheList (the normal
1649 * case), then any conflicting oper must immediately adjoin this
1650 * one in the list, so we only need to look at the newest result
1651 * item. If we have an unordered list, we have to scan the whole
1656 FuncCandidateList prevResult;
1658 if (catlist->ordered)
1660 if (operform->oprleft == resultList->args[0] &&
1661 operform->oprright == resultList->args[1])
1662 prevResult = resultList;
1668 for (prevResult = resultList;
1670 prevResult = prevResult->next)
1672 if (operform->oprleft == prevResult->args[0] &&
1673 operform->oprright == prevResult->args[1])
1679 /* We have a match with a previous result */
1680 Assert(pathpos != prevResult->pathpos);
1681 if (pathpos > prevResult->pathpos)
1682 continue; /* keep previous result */
1683 /* replace previous result */
1684 prevResult->pathpos = pathpos;
1685 prevResult->oid = HeapTupleGetOid(opertup);
1686 continue; /* args are same, of course */
1692 * Okay to add it to result list
1694 newResult = (FuncCandidateList) (resultSpace + nextResult);
1695 nextResult += SPACE_PER_OP;
1697 newResult->pathpos = pathpos;
1698 newResult->oid = HeapTupleGetOid(opertup);
1699 newResult->nargs = 2;
1700 newResult->nvargs = 0;
1701 newResult->ndargs = 0;
1702 newResult->argnumbers = NULL;
1703 newResult->args[0] = operform->oprleft;
1704 newResult->args[1] = operform->oprright;
1705 newResult->next = resultList;
1706 resultList = newResult;
1709 ReleaseSysCacheList(catlist);
1716 * Determine whether an operator (identified by OID) is visible in the
1717 * current search path. Visible means "would be found by searching
1718 * for the unqualified operator name with exact argument matches".
1721 OperatorIsVisible(Oid oprid)
1724 Form_pg_operator oprform;
1728 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1729 if (!HeapTupleIsValid(oprtup))
1730 elog(ERROR, "cache lookup failed for operator %u", oprid);
1731 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1733 recomputeNamespacePath();
1736 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1737 * the system namespace are surely in the path and so we needn't even do
1738 * list_member_oid() for them.
1740 oprnamespace = oprform->oprnamespace;
1741 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1742 !list_member_oid(activeSearchPath, oprnamespace))
1747 * If it is in the path, it might still not be visible; it could be
1748 * hidden by another operator of the same name and arguments earlier
1749 * in the path. So we must do a slow check to see if this is the same
1750 * operator that would be found by OpernameGetOprid.
1752 char *oprname = NameStr(oprform->oprname);
1754 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1755 oprform->oprleft, oprform->oprright)
1759 ReleaseSysCache(oprtup);
1766 * OpclassnameGetOpcid
1767 * Try to resolve an unqualified index opclass name.
1768 * Returns OID if opclass found in search path, else InvalidOid.
1770 * This is essentially the same as TypenameGetTypid, but we have to have
1771 * an extra argument for the index AM OID.
1774 OpclassnameGetOpcid(Oid amid, const char *opcname)
1779 recomputeNamespacePath();
1781 foreach(l, activeSearchPath)
1783 Oid namespaceId = lfirst_oid(l);
1785 if (namespaceId == myTempNamespace)
1786 continue; /* do not look in temp namespace */
1788 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1789 ObjectIdGetDatum(amid),
1790 PointerGetDatum(opcname),
1791 ObjectIdGetDatum(namespaceId));
1792 if (OidIsValid(opcid))
1796 /* Not found in path */
1802 * Determine whether an opclass (identified by OID) is visible in the
1803 * current search path. Visible means "would be found by searching
1804 * for the unqualified opclass name".
1807 OpclassIsVisible(Oid opcid)
1810 Form_pg_opclass opcform;
1814 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1815 if (!HeapTupleIsValid(opctup))
1816 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1817 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1819 recomputeNamespacePath();
1822 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1823 * the system namespace are surely in the path and so we needn't even do
1824 * list_member_oid() for them.
1826 opcnamespace = opcform->opcnamespace;
1827 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1828 !list_member_oid(activeSearchPath, opcnamespace))
1833 * If it is in the path, it might still not be visible; it could be
1834 * hidden by another opclass of the same name earlier in the path. So
1835 * we must do a slow check to see if this opclass would be found by
1836 * OpclassnameGetOpcid.
1838 char *opcname = NameStr(opcform->opcname);
1840 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1843 ReleaseSysCache(opctup);
1849 * OpfamilynameGetOpfid
1850 * Try to resolve an unqualified index opfamily name.
1851 * Returns OID if opfamily found in search path, else InvalidOid.
1853 * This is essentially the same as TypenameGetTypid, but we have to have
1854 * an extra argument for the index AM OID.
1857 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1862 recomputeNamespacePath();
1864 foreach(l, activeSearchPath)
1866 Oid namespaceId = lfirst_oid(l);
1868 if (namespaceId == myTempNamespace)
1869 continue; /* do not look in temp namespace */
1871 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1872 ObjectIdGetDatum(amid),
1873 PointerGetDatum(opfname),
1874 ObjectIdGetDatum(namespaceId));
1875 if (OidIsValid(opfid))
1879 /* Not found in path */
1885 * Determine whether an opfamily (identified by OID) is visible in the
1886 * current search path. Visible means "would be found by searching
1887 * for the unqualified opfamily name".
1890 OpfamilyIsVisible(Oid opfid)
1893 Form_pg_opfamily opfform;
1897 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1898 if (!HeapTupleIsValid(opftup))
1899 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1900 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1902 recomputeNamespacePath();
1905 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1906 * the system namespace are surely in the path and so we needn't even do
1907 * list_member_oid() for them.
1909 opfnamespace = opfform->opfnamespace;
1910 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1911 !list_member_oid(activeSearchPath, opfnamespace))
1916 * If it is in the path, it might still not be visible; it could be
1917 * hidden by another opfamily of the same name earlier in the path. So
1918 * we must do a slow check to see if this opfamily would be found by
1919 * OpfamilynameGetOpfid.
1921 char *opfname = NameStr(opfform->opfname);
1923 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1926 ReleaseSysCache(opftup);
1932 * CollationGetCollid
1933 * Try to resolve an unqualified collation name.
1934 * Returns OID if collation found in search path, else InvalidOid.
1937 CollationGetCollid(const char *collname)
1939 int32 dbencoding = GetDatabaseEncoding();
1942 recomputeNamespacePath();
1944 foreach(l, activeSearchPath)
1946 Oid namespaceId = lfirst_oid(l);
1949 if (namespaceId == myTempNamespace)
1950 continue; /* do not look in temp namespace */
1952 /* Check for database-encoding-specific entry */
1953 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1954 PointerGetDatum(collname),
1955 Int32GetDatum(dbencoding),
1956 ObjectIdGetDatum(namespaceId));
1957 if (OidIsValid(collid))
1960 /* Check for any-encoding entry */
1961 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1962 PointerGetDatum(collname),
1964 ObjectIdGetDatum(namespaceId));
1965 if (OidIsValid(collid))
1969 /* Not found in path */
1974 * CollationIsVisible
1975 * Determine whether a collation (identified by OID) is visible in the
1976 * current search path. Visible means "would be found by searching
1977 * for the unqualified collation name".
1980 CollationIsVisible(Oid collid)
1983 Form_pg_collation collform;
1987 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1988 if (!HeapTupleIsValid(colltup))
1989 elog(ERROR, "cache lookup failed for collation %u", collid);
1990 collform = (Form_pg_collation) GETSTRUCT(colltup);
1992 recomputeNamespacePath();
1995 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1996 * the system namespace are surely in the path and so we needn't even do
1997 * list_member_oid() for them.
1999 collnamespace = collform->collnamespace;
2000 if (collnamespace != PG_CATALOG_NAMESPACE &&
2001 !list_member_oid(activeSearchPath, collnamespace))
2006 * If it is in the path, it might still not be visible; it could be
2007 * hidden by another conversion of the same name earlier in the path.
2008 * So we must do a slow check to see if this conversion would be found
2009 * by CollationGetCollid.
2011 char *collname = NameStr(collform->collname);
2013 visible = (CollationGetCollid(collname) == collid);
2016 ReleaseSysCache(colltup);
2023 * ConversionGetConid
2024 * Try to resolve an unqualified conversion name.
2025 * Returns OID if conversion found in search path, else InvalidOid.
2027 * This is essentially the same as RelnameGetRelid.
2030 ConversionGetConid(const char *conname)
2035 recomputeNamespacePath();
2037 foreach(l, activeSearchPath)
2039 Oid namespaceId = lfirst_oid(l);
2041 if (namespaceId == myTempNamespace)
2042 continue; /* do not look in temp namespace */
2044 conid = GetSysCacheOid2(CONNAMENSP,
2045 PointerGetDatum(conname),
2046 ObjectIdGetDatum(namespaceId));
2047 if (OidIsValid(conid))
2051 /* Not found in path */
2056 * ConversionIsVisible
2057 * Determine whether a conversion (identified by OID) is visible in the
2058 * current search path. Visible means "would be found by searching
2059 * for the unqualified conversion name".
2062 ConversionIsVisible(Oid conid)
2065 Form_pg_conversion conform;
2069 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2070 if (!HeapTupleIsValid(contup))
2071 elog(ERROR, "cache lookup failed for conversion %u", conid);
2072 conform = (Form_pg_conversion) GETSTRUCT(contup);
2074 recomputeNamespacePath();
2077 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2078 * the system namespace are surely in the path and so we needn't even do
2079 * list_member_oid() for them.
2081 connamespace = conform->connamespace;
2082 if (connamespace != PG_CATALOG_NAMESPACE &&
2083 !list_member_oid(activeSearchPath, connamespace))
2088 * If it is in the path, it might still not be visible; it could be
2089 * hidden by another conversion of the same name earlier in the path.
2090 * So we must do a slow check to see if this conversion would be found
2091 * by ConversionGetConid.
2093 char *conname = NameStr(conform->conname);
2095 visible = (ConversionGetConid(conname) == conid);
2098 ReleaseSysCache(contup);
2104 * get_ts_parser_oid - find a TS parser by possibly qualified name
2106 * If not found, returns InvalidOid if missing_ok, else throws error
2109 get_ts_parser_oid(List *names, bool missing_ok)
2114 Oid prsoid = InvalidOid;
2117 /* deconstruct the name list */
2118 DeconstructQualifiedName(names, &schemaname, &parser_name);
2122 /* use exact schema given */
2123 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2124 if (missing_ok && !OidIsValid(namespaceId))
2125 prsoid = InvalidOid;
2127 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2128 PointerGetDatum(parser_name),
2129 ObjectIdGetDatum(namespaceId));
2133 /* search for it in search path */
2134 recomputeNamespacePath();
2136 foreach(l, activeSearchPath)
2138 namespaceId = lfirst_oid(l);
2140 if (namespaceId == myTempNamespace)
2141 continue; /* do not look in temp namespace */
2143 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2144 PointerGetDatum(parser_name),
2145 ObjectIdGetDatum(namespaceId));
2146 if (OidIsValid(prsoid))
2151 if (!OidIsValid(prsoid) && !missing_ok)
2153 (errcode(ERRCODE_UNDEFINED_OBJECT),
2154 errmsg("text search parser \"%s\" does not exist",
2155 NameListToString(names))));
2162 * Determine whether a parser (identified by OID) is visible in the
2163 * current search path. Visible means "would be found by searching
2164 * for the unqualified parser name".
2167 TSParserIsVisible(Oid prsId)
2170 Form_pg_ts_parser form;
2174 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2175 if (!HeapTupleIsValid(tup))
2176 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2177 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2179 recomputeNamespacePath();
2182 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2183 * the system namespace are surely in the path and so we needn't even do
2184 * list_member_oid() for them.
2186 namespace = form->prsnamespace;
2187 if (namespace != PG_CATALOG_NAMESPACE &&
2188 !list_member_oid(activeSearchPath, namespace))
2193 * If it is in the path, it might still not be visible; it could be
2194 * hidden by another parser of the same name earlier in the path. So
2195 * we must do a slow check for conflicting parsers.
2197 char *name = NameStr(form->prsname);
2201 foreach(l, activeSearchPath)
2203 Oid namespaceId = lfirst_oid(l);
2205 if (namespaceId == myTempNamespace)
2206 continue; /* do not look in temp namespace */
2208 if (namespaceId == namespace)
2210 /* Found it first in path */
2214 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2215 PointerGetDatum(name),
2216 ObjectIdGetDatum(namespaceId)))
2218 /* Found something else first in path */
2224 ReleaseSysCache(tup);
2230 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2232 * If not found, returns InvalidOid if failOK, else throws error
2235 get_ts_dict_oid(List *names, bool missing_ok)
2240 Oid dictoid = InvalidOid;
2243 /* deconstruct the name list */
2244 DeconstructQualifiedName(names, &schemaname, &dict_name);
2248 /* use exact schema given */
2249 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2250 if (missing_ok && !OidIsValid(namespaceId))
2251 dictoid = InvalidOid;
2253 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2254 PointerGetDatum(dict_name),
2255 ObjectIdGetDatum(namespaceId));
2259 /* search for it in search path */
2260 recomputeNamespacePath();
2262 foreach(l, activeSearchPath)
2264 namespaceId = lfirst_oid(l);
2266 if (namespaceId == myTempNamespace)
2267 continue; /* do not look in temp namespace */
2269 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2270 PointerGetDatum(dict_name),
2271 ObjectIdGetDatum(namespaceId));
2272 if (OidIsValid(dictoid))
2277 if (!OidIsValid(dictoid) && !missing_ok)
2279 (errcode(ERRCODE_UNDEFINED_OBJECT),
2280 errmsg("text search dictionary \"%s\" does not exist",
2281 NameListToString(names))));
2287 * TSDictionaryIsVisible
2288 * Determine whether a dictionary (identified by OID) is visible in the
2289 * current search path. Visible means "would be found by searching
2290 * for the unqualified dictionary name".
2293 TSDictionaryIsVisible(Oid dictId)
2296 Form_pg_ts_dict form;
2300 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2301 if (!HeapTupleIsValid(tup))
2302 elog(ERROR, "cache lookup failed for text search dictionary %u",
2304 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2306 recomputeNamespacePath();
2309 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2310 * the system namespace are surely in the path and so we needn't even do
2311 * list_member_oid() for them.
2313 namespace = form->dictnamespace;
2314 if (namespace != PG_CATALOG_NAMESPACE &&
2315 !list_member_oid(activeSearchPath, namespace))
2320 * If it is in the path, it might still not be visible; it could be
2321 * hidden by another dictionary of the same name earlier in the path.
2322 * So we must do a slow check for conflicting dictionaries.
2324 char *name = NameStr(form->dictname);
2328 foreach(l, activeSearchPath)
2330 Oid namespaceId = lfirst_oid(l);
2332 if (namespaceId == myTempNamespace)
2333 continue; /* do not look in temp namespace */
2335 if (namespaceId == namespace)
2337 /* Found it first in path */
2341 if (SearchSysCacheExists2(TSDICTNAMENSP,
2342 PointerGetDatum(name),
2343 ObjectIdGetDatum(namespaceId)))
2345 /* Found something else first in path */
2351 ReleaseSysCache(tup);
2357 * get_ts_template_oid - find a TS template by possibly qualified name
2359 * If not found, returns InvalidOid if missing_ok, else throws error
2362 get_ts_template_oid(List *names, bool missing_ok)
2365 char *template_name;
2367 Oid tmploid = InvalidOid;
2370 /* deconstruct the name list */
2371 DeconstructQualifiedName(names, &schemaname, &template_name);
2375 /* use exact schema given */
2376 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2377 if (missing_ok && !OidIsValid(namespaceId))
2378 tmploid = InvalidOid;
2380 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2381 PointerGetDatum(template_name),
2382 ObjectIdGetDatum(namespaceId));
2386 /* search for it in search path */
2387 recomputeNamespacePath();
2389 foreach(l, activeSearchPath)
2391 namespaceId = lfirst_oid(l);
2393 if (namespaceId == myTempNamespace)
2394 continue; /* do not look in temp namespace */
2396 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2397 PointerGetDatum(template_name),
2398 ObjectIdGetDatum(namespaceId));
2399 if (OidIsValid(tmploid))
2404 if (!OidIsValid(tmploid) && !missing_ok)
2406 (errcode(ERRCODE_UNDEFINED_OBJECT),
2407 errmsg("text search template \"%s\" does not exist",
2408 NameListToString(names))));
2414 * TSTemplateIsVisible
2415 * Determine whether a template (identified by OID) is visible in the
2416 * current search path. Visible means "would be found by searching
2417 * for the unqualified template name".
2420 TSTemplateIsVisible(Oid tmplId)
2423 Form_pg_ts_template form;
2427 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2428 if (!HeapTupleIsValid(tup))
2429 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2430 form = (Form_pg_ts_template) GETSTRUCT(tup);
2432 recomputeNamespacePath();
2435 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2436 * the system namespace are surely in the path and so we needn't even do
2437 * list_member_oid() for them.
2439 namespace = form->tmplnamespace;
2440 if (namespace != PG_CATALOG_NAMESPACE &&
2441 !list_member_oid(activeSearchPath, namespace))
2446 * If it is in the path, it might still not be visible; it could be
2447 * hidden by another template of the same name earlier in the path. So
2448 * we must do a slow check for conflicting templates.
2450 char *name = NameStr(form->tmplname);
2454 foreach(l, activeSearchPath)
2456 Oid namespaceId = lfirst_oid(l);
2458 if (namespaceId == myTempNamespace)
2459 continue; /* do not look in temp namespace */
2461 if (namespaceId == namespace)
2463 /* Found it first in path */
2467 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2468 PointerGetDatum(name),
2469 ObjectIdGetDatum(namespaceId)))
2471 /* Found something else first in path */
2477 ReleaseSysCache(tup);
2483 * get_ts_config_oid - find a TS config by possibly qualified name
2485 * If not found, returns InvalidOid if missing_ok, else throws error
2488 get_ts_config_oid(List *names, bool missing_ok)
2493 Oid cfgoid = InvalidOid;
2496 /* deconstruct the name list */
2497 DeconstructQualifiedName(names, &schemaname, &config_name);
2501 /* use exact schema given */
2502 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2503 if (missing_ok && !OidIsValid(namespaceId))
2504 cfgoid = InvalidOid;
2506 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2507 PointerGetDatum(config_name),
2508 ObjectIdGetDatum(namespaceId));
2512 /* search for it in search path */
2513 recomputeNamespacePath();
2515 foreach(l, activeSearchPath)
2517 namespaceId = lfirst_oid(l);
2519 if (namespaceId == myTempNamespace)
2520 continue; /* do not look in temp namespace */
2522 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2523 PointerGetDatum(config_name),
2524 ObjectIdGetDatum(namespaceId));
2525 if (OidIsValid(cfgoid))
2530 if (!OidIsValid(cfgoid) && !missing_ok)
2532 (errcode(ERRCODE_UNDEFINED_OBJECT),
2533 errmsg("text search configuration \"%s\" does not exist",
2534 NameListToString(names))));
2541 * Determine whether a text search configuration (identified by OID)
2542 * is visible in the current search path. Visible means "would be found
2543 * by searching for the unqualified text search configuration name".
2546 TSConfigIsVisible(Oid cfgid)
2549 Form_pg_ts_config form;
2553 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2554 if (!HeapTupleIsValid(tup))
2555 elog(ERROR, "cache lookup failed for text search configuration %u",
2557 form = (Form_pg_ts_config) GETSTRUCT(tup);
2559 recomputeNamespacePath();
2562 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2563 * the system namespace are surely in the path and so we needn't even do
2564 * list_member_oid() for them.
2566 namespace = form->cfgnamespace;
2567 if (namespace != PG_CATALOG_NAMESPACE &&
2568 !list_member_oid(activeSearchPath, namespace))
2573 * If it is in the path, it might still not be visible; it could be
2574 * hidden by another configuration of the same name earlier in the
2575 * path. So we must do a slow check for conflicting configurations.
2577 char *name = NameStr(form->cfgname);
2581 foreach(l, activeSearchPath)
2583 Oid namespaceId = lfirst_oid(l);
2585 if (namespaceId == myTempNamespace)
2586 continue; /* do not look in temp namespace */
2588 if (namespaceId == namespace)
2590 /* Found it first in path */
2594 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2595 PointerGetDatum(name),
2596 ObjectIdGetDatum(namespaceId)))
2598 /* Found something else first in path */
2604 ReleaseSysCache(tup);
2611 * DeconstructQualifiedName
2612 * Given a possibly-qualified name expressed as a list of String nodes,
2613 * extract the schema name and object name.
2615 * *nspname_p is set to NULL if there is no explicit schema name.
2618 DeconstructQualifiedName(List *names,
2623 char *schemaname = NULL;
2624 char *objname = NULL;
2626 switch (list_length(names))
2629 objname = strVal(linitial(names));
2632 schemaname = strVal(linitial(names));
2633 objname = strVal(lsecond(names));
2636 catalogname = strVal(linitial(names));
2637 schemaname = strVal(lsecond(names));
2638 objname = strVal(lthird(names));
2641 * We check the catalog name and then ignore it.
2643 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2645 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2646 errmsg("cross-database references are not implemented: %s",
2647 NameListToString(names))));
2651 (errcode(ERRCODE_SYNTAX_ERROR),
2652 errmsg("improper qualified name (too many dotted names): %s",
2653 NameListToString(names))));
2657 *nspname_p = schemaname;
2658 *objname_p = objname;
2662 * LookupNamespaceNoError
2663 * Look up a schema name.
2665 * Returns the namespace OID, or InvalidOid if not found.
2667 * Note this does NOT perform any permissions check --- callers are
2668 * responsible for being sure that an appropriate check is made.
2669 * In the majority of cases LookupExplicitNamespace is preferable.
2672 LookupNamespaceNoError(const char *nspname)
2674 /* check for pg_temp alias */
2675 if (strcmp(nspname, "pg_temp") == 0)
2677 if (OidIsValid(myTempNamespace))
2679 InvokeNamespaceSearchHook(myTempNamespace, true);
2680 return myTempNamespace;
2684 * Since this is used only for looking up existing objects, there is
2685 * no point in trying to initialize the temp namespace here; and doing
2686 * so might create problems for some callers. Just report "not found".
2691 return get_namespace_oid(nspname, true);
2695 * LookupExplicitNamespace
2696 * Process an explicitly-specified schema name: look up the schema
2697 * and verify we have USAGE (lookup) rights in it.
2699 * Returns the namespace OID
2702 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2705 AclResult aclresult;
2707 /* check for pg_temp alias */
2708 if (strcmp(nspname, "pg_temp") == 0)
2710 if (OidIsValid(myTempNamespace))
2711 return myTempNamespace;
2714 * Since this is used only for looking up existing objects, there is
2715 * no point in trying to initialize the temp namespace here; and doing
2716 * so might create problems for some callers --- just fall through.
2720 namespaceId = get_namespace_oid(nspname, missing_ok);
2721 if (missing_ok && !OidIsValid(namespaceId))
2724 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2725 if (aclresult != ACLCHECK_OK)
2726 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2728 /* Schema search hook for this lookup */
2729 InvokeNamespaceSearchHook(namespaceId, true);
2735 * LookupCreationNamespace
2736 * Look up the schema and verify we have CREATE rights on it.
2738 * This is just like LookupExplicitNamespace except for the different
2739 * permission check, and that we are willing to create pg_temp if needed.
2741 * Note: calling this may result in a CommandCounterIncrement operation,
2742 * if we have to create or clean out the temp namespace.
2745 LookupCreationNamespace(const char *nspname)
2748 AclResult aclresult;
2750 /* check for pg_temp alias */
2751 if (strcmp(nspname, "pg_temp") == 0)
2753 /* Initialize temp namespace if first time through */
2754 if (!OidIsValid(myTempNamespace))
2755 InitTempTableNamespace();
2756 return myTempNamespace;
2759 namespaceId = get_namespace_oid(nspname, false);
2761 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2762 if (aclresult != ACLCHECK_OK)
2763 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2770 * Common checks on switching namespaces.
2772 * We complain if either the old or new namespaces is a temporary schema
2773 * (or temporary toast schema), or if either the old or new namespaces is the
2777 CheckSetNamespace(Oid oldNspOid, Oid nspOid)
2779 /* disallow renaming into or out of temp schemas */
2780 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2782 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2783 errmsg("cannot move objects into or out of temporary schemas")));
2785 /* same for TOAST schema */
2786 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2788 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2789 errmsg("cannot move objects into or out of TOAST schema")));
2793 * QualifiedNameGetCreationNamespace
2794 * Given a possibly-qualified name for an object (in List-of-Values
2795 * format), determine what namespace the object should be created in.
2796 * Also extract and return the object name (last component of list).
2798 * Note: this does not apply any permissions check. Callers must check
2799 * for CREATE rights on the selected namespace when appropriate.
2801 * Note: calling this may result in a CommandCounterIncrement operation,
2802 * if we have to create or clean out the temp namespace.
2805 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2810 /* deconstruct the name list */
2811 DeconstructQualifiedName(names, &schemaname, objname_p);
2815 /* check for pg_temp alias */
2816 if (strcmp(schemaname, "pg_temp") == 0)
2818 /* Initialize temp namespace if first time through */
2819 if (!OidIsValid(myTempNamespace))
2820 InitTempTableNamespace();
2821 return myTempNamespace;
2823 /* use exact schema given */
2824 namespaceId = get_namespace_oid(schemaname, false);
2825 /* we do not check for USAGE rights here! */
2829 /* use the default creation namespace */
2830 recomputeNamespacePath();
2831 if (activeTempCreationPending)
2833 /* Need to initialize temp namespace */
2834 InitTempTableNamespace();
2835 return myTempNamespace;
2837 namespaceId = activeCreationNamespace;
2838 if (!OidIsValid(namespaceId))
2840 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2841 errmsg("no schema has been selected to create in")));
2848 * get_namespace_oid - given a namespace name, look up the OID
2850 * If missing_ok is false, throw an error if namespace name not found. If
2851 * true, just return InvalidOid.
2854 get_namespace_oid(const char *nspname, bool missing_ok)
2858 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2859 if (!OidIsValid(oid) && !missing_ok)
2861 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2862 errmsg("schema \"%s\" does not exist", nspname)));
2868 * makeRangeVarFromNameList
2869 * Utility routine to convert a qualified-name list into RangeVar form.
2872 makeRangeVarFromNameList(List *names)
2874 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2876 switch (list_length(names))
2879 rel->relname = strVal(linitial(names));
2882 rel->schemaname = strVal(linitial(names));
2883 rel->relname = strVal(lsecond(names));
2886 rel->catalogname = strVal(linitial(names));
2887 rel->schemaname = strVal(lsecond(names));
2888 rel->relname = strVal(lthird(names));
2892 (errcode(ERRCODE_SYNTAX_ERROR),
2893 errmsg("improper relation name (too many dotted names): %s",
2894 NameListToString(names))));
2903 * Utility routine to convert a qualified-name list into a string.
2905 * This is used primarily to form error messages, and so we do not quote
2906 * the list elements, for the sake of legibility.
2908 * In most scenarios the list elements should always be Value strings,
2909 * but we also allow A_Star for the convenience of ColumnRef processing.
2912 NameListToString(List *names)
2914 StringInfoData string;
2917 initStringInfo(&string);
2921 Node *name = (Node *) lfirst(l);
2923 if (l != list_head(names))
2924 appendStringInfoChar(&string, '.');
2926 if (IsA(name, String))
2927 appendStringInfoString(&string, strVal(name));
2928 else if (IsA(name, A_Star))
2929 appendStringInfoChar(&string, '*');
2931 elog(ERROR, "unexpected node type in name list: %d",
2932 (int) nodeTag(name));
2939 * NameListToQuotedString
2940 * Utility routine to convert a qualified-name list into a string.
2942 * Same as above except that names will be double-quoted where necessary,
2943 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2946 NameListToQuotedString(List *names)
2948 StringInfoData string;
2951 initStringInfo(&string);
2955 if (l != list_head(names))
2956 appendStringInfoChar(&string, '.');
2957 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2964 * isTempNamespace - is the given namespace my temporary-table namespace?
2967 isTempNamespace(Oid namespaceId)
2969 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2975 * isTempToastNamespace - is the given namespace my temporary-toast-table
2979 isTempToastNamespace(Oid namespaceId)
2981 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2987 * isTempOrTempToastNamespace - is the given namespace my temporary-table
2988 * namespace or my temporary-toast-table namespace?
2991 isTempOrTempToastNamespace(Oid namespaceId)
2993 if (OidIsValid(myTempNamespace) &&
2994 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3000 * isAnyTempNamespace - is the given namespace a temporary-table namespace
3001 * (either my own, or another backend's)? Temporary-toast-table namespaces
3002 * are included, too.
3005 isAnyTempNamespace(Oid namespaceId)
3010 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3011 nspname = get_namespace_name(namespaceId);
3013 return false; /* no such namespace? */
3014 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3015 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3021 * isOtherTempNamespace - is the given namespace some other backend's
3022 * temporary-table namespace (including temporary-toast-table namespaces)?
3024 * Note: for most purposes in the C code, this function is obsolete. Use
3025 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3028 isOtherTempNamespace(Oid namespaceId)
3030 /* If it's my own temp namespace, say "false" */
3031 if (isTempOrTempToastNamespace(namespaceId))
3033 /* Else, if it's any temp namespace, say "true" */
3034 return isAnyTempNamespace(namespaceId);
3038 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3039 * namespace (either my own, or another backend's), return the BackendId
3040 * that owns it. Temporary-toast-table namespaces are included, too.
3041 * If it isn't a temp namespace, return InvalidBackendId.
3044 GetTempNamespaceBackendId(Oid namespaceId)
3049 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3050 nspname = get_namespace_name(namespaceId);
3052 return InvalidBackendId; /* no such namespace? */
3053 if (strncmp(nspname, "pg_temp_", 8) == 0)
3054 result = atoi(nspname + 8);
3055 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3056 result = atoi(nspname + 14);
3058 result = InvalidBackendId;
3064 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3065 * which must already be assigned. (This is only used when creating a toast
3066 * table for a temp table, so we must have already done InitTempTableNamespace)
3069 GetTempToastNamespace(void)
3071 Assert(OidIsValid(myTempToastNamespace));
3072 return myTempToastNamespace;
3077 * GetOverrideSearchPath - fetch current search path definition in form
3078 * used by PushOverrideSearchPath.
3080 * The result structure is allocated in the specified memory context
3081 * (which might or might not be equal to CurrentMemoryContext); but any
3082 * junk created by revalidation calculations will be in CurrentMemoryContext.
3084 OverrideSearchPath *
3085 GetOverrideSearchPath(MemoryContext context)
3087 OverrideSearchPath *result;
3089 MemoryContext oldcxt;
3091 recomputeNamespacePath();
3093 oldcxt = MemoryContextSwitchTo(context);
3095 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3096 schemas = list_copy(activeSearchPath);
3097 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3099 if (linitial_oid(schemas) == myTempNamespace)
3100 result->addTemp = true;
3103 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3104 result->addCatalog = true;
3106 schemas = list_delete_first(schemas);
3108 result->schemas = schemas;
3110 MemoryContextSwitchTo(oldcxt);
3116 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3118 * The result structure is allocated in CurrentMemoryContext.
3120 OverrideSearchPath *
3121 CopyOverrideSearchPath(OverrideSearchPath *path)
3123 OverrideSearchPath *result;
3125 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3126 result->schemas = list_copy(path->schemas);
3127 result->addCatalog = path->addCatalog;
3128 result->addTemp = path->addTemp;
3134 * OverrideSearchPathMatchesCurrent - does path match current setting?
3137 OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
3142 recomputeNamespacePath();
3144 /* We scan down the activeSearchPath to see if it matches the input. */
3145 lc = list_head(activeSearchPath);
3147 /* If path->addTemp, first item should be my temp namespace. */
3150 if (lc && lfirst_oid(lc) == myTempNamespace)
3155 /* If path->addCatalog, next item should be pg_catalog. */
3156 if (path->addCatalog)
3158 if (lc && lfirst_oid(lc) == PG_CATALOG_NAMESPACE)
3163 /* We should now be looking at the activeCreationNamespace. */
3164 if (activeCreationNamespace != (lc ? lfirst_oid(lc) : InvalidOid))
3166 /* The remainder of activeSearchPath should match path->schemas. */
3167 foreach(lcp, path->schemas)
3169 if (lc && lfirst_oid(lc) == lfirst_oid(lcp))
3180 * PushOverrideSearchPath - temporarily override the search path
3182 * We allow nested overrides, hence the push/pop terminology. The GUC
3183 * search_path variable is ignored while an override is active.
3185 * It's possible that newpath->useTemp is set but there is no longer any
3186 * active temp namespace, if the path was saved during a transaction that
3187 * created a temp namespace and was later rolled back. In that case we just
3188 * ignore useTemp. A plausible alternative would be to create a new temp
3189 * namespace, but for existing callers that's not necessary because an empty
3190 * temp namespace wouldn't affect their results anyway.
3192 * It's also worth noting that other schemas listed in newpath might not
3193 * exist anymore either. We don't worry about this because OIDs that match
3194 * no existing namespace will simply not produce any hits during searches.
3197 PushOverrideSearchPath(OverrideSearchPath *newpath)
3199 OverrideStackEntry *entry;
3202 MemoryContext oldcxt;
3205 * Copy the list for safekeeping, and insert implicitly-searched
3206 * namespaces as needed. This code should track recomputeNamespacePath.
3208 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3210 oidlist = list_copy(newpath->schemas);
3213 * Remember the first member of the explicit list.
3216 firstNS = InvalidOid;
3218 firstNS = linitial_oid(oidlist);
3221 * Add any implicitly-searched namespaces to the list. Note these go on
3222 * the front, not the back; also notice that we do not check USAGE
3223 * permissions for these.
3225 if (newpath->addCatalog)
3226 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3228 if (newpath->addTemp && OidIsValid(myTempNamespace))
3229 oidlist = lcons_oid(myTempNamespace, oidlist);
3232 * Build the new stack entry, then insert it at the head of the list.
3234 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3235 entry->searchPath = oidlist;
3236 entry->creationNamespace = firstNS;
3237 entry->nestLevel = GetCurrentTransactionNestLevel();
3239 overrideStack = lcons(entry, overrideStack);
3241 /* And make it active. */
3242 activeSearchPath = entry->searchPath;
3243 activeCreationNamespace = entry->creationNamespace;
3244 activeTempCreationPending = false; /* XXX is this OK? */
3246 MemoryContextSwitchTo(oldcxt);
3250 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3252 * Any push during a (sub)transaction will be popped automatically at abort.
3253 * But it's caller error if a push isn't popped in normal control flow.
3256 PopOverrideSearchPath(void)
3258 OverrideStackEntry *entry;
3260 /* Sanity checks. */
3261 if (overrideStack == NIL)
3262 elog(ERROR, "bogus PopOverrideSearchPath call");
3263 entry = (OverrideStackEntry *) linitial(overrideStack);
3264 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3265 elog(ERROR, "bogus PopOverrideSearchPath call");
3267 /* Pop the stack and free storage. */
3268 overrideStack = list_delete_first(overrideStack);
3269 list_free(entry->searchPath);
3272 /* Activate the next level down. */
3275 entry = (OverrideStackEntry *) linitial(overrideStack);
3276 activeSearchPath = entry->searchPath;
3277 activeCreationNamespace = entry->creationNamespace;
3278 activeTempCreationPending = false; /* XXX is this OK? */
3282 /* If not baseSearchPathValid, this is useless but harmless */
3283 activeSearchPath = baseSearchPath;
3284 activeCreationNamespace = baseCreationNamespace;
3285 activeTempCreationPending = baseTempCreationPending;
3291 * get_collation_oid - find a collation by possibly qualified name
3294 get_collation_oid(List *name, bool missing_ok)
3297 char *collation_name;
3298 int32 dbencoding = GetDatabaseEncoding();
3303 /* deconstruct the name list */
3304 DeconstructQualifiedName(name, &schemaname, &collation_name);
3308 /* use exact schema given */
3309 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3310 if (missing_ok && !OidIsValid(namespaceId))
3313 /* first try for encoding-specific entry, then any-encoding */
3314 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3315 PointerGetDatum(collation_name),
3316 Int32GetDatum(dbencoding),
3317 ObjectIdGetDatum(namespaceId));
3318 if (OidIsValid(colloid))
3320 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3321 PointerGetDatum(collation_name),
3323 ObjectIdGetDatum(namespaceId));
3324 if (OidIsValid(colloid))
3329 /* search for it in search path */
3330 recomputeNamespacePath();
3332 foreach(l, activeSearchPath)
3334 namespaceId = lfirst_oid(l);
3336 if (namespaceId == myTempNamespace)
3337 continue; /* do not look in temp namespace */
3339 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3340 PointerGetDatum(collation_name),
3341 Int32GetDatum(dbencoding),
3342 ObjectIdGetDatum(namespaceId));
3343 if (OidIsValid(colloid))
3345 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3346 PointerGetDatum(collation_name),
3348 ObjectIdGetDatum(namespaceId));
3349 if (OidIsValid(colloid))
3354 /* Not found in path */
3357 (errcode(ERRCODE_UNDEFINED_OBJECT),
3358 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3359 NameListToString(name), GetDatabaseEncodingName())));
3364 * get_conversion_oid - find a conversion by possibly qualified name
3367 get_conversion_oid(List *name, bool missing_ok)
3370 char *conversion_name;
3372 Oid conoid = InvalidOid;
3375 /* deconstruct the name list */
3376 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3380 /* use exact schema given */
3381 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3382 if (missing_ok && !OidIsValid(namespaceId))
3383 conoid = InvalidOid;
3385 conoid = GetSysCacheOid2(CONNAMENSP,
3386 PointerGetDatum(conversion_name),
3387 ObjectIdGetDatum(namespaceId));
3391 /* search for it in search path */
3392 recomputeNamespacePath();
3394 foreach(l, activeSearchPath)
3396 namespaceId = lfirst_oid(l);
3398 if (namespaceId == myTempNamespace)
3399 continue; /* do not look in temp namespace */
3401 conoid = GetSysCacheOid2(CONNAMENSP,
3402 PointerGetDatum(conversion_name),
3403 ObjectIdGetDatum(namespaceId));
3404 if (OidIsValid(conoid))
3409 /* Not found in path */
3410 if (!OidIsValid(conoid) && !missing_ok)
3412 (errcode(ERRCODE_UNDEFINED_OBJECT),
3413 errmsg("conversion \"%s\" does not exist",
3414 NameListToString(name))));
3419 * FindDefaultConversionProc - find default encoding conversion proc
3422 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3427 recomputeNamespacePath();
3429 foreach(l, activeSearchPath)
3431 Oid namespaceId = lfirst_oid(l);
3433 if (namespaceId == myTempNamespace)
3434 continue; /* do not look in temp namespace */
3436 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3437 if (OidIsValid(proc))
3441 /* Not found in path */
3446 * recomputeNamespacePath - recompute path derived variables if needed.
3449 recomputeNamespacePath(void)
3451 Oid roleid = GetUserId();
3459 MemoryContext oldcxt;
3461 /* Do nothing if an override search spec is active. */
3465 /* Do nothing if path is already valid. */
3466 if (baseSearchPathValid && namespaceUser == roleid)
3469 /* Need a modifiable copy of namespace_search_path string */
3470 rawname = pstrdup(namespace_search_path);
3472 /* Parse string into list of identifiers */
3473 if (!SplitIdentifierString(rawname, ',', &namelist))
3475 /* syntax error in name list */
3476 /* this should not happen if GUC checked check_search_path */
3477 elog(ERROR, "invalid list syntax");
3481 * Convert the list of names to a list of OIDs. If any names are not
3482 * recognizable or we don't have read access, just leave them out of the
3483 * list. (We can't raise an error, since the search_path setting has
3484 * already been accepted.) Don't make duplicate entries, either.
3487 temp_missing = false;
3488 foreach(l, namelist)
3490 char *curname = (char *) lfirst(l);
3493 if (strcmp(curname, "$user") == 0)
3495 /* $user --- substitute namespace matching user name, if any */
3498 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3499 if (HeapTupleIsValid(tuple))
3503 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3504 namespaceId = get_namespace_oid(rname, true);
3505 ReleaseSysCache(tuple);
3506 if (OidIsValid(namespaceId) &&
3507 !list_member_oid(oidlist, namespaceId) &&
3508 pg_namespace_aclcheck(namespaceId, roleid,
3509 ACL_USAGE) == ACLCHECK_OK &&
3510 InvokeNamespaceSearchHook(namespaceId, false))
3511 oidlist = lappend_oid(oidlist, namespaceId);
3514 else if (strcmp(curname, "pg_temp") == 0)
3516 /* pg_temp --- substitute temp namespace, if any */
3517 if (OidIsValid(myTempNamespace))
3519 if (!list_member_oid(oidlist, myTempNamespace) &&
3520 InvokeNamespaceSearchHook(myTempNamespace, false))
3521 oidlist = lappend_oid(oidlist, myTempNamespace);
3525 /* If it ought to be the creation namespace, set flag */
3527 temp_missing = true;
3532 /* normal namespace reference */
3533 namespaceId = get_namespace_oid(curname, true);
3534 if (OidIsValid(namespaceId) &&
3535 !list_member_oid(oidlist, namespaceId) &&
3536 pg_namespace_aclcheck(namespaceId, roleid,
3537 ACL_USAGE) == ACLCHECK_OK &&
3538 InvokeNamespaceSearchHook(namespaceId, false))
3539 oidlist = lappend_oid(oidlist, namespaceId);
3544 * Remember the first member of the explicit list. (Note: this is
3545 * nominally wrong if temp_missing, but we need it anyway to distinguish
3546 * explicit from implicit mention of pg_catalog.)
3549 firstNS = InvalidOid;
3551 firstNS = linitial_oid(oidlist);
3554 * Add any implicitly-searched namespaces to the list. Note these go on
3555 * the front, not the back; also notice that we do not check USAGE
3556 * permissions for these.
3558 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3559 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3561 if (OidIsValid(myTempNamespace) &&
3562 !list_member_oid(oidlist, myTempNamespace))
3563 oidlist = lcons_oid(myTempNamespace, oidlist);
3566 * Now that we've successfully built the new list of namespace OIDs, save
3567 * it in permanent storage.
3569 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3570 newpath = list_copy(oidlist);
3571 MemoryContextSwitchTo(oldcxt);
3573 /* Now safe to assign to state variables. */
3574 list_free(baseSearchPath);
3575 baseSearchPath = newpath;
3576 baseCreationNamespace = firstNS;
3577 baseTempCreationPending = temp_missing;
3579 /* Mark the path valid. */
3580 baseSearchPathValid = true;
3581 namespaceUser = roleid;
3583 /* And make it active. */
3584 activeSearchPath = baseSearchPath;
3585 activeCreationNamespace = baseCreationNamespace;
3586 activeTempCreationPending = baseTempCreationPending;
3590 list_free(namelist);
3595 * InitTempTableNamespace
3596 * Initialize temp table namespace on first use in a particular backend
3599 InitTempTableNamespace(void)
3601 char namespaceName[NAMEDATALEN];
3605 Assert(!OidIsValid(myTempNamespace));
3608 * First, do permission check to see if we are authorized to make temp
3609 * tables. We use a nonstandard error message here since "databasename:
3610 * permission denied" might be a tad cryptic.
3612 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3613 * that's necessary since current user ID could change during the session.
3614 * But there's no need to make the namespace in the first place until a
3615 * temp table creation request is made by someone with appropriate rights.
3617 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3618 ACL_CREATE_TEMP) != ACLCHECK_OK)
3620 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3621 errmsg("permission denied to create temporary tables in database \"%s\"",
3622 get_database_name(MyDatabaseId))));
3625 * Do not allow a Hot Standby slave session to make temp tables. Aside
3626 * from problems with modifying the system catalogs, there is a naming
3627 * conflict: pg_temp_N belongs to the session with BackendId N on the
3628 * master, not to a slave session with the same BackendId. We should not
3629 * be able to get here anyway due to XactReadOnly checks, but let's just
3630 * make real sure. Note that this also backstops various operations that
3631 * allow XactReadOnly transactions to modify temp tables; they'd need
3632 * RecoveryInProgress checks if not for this.
3634 if (RecoveryInProgress())
3636 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3637 errmsg("cannot create temporary tables during recovery")));
3639 /* Parallel workers can't create temporary tables, either. */
3640 if (IsParallelWorker())
3642 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3643 errmsg("cannot create temporary tables in parallel mode")));
3645 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3647 namespaceId = get_namespace_oid(namespaceName, true);
3648 if (!OidIsValid(namespaceId))
3651 * First use of this temp namespace in this database; create it. The
3652 * temp namespaces are always owned by the superuser. We leave their
3653 * permissions at default --- i.e., no access except to superuser ---
3654 * to ensure that unprivileged users can't peek at other backends'
3655 * temp tables. This works because the places that access the temp
3656 * namespace for my own backend skip permissions checks on it.
3658 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3660 /* Advance command counter to make namespace visible */
3661 CommandCounterIncrement();
3666 * If the namespace already exists, clean it out (in case the former
3667 * owner crashed without doing so).
3669 RemoveTempRelations(namespaceId);
3673 * If the corresponding toast-table namespace doesn't exist yet, create
3674 * it. (We assume there is no need to clean it out if it does exist, since
3675 * dropping a parent table should make its toast table go away.)
3677 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3680 toastspaceId = get_namespace_oid(namespaceName, true);
3681 if (!OidIsValid(toastspaceId))
3683 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3685 /* Advance command counter to make namespace visible */
3686 CommandCounterIncrement();
3690 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3691 * so all our work could be undone by transaction rollback. Set flag for
3692 * AtEOXact_Namespace to know what to do.
3694 myTempNamespace = namespaceId;
3695 myTempToastNamespace = toastspaceId;
3697 /* It should not be done already. */
3698 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3699 myTempNamespaceSubID = GetCurrentSubTransactionId();
3701 baseSearchPathValid = false; /* need to rebuild list */
3705 * End-of-transaction cleanup for namespaces.
3708 AtEOXact_Namespace(bool isCommit, bool parallel)
3711 * If we abort the transaction in which a temp namespace was selected,
3712 * we'll have to do any creation or cleanout work over again. So, just
3713 * forget the namespace entirely until next time. On the other hand, if
3714 * we commit then register an exit callback to clean out the temp tables
3715 * at backend shutdown. (We only want to register the callback once per
3716 * session, so this is a good place to do it.)
3718 if (myTempNamespaceSubID != InvalidSubTransactionId && !parallel)
3721 before_shmem_exit(RemoveTempRelationsCallback, 0);
3724 myTempNamespace = InvalidOid;
3725 myTempToastNamespace = InvalidOid;
3726 baseSearchPathValid = false; /* need to rebuild list */
3728 myTempNamespaceSubID = InvalidSubTransactionId;
3732 * Clean up if someone failed to do PopOverrideSearchPath
3737 elog(WARNING, "leaked override search path");
3738 while (overrideStack)
3740 OverrideStackEntry *entry;
3742 entry = (OverrideStackEntry *) linitial(overrideStack);
3743 overrideStack = list_delete_first(overrideStack);
3744 list_free(entry->searchPath);
3747 /* If not baseSearchPathValid, this is useless but harmless */
3748 activeSearchPath = baseSearchPath;
3749 activeCreationNamespace = baseCreationNamespace;
3750 activeTempCreationPending = baseTempCreationPending;
3755 * AtEOSubXact_Namespace
3757 * At subtransaction commit, propagate the temp-namespace-creation
3758 * flag to the parent subtransaction.
3760 * At subtransaction abort, forget the flag if we set it up.
3763 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3764 SubTransactionId parentSubid)
3766 OverrideStackEntry *entry;
3768 if (myTempNamespaceSubID == mySubid)
3771 myTempNamespaceSubID = parentSubid;
3774 myTempNamespaceSubID = InvalidSubTransactionId;
3775 /* TEMP namespace creation failed, so reset state */
3776 myTempNamespace = InvalidOid;
3777 myTempToastNamespace = InvalidOid;
3778 baseSearchPathValid = false; /* need to rebuild list */
3783 * Clean up if someone failed to do PopOverrideSearchPath
3785 while (overrideStack)
3787 entry = (OverrideStackEntry *) linitial(overrideStack);
3788 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3791 elog(WARNING, "leaked override search path");
3792 overrideStack = list_delete_first(overrideStack);
3793 list_free(entry->searchPath);
3797 /* Activate the next level down. */
3800 entry = (OverrideStackEntry *) linitial(overrideStack);
3801 activeSearchPath = entry->searchPath;
3802 activeCreationNamespace = entry->creationNamespace;
3803 activeTempCreationPending = false; /* XXX is this OK? */
3807 /* If not baseSearchPathValid, this is useless but harmless */
3808 activeSearchPath = baseSearchPath;
3809 activeCreationNamespace = baseCreationNamespace;
3810 activeTempCreationPending = baseTempCreationPending;
3815 * Remove all relations in the specified temp namespace.
3817 * This is called at backend shutdown (if we made any temp relations).
3818 * It is also called when we begin using a pre-existing temp namespace,
3819 * in order to clean out any relations that might have been created by
3820 * a crashed backend.
3823 RemoveTempRelations(Oid tempNamespaceId)
3825 ObjectAddress object;
3828 * We want to get rid of everything in the target namespace, but not the
3829 * namespace itself (deleting it only to recreate it later would be a
3830 * waste of cycles). We do this by finding everything that has a
3831 * dependency on the namespace.
3833 object.classId = NamespaceRelationId;
3834 object.objectId = tempNamespaceId;
3835 object.objectSubId = 0;
3837 deleteWhatDependsOn(&object, false);
3841 * Callback to remove temp relations at backend exit.
3844 RemoveTempRelationsCallback(int code, Datum arg)
3846 if (OidIsValid(myTempNamespace)) /* should always be true */
3848 /* Need to ensure we have a usable transaction. */
3849 AbortOutOfAnyTransaction();
3850 StartTransactionCommand();
3852 RemoveTempRelations(myTempNamespace);
3854 CommitTransactionCommand();
3859 * Remove all temp tables from the temporary namespace.
3862 ResetTempTableNamespace(void)
3864 if (OidIsValid(myTempNamespace))
3865 RemoveTempRelations(myTempNamespace);
3870 * Routines for handling the GUC variable 'search_path'.
3873 /* check_hook: validate new search_path value */
3875 check_search_path(char **newval, void **extra, GucSource source)
3880 /* Need a modifiable copy of string */
3881 rawname = pstrdup(*newval);
3883 /* Parse string into list of identifiers */
3884 if (!SplitIdentifierString(rawname, ',', &namelist))
3886 /* syntax error in name list */
3887 GUC_check_errdetail("List syntax is invalid.");
3889 list_free(namelist);
3894 * We used to try to check that the named schemas exist, but there are
3895 * many valid use-cases for having search_path settings that include
3896 * schemas that don't exist; and often, we are not inside a transaction
3897 * here and so can't consult the system catalogs anyway. So now, the only
3898 * requirement is syntactic validity of the identifier list.
3902 list_free(namelist);
3907 /* assign_hook: do extra actions as needed */
3909 assign_search_path(const char *newval, void *extra)
3912 * We mark the path as needing recomputation, but don't do anything until
3913 * it's needed. This avoids trying to do database access during GUC
3914 * initialization, or outside a transaction.
3916 baseSearchPathValid = false;
3920 * InitializeSearchPath: initialize module during InitPostgres.
3922 * This is called after we are up enough to be able to do catalog lookups.
3925 InitializeSearchPath(void)
3927 if (IsBootstrapProcessingMode())
3930 * In bootstrap mode, the search path must be 'pg_catalog' so that
3931 * tables are created in the proper namespace; ignore the GUC setting.
3933 MemoryContext oldcxt;
3935 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3936 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3937 MemoryContextSwitchTo(oldcxt);
3938 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3939 baseTempCreationPending = false;
3940 baseSearchPathValid = true;
3941 namespaceUser = GetUserId();
3942 activeSearchPath = baseSearchPath;
3943 activeCreationNamespace = baseCreationNamespace;
3944 activeTempCreationPending = baseTempCreationPending;
3949 * In normal mode, arrange for a callback on any syscache invalidation
3950 * of pg_namespace rows.
3952 CacheRegisterSyscacheCallback(NAMESPACEOID,
3955 /* Force search path to be recomputed on next use */
3956 baseSearchPathValid = false;
3962 * Syscache inval callback function
3965 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3967 /* Force search path to be recomputed on next use */
3968 baseSearchPathValid = false;
3972 * Fetch the active search path. The return value is a palloc'ed list
3973 * of OIDs; the caller is responsible for freeing this storage as
3976 * The returned list includes the implicitly-prepended namespaces only if
3977 * includeImplicit is true.
3979 * Note: calling this may result in a CommandCounterIncrement operation,
3980 * if we have to create or clean out the temp namespace.
3983 fetch_search_path(bool includeImplicit)
3987 recomputeNamespacePath();
3990 * If the temp namespace should be first, force it to exist. This is so
3991 * that callers can trust the result to reflect the actual default
3992 * creation namespace. It's a bit bogus to do this here, since
3993 * current_schema() is supposedly a stable function without side-effects,
3994 * but the alternatives seem worse.
3996 if (activeTempCreationPending)
3998 InitTempTableNamespace();
3999 recomputeNamespacePath();
4002 result = list_copy(activeSearchPath);
4003 if (!includeImplicit)
4005 while (result && linitial_oid(result) != activeCreationNamespace)
4006 result = list_delete_first(result);
4013 * Fetch the active search path into a caller-allocated array of OIDs.
4014 * Returns the number of path entries. (If this is more than sarray_len,
4015 * then the data didn't fit and is not all stored.)
4017 * The returned list always includes the implicitly-prepended namespaces,
4018 * but never includes the temp namespace. (This is suitable for existing
4019 * users, which would want to ignore the temp namespace anyway.) This
4020 * definition allows us to not worry about initializing the temp namespace.
4023 fetch_search_path_array(Oid *sarray, int sarray_len)
4028 recomputeNamespacePath();
4030 foreach(l, activeSearchPath)
4032 Oid namespaceId = lfirst_oid(l);
4034 if (namespaceId == myTempNamespace)
4035 continue; /* do not include temp namespace */
4037 if (count < sarray_len)
4038 sarray[count] = namespaceId;
4047 * Export the FooIsVisible functions as SQL-callable functions.
4049 * Note: as of Postgres 8.4, these will silently return NULL if called on
4050 * a nonexistent object OID, rather than failing. This is to avoid race
4051 * condition errors when a query that's scanning a catalog using an MVCC
4052 * snapshot uses one of these functions. The underlying IsVisible functions
4053 * always use an up-to-date snapshot and so might see the object as already
4054 * gone when it's still visible to the transaction snapshot. (There is no race
4055 * condition in the current coding because we don't accept sinval messages
4056 * between the SearchSysCacheExists test and the subsequent lookup.)
4060 pg_table_is_visible(PG_FUNCTION_ARGS)
4062 Oid oid = PG_GETARG_OID(0);
4064 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
4067 PG_RETURN_BOOL(RelationIsVisible(oid));
4071 pg_type_is_visible(PG_FUNCTION_ARGS)
4073 Oid oid = PG_GETARG_OID(0);
4075 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
4078 PG_RETURN_BOOL(TypeIsVisible(oid));
4082 pg_function_is_visible(PG_FUNCTION_ARGS)
4084 Oid oid = PG_GETARG_OID(0);
4086 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
4089 PG_RETURN_BOOL(FunctionIsVisible(oid));
4093 pg_operator_is_visible(PG_FUNCTION_ARGS)
4095 Oid oid = PG_GETARG_OID(0);
4097 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4100 PG_RETURN_BOOL(OperatorIsVisible(oid));
4104 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4106 Oid oid = PG_GETARG_OID(0);
4108 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4111 PG_RETURN_BOOL(OpclassIsVisible(oid));
4115 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4117 Oid oid = PG_GETARG_OID(0);
4119 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4122 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4126 pg_collation_is_visible(PG_FUNCTION_ARGS)
4128 Oid oid = PG_GETARG_OID(0);
4130 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4133 PG_RETURN_BOOL(CollationIsVisible(oid));
4137 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4139 Oid oid = PG_GETARG_OID(0);
4141 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4144 PG_RETURN_BOOL(ConversionIsVisible(oid));
4148 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4150 Oid oid = PG_GETARG_OID(0);
4152 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4155 PG_RETURN_BOOL(TSParserIsVisible(oid));
4159 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4161 Oid oid = PG_GETARG_OID(0);
4163 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4166 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4170 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4172 Oid oid = PG_GETARG_OID(0);
4174 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4177 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4181 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4183 Oid oid = PG_GETARG_OID(0);
4185 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4188 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4192 pg_my_temp_schema(PG_FUNCTION_ARGS)
4194 PG_RETURN_OID(myTempNamespace);
4198 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4200 Oid oid = PG_GETARG_OID(0);
4202 PG_RETURN_BOOL(isOtherTempNamespace(oid));