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-2014, 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/xact.h"
24 #include "access/xlog.h"
25 #include "catalog/dependency.h"
26 #include "catalog/objectaccess.h"
27 #include "catalog/pg_authid.h"
28 #include "catalog/pg_collation.h"
29 #include "catalog/pg_conversion.h"
30 #include "catalog/pg_conversion_fn.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_operator.h"
34 #include "catalog/pg_opfamily.h"
35 #include "catalog/pg_proc.h"
36 #include "catalog/pg_ts_config.h"
37 #include "catalog/pg_ts_dict.h"
38 #include "catalog/pg_ts_parser.h"
39 #include "catalog/pg_ts_template.h"
40 #include "catalog/pg_type.h"
41 #include "commands/dbcommands.h"
43 #include "mb/pg_wchar.h"
44 #include "miscadmin.h"
45 #include "nodes/makefuncs.h"
46 #include "parser/parse_func.h"
47 #include "storage/ipc.h"
48 #include "storage/lmgr.h"
49 #include "storage/sinval.h"
50 #include "utils/acl.h"
51 #include "utils/builtins.h"
52 #include "utils/catcache.h"
53 #include "utils/guc.h"
54 #include "utils/inval.h"
55 #include "utils/lsyscache.h"
56 #include "utils/memutils.h"
57 #include "utils/syscache.h"
61 * The namespace search path is a possibly-empty list of namespace OIDs.
62 * In addition to the explicit list, implicitly-searched namespaces
65 * 1. If a TEMP table namespace has been initialized in this session, it
66 * is implicitly searched first. (The only time this doesn't happen is
67 * when we are obeying an override search path spec that says not to use the
68 * temp namespace, or the temp namespace is included in the explicit list.)
70 * 2. The system catalog namespace is always searched. If the system
71 * namespace is present in the explicit path then it will be searched in
72 * the specified order; otherwise it will be searched after TEMP tables and
73 * *before* the explicit list. (It might seem that the system namespace
74 * should be implicitly last, but this behavior appears to be required by
75 * SQL99. Also, this provides a way to search the system namespace first
76 * without thereby making it the default creation target namespace.)
78 * For security reasons, searches using the search path will ignore the temp
79 * namespace when searching for any object type other than relations and
80 * types. (We must allow types since temp tables have rowtypes.)
82 * The default creation target namespace is always the first element of the
83 * explicit list. If the explicit list is empty, there is no default target.
85 * The textual specification of search_path can include "$user" to refer to
86 * the namespace named the same as the current user, if any. (This is just
87 * ignored if there is no such namespace.) Also, it can include "pg_temp"
88 * to refer to the current backend's temp namespace. This is usually also
89 * ignorable if the temp namespace hasn't been set up, but there's a special
90 * case: if "pg_temp" appears first then it should be the default creation
91 * target. We kluge this case a little bit so that the temp namespace isn't
92 * set up until the first attempt to create something in it. (The reason for
93 * klugery is that we can't create the temp namespace outside a transaction,
94 * but initial GUC processing of search_path happens outside a transaction.)
95 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
96 * but is not reflected in activeCreationNamespace because the namespace isn't
99 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
100 * the system namespace is the only one searched or inserted into.
101 * initdb is also careful to set search_path to "pg_catalog" for its
102 * post-bootstrap standalone backend runs. Otherwise the default search
103 * path is determined by GUC. The factory default path contains the PUBLIC
104 * namespace (if it exists), preceded by the user's personal namespace
107 * We support a stack of "override" search path settings for use within
108 * specific sections of backend code. namespace_search_path is ignored
109 * whenever the override stack is nonempty. activeSearchPath is always
110 * the actually active path; it points either to the search list of the
111 * topmost stack entry, or to baseSearchPath which is the list derived
112 * from namespace_search_path.
114 * If baseSearchPathValid is false, then baseSearchPath (and other
115 * derived variables) need to be recomputed from namespace_search_path.
116 * We mark it invalid upon an assignment to namespace_search_path or receipt
117 * of a syscache invalidation event for pg_namespace. The recomputation
118 * is done during the next non-overridden lookup attempt. Note that an
119 * override spec is never subject to recomputation.
121 * Any namespaces mentioned in namespace_search_path that are not readable
122 * by the current user ID are simply left out of baseSearchPath; so
123 * we have to be willing to recompute the path when current userid changes.
124 * namespaceUser is the userid the path has been computed for.
126 * Note: all data pointed to by these List variables is in TopMemoryContext.
129 /* These variables define the actually active state: */
131 static List *activeSearchPath = NIL;
133 /* default place to create stuff; if InvalidOid, no default */
134 static Oid activeCreationNamespace = InvalidOid;
136 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
137 static bool activeTempCreationPending = false;
139 /* These variables are the values last derived from namespace_search_path: */
141 static List *baseSearchPath = NIL;
143 static Oid baseCreationNamespace = InvalidOid;
145 static bool baseTempCreationPending = false;
147 static Oid namespaceUser = InvalidOid;
149 /* The above four values are valid only if baseSearchPathValid */
150 static bool baseSearchPathValid = true;
152 /* Override requests are remembered in a stack of OverrideStackEntry structs */
156 List *searchPath; /* the desired search path */
157 Oid creationNamespace; /* the desired creation namespace */
158 int nestLevel; /* subtransaction nesting level */
159 } OverrideStackEntry;
161 static List *overrideStack = NIL;
164 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
165 * in a particular backend session (this happens when a CREATE TEMP TABLE
166 * command is first executed). Thereafter it's the OID of the temp namespace.
168 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
169 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
171 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
172 * current subtransaction. The flag propagates up the subtransaction tree,
173 * so the main transaction will correctly recognize the flag if all
174 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
175 * we either haven't made the TEMP namespace yet, or have successfully
176 * committed its creation, depending on whether myTempNamespace is valid.
178 static Oid myTempNamespace = InvalidOid;
180 static Oid myTempToastNamespace = InvalidOid;
182 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
185 * This is the user's textual search path specification --- it's the value
186 * of the GUC variable 'search_path'.
188 char *namespace_search_path = NULL;
191 /* Local functions */
192 static void recomputeNamespacePath(void);
193 static void InitTempTableNamespace(void);
194 static void RemoveTempRelations(Oid tempNamespaceId);
195 static void RemoveTempRelationsCallback(int code, Datum arg);
196 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
197 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
200 /* These don't really need to appear in any header file */
201 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
210 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
211 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
212 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
213 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
214 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
219 * Given a RangeVar describing an existing relation,
220 * select the proper namespace and look up the relation OID.
222 * If the schema or relation is not found, return InvalidOid if missing_ok
223 * = true, otherwise raise an error.
225 * If nowait = true, throw an error if we'd have to wait for a lock.
227 * Callback allows caller to check permissions or acquire additional locks
228 * prior to grabbing the relation lock.
231 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
232 bool missing_ok, bool nowait,
233 RangeVarGetRelidCallback callback, void *callback_arg)
237 Oid oldRelId = InvalidOid;
241 * We check the catalog name and then ignore it.
243 if (relation->catalogname)
245 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
247 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
248 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
249 relation->catalogname, relation->schemaname,
250 relation->relname)));
254 * DDL operations can change the results of a name lookup. Since all such
255 * operations will generate invalidation messages, we keep track of
256 * whether any such messages show up while we're performing the operation,
257 * and retry until either (1) no more invalidation messages show up or (2)
258 * the answer doesn't change.
260 * But if lockmode = NoLock, then we assume that either the caller is OK
261 * with the answer changing under them, or that they already hold some
262 * appropriate lock, and therefore return the first answer we get without
263 * checking for invalidation messages. Also, if the requested lock is
264 * already held, LockRelationOid will not AcceptInvalidationMessages,
265 * so we may fail to notice a change. We could protect against that case
266 * by calling AcceptInvalidationMessages() before beginning this loop, but
267 * that would add a significant amount overhead, so for now we don't.
272 * Remember this value, so that, after looking up the relation name
273 * and locking its OID, we can check whether any invalidation messages
274 * have been processed that might require a do-over.
276 inval_count = SharedInvalidMessageCounter;
279 * Some non-default relpersistence value may have been specified. The
280 * parser never generates such a RangeVar in simple DML, but it can
281 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
282 * KEY)". Such a command will generate an added CREATE INDEX
283 * operation, which must be careful to find the temp table, even when
284 * pg_temp is not first in the search path.
286 if (relation->relpersistence == RELPERSISTENCE_TEMP)
288 if (!OidIsValid(myTempNamespace))
289 relId = InvalidOid; /* this probably can't happen? */
292 if (relation->schemaname)
296 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
299 * For missing_ok, allow a non-existant schema name to
302 if (namespaceId != myTempNamespace)
304 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
305 errmsg("temporary tables cannot specify a schema name")));
308 relId = get_relname_relid(relation->relname, myTempNamespace);
311 else if (relation->schemaname)
315 /* use exact schema given */
316 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
317 if (missing_ok && !OidIsValid(namespaceId))
320 relId = get_relname_relid(relation->relname, namespaceId);
324 /* search the namespace path */
325 relId = RelnameGetRelid(relation->relname);
329 * Invoke caller-supplied callback, if any.
331 * This callback is a good place to check permissions: we haven't
332 * taken the table lock yet (and it's really best to check permissions
333 * before locking anything!), but we've gotten far enough to know what
334 * OID we think we should lock. Of course, concurrent DDL might
335 * change things while we're waiting for the lock, but in that case
336 * the callback will be invoked again for the new OID.
339 callback(relation, relId, oldRelId, callback_arg);
342 * If no lock requested, we assume the caller knows what they're
343 * doing. They should have already acquired a heavyweight lock on
344 * this relation earlier in the processing of this same statement, so
345 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
346 * that might pull the rug out from under them.
348 if (lockmode == NoLock)
352 * If, upon retry, we get back the same OID we did last time, then the
353 * invalidation messages we processed did not change the final answer.
356 * If we got a different OID, we've locked the relation that used to
357 * have this name rather than the one that does now. So release the
362 if (relId == oldRelId)
364 if (OidIsValid(oldRelId))
365 UnlockRelationOid(oldRelId, lockmode);
369 * Lock relation. This will also accept any pending invalidation
370 * messages. If we got back InvalidOid, indicating not found, then
371 * there's nothing to lock, but we accept invalidation messages
372 * anyway, to flush any negative catcache entries that may be
375 if (!OidIsValid(relId))
376 AcceptInvalidationMessages();
378 LockRelationOid(relId, lockmode);
379 else if (!ConditionalLockRelationOid(relId, lockmode))
381 if (relation->schemaname)
383 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
384 errmsg("could not obtain lock on relation \"%s.%s\"",
385 relation->schemaname, relation->relname)));
388 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
389 errmsg("could not obtain lock on relation \"%s\"",
390 relation->relname)));
394 * If no invalidation message were processed, we're done!
396 if (inval_count == SharedInvalidMessageCounter)
400 * Something may have changed. Let's repeat the name lookup, to make
401 * sure this name still references the same relation it did
408 if (!OidIsValid(relId) && !missing_ok)
410 if (relation->schemaname)
412 (errcode(ERRCODE_UNDEFINED_TABLE),
413 errmsg("relation \"%s.%s\" does not exist",
414 relation->schemaname, relation->relname)));
417 (errcode(ERRCODE_UNDEFINED_TABLE),
418 errmsg("relation \"%s\" does not exist",
419 relation->relname)));
425 * RangeVarGetCreationNamespace
426 * Given a RangeVar describing a to-be-created relation,
427 * choose which namespace to create it in.
429 * Note: calling this may result in a CommandCounterIncrement operation.
430 * That will happen on the first request for a temp table in any particular
431 * backend run; we will need to either create or clean out the temp schema.
434 RangeVarGetCreationNamespace(const RangeVar *newRelation)
439 * We check the catalog name and then ignore it.
441 if (newRelation->catalogname)
443 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
446 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
447 newRelation->catalogname, newRelation->schemaname,
448 newRelation->relname)));
451 if (newRelation->schemaname)
453 /* check for pg_temp alias */
454 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
456 /* Initialize temp namespace if first time through */
457 if (!OidIsValid(myTempNamespace))
458 InitTempTableNamespace();
459 return myTempNamespace;
461 /* use exact schema given */
462 namespaceId = get_namespace_oid(newRelation->schemaname, false);
463 /* we do not check for USAGE rights here! */
465 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
467 /* Initialize temp namespace if first time through */
468 if (!OidIsValid(myTempNamespace))
469 InitTempTableNamespace();
470 return myTempNamespace;
474 /* use the default creation namespace */
475 recomputeNamespacePath();
476 if (activeTempCreationPending)
478 /* Need to initialize temp namespace */
479 InitTempTableNamespace();
480 return myTempNamespace;
482 namespaceId = activeCreationNamespace;
483 if (!OidIsValid(namespaceId))
485 (errcode(ERRCODE_UNDEFINED_SCHEMA),
486 errmsg("no schema has been selected to create in")));
489 /* Note: callers will check for CREATE rights when appropriate */
495 * RangeVarGetAndCheckCreationNamespace
497 * This function returns the OID of the namespace in which a new relation
498 * with a given name should be created. If the user does not have CREATE
499 * permission on the target namespace, this function will instead signal
502 * If non-NULL, *existing_oid is set to the OID of any existing relation with
503 * the same name which already exists in that namespace, or to InvalidOid if
504 * no such relation exists.
506 * If lockmode != NoLock, the specified lock mode is acquired on the existing
507 * relation, if any, provided that the current user owns the target relation.
508 * However, if lockmode != NoLock and the user does not own the target
509 * relation, we throw an ERROR, as we must not try to lock relations the
510 * user does not have permissions on.
512 * As a side effect, this function acquires AccessShareLock on the target
513 * namespace. Without this, the namespace could be dropped before our
514 * transaction commits, leaving behind relations with relnamespace pointing
515 * to a no-longer-exstant namespace.
517 * As a further side-effect, if the select namespace is a temporary namespace,
518 * we mark the RangeVar as RELPERSISTENCE_TEMP.
521 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
523 Oid *existing_relation_id)
527 Oid oldrelid = InvalidOid;
529 Oid oldnspid = InvalidOid;
533 * We check the catalog name and then ignore it.
535 if (relation->catalogname)
537 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
539 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
540 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
541 relation->catalogname, relation->schemaname,
542 relation->relname)));
546 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
547 * operations by tracking whether any invalidation messages are processed
548 * while we're doing the name lookups and acquiring locks. See comments
549 * in that function for a more detailed explanation of this logic.
555 inval_count = SharedInvalidMessageCounter;
557 /* Look up creation namespace and check for existing relation. */
558 nspid = RangeVarGetCreationNamespace(relation);
559 Assert(OidIsValid(nspid));
560 if (existing_relation_id != NULL)
561 relid = get_relname_relid(relation->relname, nspid);
566 * In bootstrap processing mode, we don't bother with permissions or
567 * locking. Permissions might not be working yet, and locking is
570 if (IsBootstrapProcessingMode())
573 /* Check namespace permissions. */
574 aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
575 if (aclresult != ACLCHECK_OK)
576 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
577 get_namespace_name(nspid));
581 /* If nothing changed, we're done. */
582 if (relid == oldrelid && nspid == oldnspid)
584 /* If creation namespace has changed, give up old lock. */
585 if (nspid != oldnspid)
586 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
588 /* If name points to something different, give up old lock. */
589 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
590 UnlockRelationOid(oldrelid, lockmode);
593 /* Lock namespace. */
594 if (nspid != oldnspid)
595 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
597 /* Lock relation, if required if and we have permission. */
598 if (lockmode != NoLock && OidIsValid(relid))
600 if (!pg_class_ownercheck(relid, GetUserId()))
601 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
603 if (relid != oldrelid)
604 LockRelationOid(relid, lockmode);
607 /* If no invalidation message were processed, we're done! */
608 if (inval_count == SharedInvalidMessageCounter)
611 /* Something may have changed, so recheck our work. */
617 RangeVarAdjustRelationPersistence(relation, nspid);
618 if (existing_relation_id != NULL)
619 *existing_relation_id = relid;
624 * Adjust the relpersistence for an about-to-be-created relation based on the
625 * creation namespace, and throw an error for invalid combinations.
628 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
630 switch (newRelation->relpersistence)
632 case RELPERSISTENCE_TEMP:
633 if (!isTempOrTempToastNamespace(nspid))
635 if (isAnyTempNamespace(nspid))
637 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
638 errmsg("cannot create relations in temporary schemas of other sessions")));
641 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
642 errmsg("cannot create temporary relation in non-temporary schema")));
645 case RELPERSISTENCE_PERMANENT:
646 if (isTempOrTempToastNamespace(nspid))
647 newRelation->relpersistence = RELPERSISTENCE_TEMP;
648 else if (isAnyTempNamespace(nspid))
650 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
651 errmsg("cannot create relations in temporary schemas of other sessions")));
654 if (isAnyTempNamespace(nspid))
656 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
657 errmsg("only temporary relations may be created in temporary schemas")));
663 * Try to resolve an unqualified relation name.
664 * Returns OID if relation found in search path, else InvalidOid.
667 RelnameGetRelid(const char *relname)
672 recomputeNamespacePath();
674 foreach(l, activeSearchPath)
676 Oid namespaceId = lfirst_oid(l);
678 relid = get_relname_relid(relname, namespaceId);
679 if (OidIsValid(relid))
683 /* Not found in path */
690 * Determine whether a relation (identified by OID) is visible in the
691 * current search path. Visible means "would be found by searching
692 * for the unqualified relation name".
695 RelationIsVisible(Oid relid)
698 Form_pg_class relform;
702 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
703 if (!HeapTupleIsValid(reltup))
704 elog(ERROR, "cache lookup failed for relation %u", relid);
705 relform = (Form_pg_class) GETSTRUCT(reltup);
707 recomputeNamespacePath();
710 * Quick check: if it ain't in the path at all, it ain't visible. Items in
711 * the system namespace are surely in the path and so we needn't even do
712 * list_member_oid() for them.
714 relnamespace = relform->relnamespace;
715 if (relnamespace != PG_CATALOG_NAMESPACE &&
716 !list_member_oid(activeSearchPath, relnamespace))
721 * If it is in the path, it might still not be visible; it could be
722 * hidden by another relation of the same name earlier in the path. So
723 * we must do a slow check for conflicting relations.
725 char *relname = NameStr(relform->relname);
729 foreach(l, activeSearchPath)
731 Oid namespaceId = lfirst_oid(l);
733 if (namespaceId == relnamespace)
735 /* Found it first in path */
739 if (OidIsValid(get_relname_relid(relname, namespaceId)))
741 /* Found something else first in path */
747 ReleaseSysCache(reltup);
755 * Try to resolve an unqualified datatype name.
756 * Returns OID if type found in search path, else InvalidOid.
758 * This is essentially the same as RelnameGetRelid.
761 TypenameGetTypid(const char *typname)
766 recomputeNamespacePath();
768 foreach(l, activeSearchPath)
770 Oid namespaceId = lfirst_oid(l);
772 typid = GetSysCacheOid2(TYPENAMENSP,
773 PointerGetDatum(typname),
774 ObjectIdGetDatum(namespaceId));
775 if (OidIsValid(typid))
779 /* Not found in path */
785 * Determine whether a type (identified by OID) is visible in the
786 * current search path. Visible means "would be found by searching
787 * for the unqualified type name".
790 TypeIsVisible(Oid typid)
793 Form_pg_type typform;
797 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
798 if (!HeapTupleIsValid(typtup))
799 elog(ERROR, "cache lookup failed for type %u", typid);
800 typform = (Form_pg_type) GETSTRUCT(typtup);
802 recomputeNamespacePath();
805 * Quick check: if it ain't in the path at all, it ain't visible. Items in
806 * the system namespace are surely in the path and so we needn't even do
807 * list_member_oid() for them.
809 typnamespace = typform->typnamespace;
810 if (typnamespace != PG_CATALOG_NAMESPACE &&
811 !list_member_oid(activeSearchPath, typnamespace))
816 * If it is in the path, it might still not be visible; it could be
817 * hidden by another type of the same name earlier in the path. So we
818 * must do a slow check for conflicting types.
820 char *typname = NameStr(typform->typname);
824 foreach(l, activeSearchPath)
826 Oid namespaceId = lfirst_oid(l);
828 if (namespaceId == typnamespace)
830 /* Found it first in path */
834 if (SearchSysCacheExists2(TYPENAMENSP,
835 PointerGetDatum(typname),
836 ObjectIdGetDatum(namespaceId)))
838 /* Found something else first in path */
844 ReleaseSysCache(typtup);
851 * FuncnameGetCandidates
852 * Given a possibly-qualified function name and argument count,
853 * retrieve a list of the possible matches.
855 * If nargs is -1, we return all functions matching the given name,
856 * regardless of argument count. (argnames must be NIL, and expand_variadic
857 * and expand_defaults must be false, in this case.)
859 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
860 * and only functions having all the listed argument names will be returned.
861 * (We assume that length(argnames) <= nargs and all the passed-in names are
862 * distinct.) The returned structs will include an argnumbers array showing
863 * the actual argument index for each logical argument position.
865 * If expand_variadic is true, then variadic functions having the same number
866 * or fewer arguments will be retrieved, with the variadic argument and any
867 * additional argument positions filled with the variadic element type.
868 * nvargs in the returned struct is set to the number of such arguments.
869 * If expand_variadic is false, variadic arguments are not treated specially,
870 * and the returned nvargs will always be zero.
872 * If expand_defaults is true, functions that could match after insertion of
873 * default argument values will also be retrieved. In this case the returned
874 * structs could have nargs > passed-in nargs, and ndargs is set to the number
875 * of additional args (which can be retrieved from the function's
876 * proargdefaults entry).
878 * It is not possible for nvargs and ndargs to both be nonzero in the same
879 * list entry, since default insertion allows matches to functions with more
880 * than nargs arguments while the variadic transformation requires the same
883 * When argnames isn't NIL, the returned args[] type arrays are not ordered
884 * according to the functions' declarations, but rather according to the call:
885 * first any positional arguments, then the named arguments, then defaulted
886 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
887 * array can be used to map this back to the catalog information.
888 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
890 * We search a single namespace if the function name is qualified, else
891 * all namespaces in the search path. In the multiple-namespace case,
892 * we arrange for entries in earlier namespaces to mask identical entries in
895 * When expanding variadics, we arrange for non-variadic functions to mask
896 * variadic ones if the expanded argument list is the same. It is still
897 * possible for there to be conflicts between different variadic functions,
900 * It is guaranteed that the return list will never contain multiple entries
901 * with identical argument lists. When expand_defaults is true, the entries
902 * could have more than nargs positions, but we still guarantee that they are
903 * distinct in the first nargs positions. However, if argnames isn't NIL or
904 * either expand_variadic or expand_defaults is true, there might be multiple
905 * candidate functions that expand to identical argument lists. Rather than
906 * throw error here, we report such situations by returning a single entry
907 * with oid = 0 that represents a set of such conflicting candidates.
908 * The caller might end up discarding such an entry anyway, but if it selects
909 * such an entry it should react as though the call were ambiguous.
911 * If missing_ok is true, an empty list (NULL) is returned if the name was
912 * schema- qualified with a schema that does not exist. Likewise if no
913 * candidate is found for other reasons.
916 FuncnameGetCandidates(List *names, int nargs, List *argnames,
917 bool expand_variadic, bool expand_defaults,
920 FuncCandidateList resultList = NULL;
921 bool any_special = false;
928 /* check for caller error */
929 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
931 /* deconstruct the name list */
932 DeconstructQualifiedName(names, &schemaname, &funcname);
936 /* use exact schema given */
937 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
938 if (!OidIsValid(namespaceId))
943 /* flag to indicate we need namespace search */
944 namespaceId = InvalidOid;
945 recomputeNamespacePath();
948 /* Search syscache by name only */
949 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
951 for (i = 0; i < catlist->n_members; i++)
953 HeapTuple proctup = &catlist->members[i]->tuple;
954 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
955 int pronargs = procform->pronargs;
961 int *argnumbers = NULL;
962 FuncCandidateList newResult;
964 if (OidIsValid(namespaceId))
966 /* Consider only procs in specified namespace */
967 if (procform->pronamespace != namespaceId)
973 * Consider only procs that are in the search path and are not in
974 * the temp namespace.
978 foreach(nsp, activeSearchPath)
980 if (procform->pronamespace == lfirst_oid(nsp) &&
981 procform->pronamespace != myTempNamespace)
986 continue; /* proc is not in search path */
992 * Call uses named or mixed notation
994 * Named or mixed notation can match a variadic function only if
995 * expand_variadic is off; otherwise there is no way to match the
996 * presumed-nameless parameters expanded from the variadic array.
998 if (OidIsValid(procform->provariadic) && expand_variadic)
1000 va_elem_type = InvalidOid;
1004 * Check argument count.
1006 Assert(nargs >= 0); /* -1 not supported with argnames */
1008 if (pronargs > nargs && expand_defaults)
1010 /* Ignore if not enough default expressions */
1011 if (nargs + procform->pronargdefaults < pronargs)
1013 use_defaults = true;
1016 use_defaults = false;
1018 /* Ignore if it doesn't match requested argument count */
1019 if (pronargs != nargs && !use_defaults)
1022 /* Check for argument name match, generate positional mapping */
1023 if (!MatchNamedCall(proctup, nargs, argnames,
1027 /* Named argument matching is always "special" */
1033 * Call uses positional notation
1035 * Check if function is variadic, and get variadic element type if
1036 * so. If expand_variadic is false, we should just ignore
1039 if (pronargs <= nargs && expand_variadic)
1041 va_elem_type = procform->provariadic;
1042 variadic = OidIsValid(va_elem_type);
1043 any_special |= variadic;
1047 va_elem_type = InvalidOid;
1052 * Check if function can match by using parameter defaults.
1054 if (pronargs > nargs && expand_defaults)
1056 /* Ignore if not enough default expressions */
1057 if (nargs + procform->pronargdefaults < pronargs)
1059 use_defaults = true;
1063 use_defaults = false;
1065 /* Ignore if it doesn't match requested argument count */
1066 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1071 * We must compute the effective argument list so that we can easily
1072 * compare it to earlier results. We waste a palloc cycle if it gets
1073 * masked by an earlier result, but really that's a pretty infrequent
1074 * case so it's not worth worrying about.
1076 effective_nargs = Max(pronargs, nargs);
1077 newResult = (FuncCandidateList)
1078 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
1079 + effective_nargs * sizeof(Oid));
1080 newResult->pathpos = pathpos;
1081 newResult->oid = HeapTupleGetOid(proctup);
1082 newResult->nargs = effective_nargs;
1083 newResult->argnumbers = argnumbers;
1086 /* Re-order the argument types into call's logical order */
1087 Oid *proargtypes = procform->proargtypes.values;
1090 for (i = 0; i < pronargs; i++)
1091 newResult->args[i] = proargtypes[argnumbers[i]];
1095 /* Simple positional case, just copy proargtypes as-is */
1096 memcpy(newResult->args, procform->proargtypes.values,
1097 pronargs * sizeof(Oid));
1103 newResult->nvargs = effective_nargs - pronargs + 1;
1104 /* Expand variadic argument into N copies of element type */
1105 for (i = pronargs - 1; i < effective_nargs; i++)
1106 newResult->args[i] = va_elem_type;
1109 newResult->nvargs = 0;
1110 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1113 * Does it have the same arguments as something we already accepted?
1114 * If so, decide what to do to avoid returning duplicate argument
1115 * lists. We can skip this check for the single-namespace case if no
1116 * special (named, variadic or defaults) match has been made, since
1117 * then the unique index on pg_proc guarantees all the matches have
1118 * different argument lists.
1120 if (resultList != NULL &&
1121 (any_special || !OidIsValid(namespaceId)))
1124 * If we have an ordered list from SearchSysCacheList (the normal
1125 * case), then any conflicting proc must immediately adjoin this
1126 * one in the list, so we only need to look at the newest result
1127 * item. If we have an unordered list, we have to scan the whole
1128 * result list. Also, if either the current candidate or any
1129 * previous candidate is a special match, we can't assume that
1130 * conflicts are adjacent.
1132 * We ignore defaulted arguments in deciding what is a match.
1134 FuncCandidateList prevResult;
1136 if (catlist->ordered && !any_special)
1138 /* ndargs must be 0 if !any_special */
1139 if (effective_nargs == resultList->nargs &&
1140 memcmp(newResult->args,
1142 effective_nargs * sizeof(Oid)) == 0)
1143 prevResult = resultList;
1149 int cmp_nargs = newResult->nargs - newResult->ndargs;
1151 for (prevResult = resultList;
1153 prevResult = prevResult->next)
1155 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1156 memcmp(newResult->args,
1158 cmp_nargs * sizeof(Oid)) == 0)
1166 * We have a match with a previous result. Decide which one
1167 * to keep, or mark it ambiguous if we can't decide. The
1168 * logic here is preference > 0 means prefer the old result,
1169 * preference < 0 means prefer the new, preference = 0 means
1174 if (pathpos != prevResult->pathpos)
1177 * Prefer the one that's earlier in the search path.
1179 preference = pathpos - prevResult->pathpos;
1181 else if (variadic && prevResult->nvargs == 0)
1184 * With variadic functions we could have, for example,
1185 * both foo(numeric) and foo(variadic numeric[]) in the
1186 * same namespace; if so we prefer the non-variadic match
1187 * on efficiency grounds.
1191 else if (!variadic && prevResult->nvargs > 0)
1198 * We can't decide. This can happen with, for example,
1199 * both foo(numeric, variadic numeric[]) and
1200 * foo(variadic numeric[]) in the same namespace, or
1201 * both foo(int) and foo (int, int default something)
1202 * in the same namespace, or both foo(a int, b text)
1203 * and foo(b text, a int) in the same namespace.
1211 /* keep previous result */
1215 else if (preference < 0)
1217 /* remove previous result from the list */
1218 if (prevResult == resultList)
1219 resultList = prevResult->next;
1222 FuncCandidateList prevPrevResult;
1224 for (prevPrevResult = resultList;
1226 prevPrevResult = prevPrevResult->next)
1228 if (prevResult == prevPrevResult->next)
1230 prevPrevResult->next = prevResult->next;
1234 Assert(prevPrevResult); /* assert we found it */
1237 /* fall through to add newResult to list */
1241 /* mark old result as ambiguous, discard new */
1242 prevResult->oid = InvalidOid;
1250 * Okay to add it to result list
1252 newResult->next = resultList;
1253 resultList = newResult;
1256 ReleaseSysCacheList(catlist);
1263 * Given a pg_proc heap tuple and a call's list of argument names,
1264 * check whether the function could match the call.
1266 * The call could match if all supplied argument names are accepted by
1267 * the function, in positions after the last positional argument, and there
1268 * are defaults for all unsupplied arguments.
1270 * The number of positional arguments is nargs - list_length(argnames).
1271 * Note caller has already done basic checks on argument count.
1273 * On match, return true and fill *argnumbers with a palloc'd array showing
1274 * the mapping from call argument positions to actual function argument
1275 * numbers. Defaulted arguments are included in this map, at positions
1276 * after the last supplied argument.
1279 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1282 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1283 int pronargs = procform->pronargs;
1284 int numposargs = nargs - list_length(argnames);
1289 bool arggiven[FUNC_MAX_ARGS];
1291 int ap; /* call args position */
1292 int pp; /* proargs position */
1295 Assert(argnames != NIL);
1296 Assert(numposargs >= 0);
1297 Assert(nargs <= pronargs);
1299 /* Ignore this function if its proargnames is null */
1300 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1305 /* OK, let's extract the argument names and types */
1306 pronallargs = get_func_arg_info(proctup,
1307 &p_argtypes, &p_argnames, &p_argmodes);
1308 Assert(p_argnames != NULL);
1310 /* initialize state for matching */
1311 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1312 memset(arggiven, false, pronargs * sizeof(bool));
1314 /* there are numposargs positional args before the named args */
1315 for (ap = 0; ap < numposargs; ap++)
1317 (*argnumbers)[ap] = ap;
1318 arggiven[ap] = true;
1321 /* now examine the named args */
1322 foreach(lc, argnames)
1324 char *argname = (char *) lfirst(lc);
1330 for (i = 0; i < pronallargs; i++)
1332 /* consider only input parameters */
1334 (p_argmodes[i] != FUNC_PARAM_IN &&
1335 p_argmodes[i] != FUNC_PARAM_INOUT &&
1336 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1338 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1340 /* fail if argname matches a positional argument */
1343 arggiven[pp] = true;
1344 (*argnumbers)[ap] = pp;
1348 /* increase pp only for input parameters */
1351 /* if name isn't in proargnames, fail */
1357 Assert(ap == nargs); /* processed all actual parameters */
1359 /* Check for default arguments */
1360 if (nargs < pronargs)
1362 int first_arg_with_default = pronargs - procform->pronargdefaults;
1364 for (pp = numposargs; pp < pronargs; pp++)
1368 /* fail if arg not given and no default available */
1369 if (pp < first_arg_with_default)
1371 (*argnumbers)[ap++] = pp;
1375 Assert(ap == pronargs); /* processed all function parameters */
1382 * Determine whether a function (identified by OID) is visible in the
1383 * current search path. Visible means "would be found by searching
1384 * for the unqualified function name with exact argument matches".
1387 FunctionIsVisible(Oid funcid)
1390 Form_pg_proc procform;
1394 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1395 if (!HeapTupleIsValid(proctup))
1396 elog(ERROR, "cache lookup failed for function %u", funcid);
1397 procform = (Form_pg_proc) GETSTRUCT(proctup);
1399 recomputeNamespacePath();
1402 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1403 * the system namespace are surely in the path and so we needn't even do
1404 * list_member_oid() for them.
1406 pronamespace = procform->pronamespace;
1407 if (pronamespace != PG_CATALOG_NAMESPACE &&
1408 !list_member_oid(activeSearchPath, pronamespace))
1413 * If it is in the path, it might still not be visible; it could be
1414 * hidden by another proc of the same name and arguments earlier in
1415 * the path. So we must do a slow check to see if this is the same
1416 * proc that would be found by FuncnameGetCandidates.
1418 char *proname = NameStr(procform->proname);
1419 int nargs = procform->pronargs;
1420 FuncCandidateList clist;
1424 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1425 nargs, NIL, false, false, false);
1427 for (; clist; clist = clist->next)
1429 if (memcmp(clist->args, procform->proargtypes.values,
1430 nargs * sizeof(Oid)) == 0)
1432 /* Found the expected entry; is it the right proc? */
1433 visible = (clist->oid == funcid);
1439 ReleaseSysCache(proctup);
1447 * Given a possibly-qualified operator name and exact input datatypes,
1448 * look up the operator. Returns InvalidOid if not found.
1450 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1453 * If the operator name is not schema-qualified, it is sought in the current
1454 * namespace search path. If the name is schema-qualified and the given
1455 * schema does not exist, InvalidOid is returned.
1458 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1465 /* deconstruct the name list */
1466 DeconstructQualifiedName(names, &schemaname, &opername);
1470 /* search only in exact schema given */
1473 namespaceId = LookupExplicitNamespace(schemaname, true);
1474 if (OidIsValid(namespaceId))
1478 opertup = SearchSysCache4(OPERNAMENSP,
1479 CStringGetDatum(opername),
1480 ObjectIdGetDatum(oprleft),
1481 ObjectIdGetDatum(oprright),
1482 ObjectIdGetDatum(namespaceId));
1483 if (HeapTupleIsValid(opertup))
1485 Oid result = HeapTupleGetOid(opertup);
1487 ReleaseSysCache(opertup);
1495 /* Search syscache by name and argument types */
1496 catlist = SearchSysCacheList3(OPERNAMENSP,
1497 CStringGetDatum(opername),
1498 ObjectIdGetDatum(oprleft),
1499 ObjectIdGetDatum(oprright));
1501 if (catlist->n_members == 0)
1503 /* no hope, fall out early */
1504 ReleaseSysCacheList(catlist);
1509 * We have to find the list member that is first in the search path, if
1510 * there's more than one. This doubly-nested loop looks ugly, but in
1511 * practice there should usually be few catlist members.
1513 recomputeNamespacePath();
1515 foreach(l, activeSearchPath)
1517 Oid namespaceId = lfirst_oid(l);
1520 if (namespaceId == myTempNamespace)
1521 continue; /* do not look in temp namespace */
1523 for (i = 0; i < catlist->n_members; i++)
1525 HeapTuple opertup = &catlist->members[i]->tuple;
1526 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1528 if (operform->oprnamespace == namespaceId)
1530 Oid result = HeapTupleGetOid(opertup);
1532 ReleaseSysCacheList(catlist);
1538 ReleaseSysCacheList(catlist);
1543 * OpernameGetCandidates
1544 * Given a possibly-qualified operator name and operator kind,
1545 * retrieve a list of the possible matches.
1547 * If oprkind is '\0', we return all operators matching the given name,
1548 * regardless of arguments.
1550 * We search a single namespace if the operator name is qualified, else
1551 * all namespaces in the search path. The return list will never contain
1552 * multiple entries with identical argument lists --- in the multiple-
1553 * namespace case, we arrange for entries in earlier namespaces to mask
1554 * identical entries in later namespaces.
1556 * The returned items always have two args[] entries --- one or the other
1557 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1560 OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
1562 FuncCandidateList resultList = NULL;
1563 char *resultSpace = NULL;
1571 /* deconstruct the name list */
1572 DeconstructQualifiedName(names, &schemaname, &opername);
1576 /* use exact schema given */
1577 namespaceId = LookupExplicitNamespace(schemaname, missing_schema_ok);
1578 if (missing_schema_ok && !OidIsValid(namespaceId))
1583 /* flag to indicate we need namespace search */
1584 namespaceId = InvalidOid;
1585 recomputeNamespacePath();
1588 /* Search syscache by name only */
1589 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1592 * In typical scenarios, most if not all of the operators found by the
1593 * catcache search will end up getting returned; and there can be quite a
1594 * few, for common operator names such as '=' or '+'. To reduce the time
1595 * spent in palloc, we allocate the result space as an array large enough
1596 * to hold all the operators. The original coding of this routine did a
1597 * separate palloc for each operator, but profiling revealed that the
1598 * pallocs used an unreasonably large fraction of parsing time.
1600 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1602 if (catlist->n_members > 0)
1603 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1605 for (i = 0; i < catlist->n_members; i++)
1607 HeapTuple opertup = &catlist->members[i]->tuple;
1608 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1610 FuncCandidateList newResult;
1612 /* Ignore operators of wrong kind, if specific kind requested */
1613 if (oprkind && operform->oprkind != oprkind)
1616 if (OidIsValid(namespaceId))
1618 /* Consider only opers in specified namespace */
1619 if (operform->oprnamespace != namespaceId)
1621 /* No need to check args, they must all be different */
1626 * Consider only opers that are in the search path and are not in
1627 * the temp namespace.
1631 foreach(nsp, activeSearchPath)
1633 if (operform->oprnamespace == lfirst_oid(nsp) &&
1634 operform->oprnamespace != myTempNamespace)
1639 continue; /* oper is not in search path */
1642 * Okay, it's in the search path, but does it have the same
1643 * arguments as something we already accepted? If so, keep only
1644 * the one that appears earlier in the search path.
1646 * If we have an ordered list from SearchSysCacheList (the normal
1647 * case), then any conflicting oper must immediately adjoin this
1648 * one in the list, so we only need to look at the newest result
1649 * item. If we have an unordered list, we have to scan the whole
1654 FuncCandidateList prevResult;
1656 if (catlist->ordered)
1658 if (operform->oprleft == resultList->args[0] &&
1659 operform->oprright == resultList->args[1])
1660 prevResult = resultList;
1666 for (prevResult = resultList;
1668 prevResult = prevResult->next)
1670 if (operform->oprleft == prevResult->args[0] &&
1671 operform->oprright == prevResult->args[1])
1677 /* We have a match with a previous result */
1678 Assert(pathpos != prevResult->pathpos);
1679 if (pathpos > prevResult->pathpos)
1680 continue; /* keep previous result */
1681 /* replace previous result */
1682 prevResult->pathpos = pathpos;
1683 prevResult->oid = HeapTupleGetOid(opertup);
1684 continue; /* args are same, of course */
1690 * Okay to add it to result list
1692 newResult = (FuncCandidateList) (resultSpace + nextResult);
1693 nextResult += SPACE_PER_OP;
1695 newResult->pathpos = pathpos;
1696 newResult->oid = HeapTupleGetOid(opertup);
1697 newResult->nargs = 2;
1698 newResult->nvargs = 0;
1699 newResult->ndargs = 0;
1700 newResult->argnumbers = NULL;
1701 newResult->args[0] = operform->oprleft;
1702 newResult->args[1] = operform->oprright;
1703 newResult->next = resultList;
1704 resultList = newResult;
1707 ReleaseSysCacheList(catlist);
1714 * Determine whether an operator (identified by OID) is visible in the
1715 * current search path. Visible means "would be found by searching
1716 * for the unqualified operator name with exact argument matches".
1719 OperatorIsVisible(Oid oprid)
1722 Form_pg_operator oprform;
1726 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1727 if (!HeapTupleIsValid(oprtup))
1728 elog(ERROR, "cache lookup failed for operator %u", oprid);
1729 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1731 recomputeNamespacePath();
1734 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1735 * the system namespace are surely in the path and so we needn't even do
1736 * list_member_oid() for them.
1738 oprnamespace = oprform->oprnamespace;
1739 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1740 !list_member_oid(activeSearchPath, oprnamespace))
1745 * If it is in the path, it might still not be visible; it could be
1746 * hidden by another operator of the same name and arguments earlier
1747 * in the path. So we must do a slow check to see if this is the same
1748 * operator that would be found by OpernameGetOprid.
1750 char *oprname = NameStr(oprform->oprname);
1752 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1753 oprform->oprleft, oprform->oprright)
1757 ReleaseSysCache(oprtup);
1764 * OpclassnameGetOpcid
1765 * Try to resolve an unqualified index opclass name.
1766 * Returns OID if opclass found in search path, else InvalidOid.
1768 * This is essentially the same as TypenameGetTypid, but we have to have
1769 * an extra argument for the index AM OID.
1772 OpclassnameGetOpcid(Oid amid, const char *opcname)
1777 recomputeNamespacePath();
1779 foreach(l, activeSearchPath)
1781 Oid namespaceId = lfirst_oid(l);
1783 if (namespaceId == myTempNamespace)
1784 continue; /* do not look in temp namespace */
1786 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1787 ObjectIdGetDatum(amid),
1788 PointerGetDatum(opcname),
1789 ObjectIdGetDatum(namespaceId));
1790 if (OidIsValid(opcid))
1794 /* Not found in path */
1800 * Determine whether an opclass (identified by OID) is visible in the
1801 * current search path. Visible means "would be found by searching
1802 * for the unqualified opclass name".
1805 OpclassIsVisible(Oid opcid)
1808 Form_pg_opclass opcform;
1812 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1813 if (!HeapTupleIsValid(opctup))
1814 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1815 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1817 recomputeNamespacePath();
1820 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1821 * the system namespace are surely in the path and so we needn't even do
1822 * list_member_oid() for them.
1824 opcnamespace = opcform->opcnamespace;
1825 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1826 !list_member_oid(activeSearchPath, opcnamespace))
1831 * If it is in the path, it might still not be visible; it could be
1832 * hidden by another opclass of the same name earlier in the path. So
1833 * we must do a slow check to see if this opclass would be found by
1834 * OpclassnameGetOpcid.
1836 char *opcname = NameStr(opcform->opcname);
1838 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1841 ReleaseSysCache(opctup);
1847 * OpfamilynameGetOpfid
1848 * Try to resolve an unqualified index opfamily name.
1849 * Returns OID if opfamily found in search path, else InvalidOid.
1851 * This is essentially the same as TypenameGetTypid, but we have to have
1852 * an extra argument for the index AM OID.
1855 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1860 recomputeNamespacePath();
1862 foreach(l, activeSearchPath)
1864 Oid namespaceId = lfirst_oid(l);
1866 if (namespaceId == myTempNamespace)
1867 continue; /* do not look in temp namespace */
1869 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1870 ObjectIdGetDatum(amid),
1871 PointerGetDatum(opfname),
1872 ObjectIdGetDatum(namespaceId));
1873 if (OidIsValid(opfid))
1877 /* Not found in path */
1883 * Determine whether an opfamily (identified by OID) is visible in the
1884 * current search path. Visible means "would be found by searching
1885 * for the unqualified opfamily name".
1888 OpfamilyIsVisible(Oid opfid)
1891 Form_pg_opfamily opfform;
1895 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1896 if (!HeapTupleIsValid(opftup))
1897 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1898 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1900 recomputeNamespacePath();
1903 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1904 * the system namespace are surely in the path and so we needn't even do
1905 * list_member_oid() for them.
1907 opfnamespace = opfform->opfnamespace;
1908 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1909 !list_member_oid(activeSearchPath, opfnamespace))
1914 * If it is in the path, it might still not be visible; it could be
1915 * hidden by another opfamily of the same name earlier in the path. So
1916 * we must do a slow check to see if this opfamily would be found by
1917 * OpfamilynameGetOpfid.
1919 char *opfname = NameStr(opfform->opfname);
1921 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1924 ReleaseSysCache(opftup);
1930 * CollationGetCollid
1931 * Try to resolve an unqualified collation name.
1932 * Returns OID if collation found in search path, else InvalidOid.
1935 CollationGetCollid(const char *collname)
1937 int32 dbencoding = GetDatabaseEncoding();
1940 recomputeNamespacePath();
1942 foreach(l, activeSearchPath)
1944 Oid namespaceId = lfirst_oid(l);
1947 if (namespaceId == myTempNamespace)
1948 continue; /* do not look in temp namespace */
1950 /* Check for database-encoding-specific entry */
1951 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1952 PointerGetDatum(collname),
1953 Int32GetDatum(dbencoding),
1954 ObjectIdGetDatum(namespaceId));
1955 if (OidIsValid(collid))
1958 /* Check for any-encoding entry */
1959 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1960 PointerGetDatum(collname),
1962 ObjectIdGetDatum(namespaceId));
1963 if (OidIsValid(collid))
1967 /* Not found in path */
1972 * CollationIsVisible
1973 * Determine whether a collation (identified by OID) is visible in the
1974 * current search path. Visible means "would be found by searching
1975 * for the unqualified collation name".
1978 CollationIsVisible(Oid collid)
1981 Form_pg_collation collform;
1985 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1986 if (!HeapTupleIsValid(colltup))
1987 elog(ERROR, "cache lookup failed for collation %u", collid);
1988 collform = (Form_pg_collation) GETSTRUCT(colltup);
1990 recomputeNamespacePath();
1993 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1994 * the system namespace are surely in the path and so we needn't even do
1995 * list_member_oid() for them.
1997 collnamespace = collform->collnamespace;
1998 if (collnamespace != PG_CATALOG_NAMESPACE &&
1999 !list_member_oid(activeSearchPath, collnamespace))
2004 * If it is in the path, it might still not be visible; it could be
2005 * hidden by another conversion of the same name earlier in the path.
2006 * So we must do a slow check to see if this conversion would be found
2007 * by CollationGetCollid.
2009 char *collname = NameStr(collform->collname);
2011 visible = (CollationGetCollid(collname) == collid);
2014 ReleaseSysCache(colltup);
2021 * ConversionGetConid
2022 * Try to resolve an unqualified conversion name.
2023 * Returns OID if conversion found in search path, else InvalidOid.
2025 * This is essentially the same as RelnameGetRelid.
2028 ConversionGetConid(const char *conname)
2033 recomputeNamespacePath();
2035 foreach(l, activeSearchPath)
2037 Oid namespaceId = lfirst_oid(l);
2039 if (namespaceId == myTempNamespace)
2040 continue; /* do not look in temp namespace */
2042 conid = GetSysCacheOid2(CONNAMENSP,
2043 PointerGetDatum(conname),
2044 ObjectIdGetDatum(namespaceId));
2045 if (OidIsValid(conid))
2049 /* Not found in path */
2054 * ConversionIsVisible
2055 * Determine whether a conversion (identified by OID) is visible in the
2056 * current search path. Visible means "would be found by searching
2057 * for the unqualified conversion name".
2060 ConversionIsVisible(Oid conid)
2063 Form_pg_conversion conform;
2067 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2068 if (!HeapTupleIsValid(contup))
2069 elog(ERROR, "cache lookup failed for conversion %u", conid);
2070 conform = (Form_pg_conversion) GETSTRUCT(contup);
2072 recomputeNamespacePath();
2075 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2076 * the system namespace are surely in the path and so we needn't even do
2077 * list_member_oid() for them.
2079 connamespace = conform->connamespace;
2080 if (connamespace != PG_CATALOG_NAMESPACE &&
2081 !list_member_oid(activeSearchPath, connamespace))
2086 * If it is in the path, it might still not be visible; it could be
2087 * hidden by another conversion of the same name earlier in the path.
2088 * So we must do a slow check to see if this conversion would be found
2089 * by ConversionGetConid.
2091 char *conname = NameStr(conform->conname);
2093 visible = (ConversionGetConid(conname) == conid);
2096 ReleaseSysCache(contup);
2102 * get_ts_parser_oid - find a TS parser by possibly qualified name
2104 * If not found, returns InvalidOid if missing_ok, else throws error
2107 get_ts_parser_oid(List *names, bool missing_ok)
2112 Oid prsoid = InvalidOid;
2115 /* deconstruct the name list */
2116 DeconstructQualifiedName(names, &schemaname, &parser_name);
2120 /* use exact schema given */
2121 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2122 if (missing_ok && !OidIsValid(namespaceId))
2123 prsoid = InvalidOid;
2125 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2126 PointerGetDatum(parser_name),
2127 ObjectIdGetDatum(namespaceId));
2131 /* search for it in search path */
2132 recomputeNamespacePath();
2134 foreach(l, activeSearchPath)
2136 namespaceId = lfirst_oid(l);
2138 if (namespaceId == myTempNamespace)
2139 continue; /* do not look in temp namespace */
2141 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2142 PointerGetDatum(parser_name),
2143 ObjectIdGetDatum(namespaceId));
2144 if (OidIsValid(prsoid))
2149 if (!OidIsValid(prsoid) && !missing_ok)
2151 (errcode(ERRCODE_UNDEFINED_OBJECT),
2152 errmsg("text search parser \"%s\" does not exist",
2153 NameListToString(names))));
2160 * Determine whether a parser (identified by OID) is visible in the
2161 * current search path. Visible means "would be found by searching
2162 * for the unqualified parser name".
2165 TSParserIsVisible(Oid prsId)
2168 Form_pg_ts_parser form;
2172 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2173 if (!HeapTupleIsValid(tup))
2174 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2175 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2177 recomputeNamespacePath();
2180 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2181 * the system namespace are surely in the path and so we needn't even do
2182 * list_member_oid() for them.
2184 namespace = form->prsnamespace;
2185 if (namespace != PG_CATALOG_NAMESPACE &&
2186 !list_member_oid(activeSearchPath, namespace))
2191 * If it is in the path, it might still not be visible; it could be
2192 * hidden by another parser of the same name earlier in the path. So
2193 * we must do a slow check for conflicting parsers.
2195 char *name = NameStr(form->prsname);
2199 foreach(l, activeSearchPath)
2201 Oid namespaceId = lfirst_oid(l);
2203 if (namespaceId == myTempNamespace)
2204 continue; /* do not look in temp namespace */
2206 if (namespaceId == namespace)
2208 /* Found it first in path */
2212 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2213 PointerGetDatum(name),
2214 ObjectIdGetDatum(namespaceId)))
2216 /* Found something else first in path */
2222 ReleaseSysCache(tup);
2228 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2230 * If not found, returns InvalidOid if failOK, else throws error
2233 get_ts_dict_oid(List *names, bool missing_ok)
2238 Oid dictoid = InvalidOid;
2241 /* deconstruct the name list */
2242 DeconstructQualifiedName(names, &schemaname, &dict_name);
2246 /* use exact schema given */
2247 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2248 if (missing_ok && !OidIsValid(namespaceId))
2249 dictoid = InvalidOid;
2251 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2252 PointerGetDatum(dict_name),
2253 ObjectIdGetDatum(namespaceId));
2257 /* search for it in search path */
2258 recomputeNamespacePath();
2260 foreach(l, activeSearchPath)
2262 namespaceId = lfirst_oid(l);
2264 if (namespaceId == myTempNamespace)
2265 continue; /* do not look in temp namespace */
2267 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2268 PointerGetDatum(dict_name),
2269 ObjectIdGetDatum(namespaceId));
2270 if (OidIsValid(dictoid))
2275 if (!OidIsValid(dictoid) && !missing_ok)
2277 (errcode(ERRCODE_UNDEFINED_OBJECT),
2278 errmsg("text search dictionary \"%s\" does not exist",
2279 NameListToString(names))));
2285 * TSDictionaryIsVisible
2286 * Determine whether a dictionary (identified by OID) is visible in the
2287 * current search path. Visible means "would be found by searching
2288 * for the unqualified dictionary name".
2291 TSDictionaryIsVisible(Oid dictId)
2294 Form_pg_ts_dict form;
2298 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2299 if (!HeapTupleIsValid(tup))
2300 elog(ERROR, "cache lookup failed for text search dictionary %u",
2302 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2304 recomputeNamespacePath();
2307 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2308 * the system namespace are surely in the path and so we needn't even do
2309 * list_member_oid() for them.
2311 namespace = form->dictnamespace;
2312 if (namespace != PG_CATALOG_NAMESPACE &&
2313 !list_member_oid(activeSearchPath, namespace))
2318 * If it is in the path, it might still not be visible; it could be
2319 * hidden by another dictionary of the same name earlier in the path.
2320 * So we must do a slow check for conflicting dictionaries.
2322 char *name = NameStr(form->dictname);
2326 foreach(l, activeSearchPath)
2328 Oid namespaceId = lfirst_oid(l);
2330 if (namespaceId == myTempNamespace)
2331 continue; /* do not look in temp namespace */
2333 if (namespaceId == namespace)
2335 /* Found it first in path */
2339 if (SearchSysCacheExists2(TSDICTNAMENSP,
2340 PointerGetDatum(name),
2341 ObjectIdGetDatum(namespaceId)))
2343 /* Found something else first in path */
2349 ReleaseSysCache(tup);
2355 * get_ts_template_oid - find a TS template by possibly qualified name
2357 * If not found, returns InvalidOid if missing_ok, else throws error
2360 get_ts_template_oid(List *names, bool missing_ok)
2363 char *template_name;
2365 Oid tmploid = InvalidOid;
2368 /* deconstruct the name list */
2369 DeconstructQualifiedName(names, &schemaname, &template_name);
2373 /* use exact schema given */
2374 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2375 if (missing_ok && !OidIsValid(namespaceId))
2376 tmploid = InvalidOid;
2378 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2379 PointerGetDatum(template_name),
2380 ObjectIdGetDatum(namespaceId));
2384 /* search for it in search path */
2385 recomputeNamespacePath();
2387 foreach(l, activeSearchPath)
2389 namespaceId = lfirst_oid(l);
2391 if (namespaceId == myTempNamespace)
2392 continue; /* do not look in temp namespace */
2394 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2395 PointerGetDatum(template_name),
2396 ObjectIdGetDatum(namespaceId));
2397 if (OidIsValid(tmploid))
2402 if (!OidIsValid(tmploid) && !missing_ok)
2404 (errcode(ERRCODE_UNDEFINED_OBJECT),
2405 errmsg("text search template \"%s\" does not exist",
2406 NameListToString(names))));
2412 * TSTemplateIsVisible
2413 * Determine whether a template (identified by OID) is visible in the
2414 * current search path. Visible means "would be found by searching
2415 * for the unqualified template name".
2418 TSTemplateIsVisible(Oid tmplId)
2421 Form_pg_ts_template form;
2425 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2426 if (!HeapTupleIsValid(tup))
2427 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2428 form = (Form_pg_ts_template) GETSTRUCT(tup);
2430 recomputeNamespacePath();
2433 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2434 * the system namespace are surely in the path and so we needn't even do
2435 * list_member_oid() for them.
2437 namespace = form->tmplnamespace;
2438 if (namespace != PG_CATALOG_NAMESPACE &&
2439 !list_member_oid(activeSearchPath, namespace))
2444 * If it is in the path, it might still not be visible; it could be
2445 * hidden by another template of the same name earlier in the path. So
2446 * we must do a slow check for conflicting templates.
2448 char *name = NameStr(form->tmplname);
2452 foreach(l, activeSearchPath)
2454 Oid namespaceId = lfirst_oid(l);
2456 if (namespaceId == myTempNamespace)
2457 continue; /* do not look in temp namespace */
2459 if (namespaceId == namespace)
2461 /* Found it first in path */
2465 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2466 PointerGetDatum(name),
2467 ObjectIdGetDatum(namespaceId)))
2469 /* Found something else first in path */
2475 ReleaseSysCache(tup);
2481 * get_ts_config_oid - find a TS config by possibly qualified name
2483 * If not found, returns InvalidOid if missing_ok, else throws error
2486 get_ts_config_oid(List *names, bool missing_ok)
2491 Oid cfgoid = InvalidOid;
2494 /* deconstruct the name list */
2495 DeconstructQualifiedName(names, &schemaname, &config_name);
2499 /* use exact schema given */
2500 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2501 if (missing_ok && !OidIsValid(namespaceId))
2502 cfgoid = InvalidOid;
2504 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2505 PointerGetDatum(config_name),
2506 ObjectIdGetDatum(namespaceId));
2510 /* search for it in search path */
2511 recomputeNamespacePath();
2513 foreach(l, activeSearchPath)
2515 namespaceId = lfirst_oid(l);
2517 if (namespaceId == myTempNamespace)
2518 continue; /* do not look in temp namespace */
2520 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2521 PointerGetDatum(config_name),
2522 ObjectIdGetDatum(namespaceId));
2523 if (OidIsValid(cfgoid))
2528 if (!OidIsValid(cfgoid) && !missing_ok)
2530 (errcode(ERRCODE_UNDEFINED_OBJECT),
2531 errmsg("text search configuration \"%s\" does not exist",
2532 NameListToString(names))));
2539 * Determine whether a text search configuration (identified by OID)
2540 * is visible in the current search path. Visible means "would be found
2541 * by searching for the unqualified text search configuration name".
2544 TSConfigIsVisible(Oid cfgid)
2547 Form_pg_ts_config form;
2551 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2552 if (!HeapTupleIsValid(tup))
2553 elog(ERROR, "cache lookup failed for text search configuration %u",
2555 form = (Form_pg_ts_config) GETSTRUCT(tup);
2557 recomputeNamespacePath();
2560 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2561 * the system namespace are surely in the path and so we needn't even do
2562 * list_member_oid() for them.
2564 namespace = form->cfgnamespace;
2565 if (namespace != PG_CATALOG_NAMESPACE &&
2566 !list_member_oid(activeSearchPath, namespace))
2571 * If it is in the path, it might still not be visible; it could be
2572 * hidden by another configuration of the same name earlier in the
2573 * path. So we must do a slow check for conflicting configurations.
2575 char *name = NameStr(form->cfgname);
2579 foreach(l, activeSearchPath)
2581 Oid namespaceId = lfirst_oid(l);
2583 if (namespaceId == myTempNamespace)
2584 continue; /* do not look in temp namespace */
2586 if (namespaceId == namespace)
2588 /* Found it first in path */
2592 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2593 PointerGetDatum(name),
2594 ObjectIdGetDatum(namespaceId)))
2596 /* Found something else first in path */
2602 ReleaseSysCache(tup);
2609 * DeconstructQualifiedName
2610 * Given a possibly-qualified name expressed as a list of String nodes,
2611 * extract the schema name and object name.
2613 * *nspname_p is set to NULL if there is no explicit schema name.
2616 DeconstructQualifiedName(List *names,
2621 char *schemaname = NULL;
2622 char *objname = NULL;
2624 switch (list_length(names))
2627 objname = strVal(linitial(names));
2630 schemaname = strVal(linitial(names));
2631 objname = strVal(lsecond(names));
2634 catalogname = strVal(linitial(names));
2635 schemaname = strVal(lsecond(names));
2636 objname = strVal(lthird(names));
2639 * We check the catalog name and then ignore it.
2641 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2643 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2644 errmsg("cross-database references are not implemented: %s",
2645 NameListToString(names))));
2649 (errcode(ERRCODE_SYNTAX_ERROR),
2650 errmsg("improper qualified name (too many dotted names): %s",
2651 NameListToString(names))));
2655 *nspname_p = schemaname;
2656 *objname_p = objname;
2660 * LookupNamespaceNoError
2661 * Look up a schema name.
2663 * Returns the namespace OID, or InvalidOid if not found.
2665 * Note this does NOT perform any permissions check --- callers are
2666 * responsible for being sure that an appropriate check is made.
2667 * In the majority of cases LookupExplicitNamespace is preferable.
2670 LookupNamespaceNoError(const char *nspname)
2672 /* check for pg_temp alias */
2673 if (strcmp(nspname, "pg_temp") == 0)
2675 if (OidIsValid(myTempNamespace))
2677 InvokeNamespaceSearchHook(myTempNamespace, true);
2678 return myTempNamespace;
2682 * Since this is used only for looking up existing objects, there is
2683 * no point in trying to initialize the temp namespace here; and doing
2684 * so might create problems for some callers. Just report "not found".
2689 return get_namespace_oid(nspname, true);
2693 * LookupExplicitNamespace
2694 * Process an explicitly-specified schema name: look up the schema
2695 * and verify we have USAGE (lookup) rights in it.
2697 * Returns the namespace OID
2700 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2703 AclResult aclresult;
2705 /* check for pg_temp alias */
2706 if (strcmp(nspname, "pg_temp") == 0)
2708 if (OidIsValid(myTempNamespace))
2709 return myTempNamespace;
2712 * Since this is used only for looking up existing objects, there is
2713 * no point in trying to initialize the temp namespace here; and doing
2714 * so might create problems for some callers --- just fall through.
2718 namespaceId = get_namespace_oid(nspname, missing_ok);
2719 if (missing_ok && !OidIsValid(namespaceId))
2722 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2723 if (aclresult != ACLCHECK_OK)
2724 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2726 /* Schema search hook for this lookup */
2727 InvokeNamespaceSearchHook(namespaceId, true);
2733 * LookupCreationNamespace
2734 * Look up the schema and verify we have CREATE rights on it.
2736 * This is just like LookupExplicitNamespace except for the different
2737 * permission check, and that we are willing to create pg_temp if needed.
2739 * Note: calling this may result in a CommandCounterIncrement operation,
2740 * if we have to create or clean out the temp namespace.
2743 LookupCreationNamespace(const char *nspname)
2746 AclResult aclresult;
2748 /* check for pg_temp alias */
2749 if (strcmp(nspname, "pg_temp") == 0)
2751 /* Initialize temp namespace if first time through */
2752 if (!OidIsValid(myTempNamespace))
2753 InitTempTableNamespace();
2754 return myTempNamespace;
2757 namespaceId = get_namespace_oid(nspname, false);
2759 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2760 if (aclresult != ACLCHECK_OK)
2761 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2768 * Common checks on switching namespaces.
2770 * We complain if (1) the old and new namespaces are the same, (2) either the
2771 * old or new namespaces is a temporary schema (or temporary toast schema), or
2772 * (3) either the old or new namespaces is the TOAST schema.
2775 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2777 if (oldNspOid == nspOid)
2779 (classid == RelationRelationId ?
2780 errcode(ERRCODE_DUPLICATE_TABLE) :
2781 classid == ProcedureRelationId ?
2782 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2783 errcode(ERRCODE_DUPLICATE_OBJECT),
2784 errmsg("%s is already in schema \"%s\"",
2785 getObjectDescriptionOids(classid, objid),
2786 get_namespace_name(nspOid))));
2788 /* disallow renaming into or out of temp schemas */
2789 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2791 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2792 errmsg("cannot move objects into or out of temporary schemas")));
2794 /* same for TOAST schema */
2795 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2797 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2798 errmsg("cannot move objects into or out of TOAST schema")));
2802 * QualifiedNameGetCreationNamespace
2803 * Given a possibly-qualified name for an object (in List-of-Values
2804 * format), determine what namespace the object should be created in.
2805 * Also extract and return the object name (last component of list).
2807 * Note: this does not apply any permissions check. Callers must check
2808 * for CREATE rights on the selected namespace when appropriate.
2810 * Note: calling this may result in a CommandCounterIncrement operation,
2811 * if we have to create or clean out the temp namespace.
2814 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2819 /* deconstruct the name list */
2820 DeconstructQualifiedName(names, &schemaname, objname_p);
2824 /* check for pg_temp alias */
2825 if (strcmp(schemaname, "pg_temp") == 0)
2827 /* Initialize temp namespace if first time through */
2828 if (!OidIsValid(myTempNamespace))
2829 InitTempTableNamespace();
2830 return myTempNamespace;
2832 /* use exact schema given */
2833 namespaceId = get_namespace_oid(schemaname, false);
2834 /* we do not check for USAGE rights here! */
2838 /* use the default creation namespace */
2839 recomputeNamespacePath();
2840 if (activeTempCreationPending)
2842 /* Need to initialize temp namespace */
2843 InitTempTableNamespace();
2844 return myTempNamespace;
2846 namespaceId = activeCreationNamespace;
2847 if (!OidIsValid(namespaceId))
2849 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2850 errmsg("no schema has been selected to create in")));
2857 * get_namespace_oid - given a namespace name, look up the OID
2859 * If missing_ok is false, throw an error if namespace name not found. If
2860 * true, just return InvalidOid.
2863 get_namespace_oid(const char *nspname, bool missing_ok)
2867 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2868 if (!OidIsValid(oid) && !missing_ok)
2870 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2871 errmsg("schema \"%s\" does not exist", nspname)));
2877 * makeRangeVarFromNameList
2878 * Utility routine to convert a qualified-name list into RangeVar form.
2881 makeRangeVarFromNameList(List *names)
2883 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2885 switch (list_length(names))
2888 rel->relname = strVal(linitial(names));
2891 rel->schemaname = strVal(linitial(names));
2892 rel->relname = strVal(lsecond(names));
2895 rel->catalogname = strVal(linitial(names));
2896 rel->schemaname = strVal(lsecond(names));
2897 rel->relname = strVal(lthird(names));
2901 (errcode(ERRCODE_SYNTAX_ERROR),
2902 errmsg("improper relation name (too many dotted names): %s",
2903 NameListToString(names))));
2912 * Utility routine to convert a qualified-name list into a string.
2914 * This is used primarily to form error messages, and so we do not quote
2915 * the list elements, for the sake of legibility.
2917 * In most scenarios the list elements should always be Value strings,
2918 * but we also allow A_Star for the convenience of ColumnRef processing.
2921 NameListToString(List *names)
2923 StringInfoData string;
2926 initStringInfo(&string);
2930 Node *name = (Node *) lfirst(l);
2932 if (l != list_head(names))
2933 appendStringInfoChar(&string, '.');
2935 if (IsA(name, String))
2936 appendStringInfoString(&string, strVal(name));
2937 else if (IsA(name, A_Star))
2938 appendStringInfoString(&string, "*");
2940 elog(ERROR, "unexpected node type in name list: %d",
2941 (int) nodeTag(name));
2948 * NameListToQuotedString
2949 * Utility routine to convert a qualified-name list into a string.
2951 * Same as above except that names will be double-quoted where necessary,
2952 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2955 NameListToQuotedString(List *names)
2957 StringInfoData string;
2960 initStringInfo(&string);
2964 if (l != list_head(names))
2965 appendStringInfoChar(&string, '.');
2966 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2973 * isTempNamespace - is the given namespace my temporary-table namespace?
2976 isTempNamespace(Oid namespaceId)
2978 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2984 * isTempToastNamespace - is the given namespace my temporary-toast-table
2988 isTempToastNamespace(Oid namespaceId)
2990 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2996 * isTempOrTempToastNamespace - is the given namespace my temporary-table
2997 * namespace or my temporary-toast-table namespace?
3000 isTempOrTempToastNamespace(Oid namespaceId)
3002 if (OidIsValid(myTempNamespace) &&
3003 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3009 * isAnyTempNamespace - is the given namespace a temporary-table namespace
3010 * (either my own, or another backend's)? Temporary-toast-table namespaces
3011 * are included, too.
3014 isAnyTempNamespace(Oid namespaceId)
3019 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3020 nspname = get_namespace_name(namespaceId);
3022 return false; /* no such namespace? */
3023 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3024 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3030 * isOtherTempNamespace - is the given namespace some other backend's
3031 * temporary-table namespace (including temporary-toast-table namespaces)?
3033 * Note: for most purposes in the C code, this function is obsolete. Use
3034 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3037 isOtherTempNamespace(Oid namespaceId)
3039 /* If it's my own temp namespace, say "false" */
3040 if (isTempOrTempToastNamespace(namespaceId))
3042 /* Else, if it's any temp namespace, say "true" */
3043 return isAnyTempNamespace(namespaceId);
3047 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3048 * namespace (either my own, or another backend's), return the BackendId
3049 * that owns it. Temporary-toast-table namespaces are included, too.
3050 * If it isn't a temp namespace, return InvalidBackendId.
3053 GetTempNamespaceBackendId(Oid namespaceId)
3058 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3059 nspname = get_namespace_name(namespaceId);
3061 return InvalidBackendId; /* no such namespace? */
3062 if (strncmp(nspname, "pg_temp_", 8) == 0)
3063 result = atoi(nspname + 8);
3064 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3065 result = atoi(nspname + 14);
3067 result = InvalidBackendId;
3073 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3074 * which must already be assigned. (This is only used when creating a toast
3075 * table for a temp table, so we must have already done InitTempTableNamespace)
3078 GetTempToastNamespace(void)
3080 Assert(OidIsValid(myTempToastNamespace));
3081 return myTempToastNamespace;
3086 * GetOverrideSearchPath - fetch current search path definition in form
3087 * used by PushOverrideSearchPath.
3089 * The result structure is allocated in the specified memory context
3090 * (which might or might not be equal to CurrentMemoryContext); but any
3091 * junk created by revalidation calculations will be in CurrentMemoryContext.
3093 OverrideSearchPath *
3094 GetOverrideSearchPath(MemoryContext context)
3096 OverrideSearchPath *result;
3098 MemoryContext oldcxt;
3100 recomputeNamespacePath();
3102 oldcxt = MemoryContextSwitchTo(context);
3104 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3105 schemas = list_copy(activeSearchPath);
3106 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3108 if (linitial_oid(schemas) == myTempNamespace)
3109 result->addTemp = true;
3112 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3113 result->addCatalog = true;
3115 schemas = list_delete_first(schemas);
3117 result->schemas = schemas;
3119 MemoryContextSwitchTo(oldcxt);
3125 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3127 * The result structure is allocated in CurrentMemoryContext.
3129 OverrideSearchPath *
3130 CopyOverrideSearchPath(OverrideSearchPath *path)
3132 OverrideSearchPath *result;
3134 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3135 result->schemas = list_copy(path->schemas);
3136 result->addCatalog = path->addCatalog;
3137 result->addTemp = path->addTemp;
3143 * OverrideSearchPathMatchesCurrent - does path match current setting?
3146 OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
3151 recomputeNamespacePath();
3153 /* We scan down the activeSearchPath to see if it matches the input. */
3154 lc = list_head(activeSearchPath);
3156 /* If path->addTemp, first item should be my temp namespace. */
3159 if (lc && lfirst_oid(lc) == myTempNamespace)
3164 /* If path->addCatalog, next item should be pg_catalog. */
3165 if (path->addCatalog)
3167 if (lc && lfirst_oid(lc) == PG_CATALOG_NAMESPACE)
3172 /* We should now be looking at the activeCreationNamespace. */
3173 if (activeCreationNamespace != (lc ? lfirst_oid(lc) : InvalidOid))
3175 /* The remainder of activeSearchPath should match path->schemas. */
3176 foreach(lcp, path->schemas)
3178 if (lc && lfirst_oid(lc) == lfirst_oid(lcp))
3189 * PushOverrideSearchPath - temporarily override the search path
3191 * We allow nested overrides, hence the push/pop terminology. The GUC
3192 * search_path variable is ignored while an override is active.
3194 * It's possible that newpath->useTemp is set but there is no longer any
3195 * active temp namespace, if the path was saved during a transaction that
3196 * created a temp namespace and was later rolled back. In that case we just
3197 * ignore useTemp. A plausible alternative would be to create a new temp
3198 * namespace, but for existing callers that's not necessary because an empty
3199 * temp namespace wouldn't affect their results anyway.
3201 * It's also worth noting that other schemas listed in newpath might not
3202 * exist anymore either. We don't worry about this because OIDs that match
3203 * no existing namespace will simply not produce any hits during searches.
3206 PushOverrideSearchPath(OverrideSearchPath *newpath)
3208 OverrideStackEntry *entry;
3211 MemoryContext oldcxt;
3214 * Copy the list for safekeeping, and insert implicitly-searched
3215 * namespaces as needed. This code should track recomputeNamespacePath.
3217 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3219 oidlist = list_copy(newpath->schemas);
3222 * Remember the first member of the explicit list.
3225 firstNS = InvalidOid;
3227 firstNS = linitial_oid(oidlist);
3230 * Add any implicitly-searched namespaces to the list. Note these go on
3231 * the front, not the back; also notice that we do not check USAGE
3232 * permissions for these.
3234 if (newpath->addCatalog)
3235 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3237 if (newpath->addTemp && OidIsValid(myTempNamespace))
3238 oidlist = lcons_oid(myTempNamespace, oidlist);
3241 * Build the new stack entry, then insert it at the head of the list.
3243 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3244 entry->searchPath = oidlist;
3245 entry->creationNamespace = firstNS;
3246 entry->nestLevel = GetCurrentTransactionNestLevel();
3248 overrideStack = lcons(entry, overrideStack);
3250 /* And make it active. */
3251 activeSearchPath = entry->searchPath;
3252 activeCreationNamespace = entry->creationNamespace;
3253 activeTempCreationPending = false; /* XXX is this OK? */
3255 MemoryContextSwitchTo(oldcxt);
3259 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3261 * Any push during a (sub)transaction will be popped automatically at abort.
3262 * But it's caller error if a push isn't popped in normal control flow.
3265 PopOverrideSearchPath(void)
3267 OverrideStackEntry *entry;
3269 /* Sanity checks. */
3270 if (overrideStack == NIL)
3271 elog(ERROR, "bogus PopOverrideSearchPath call");
3272 entry = (OverrideStackEntry *) linitial(overrideStack);
3273 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3274 elog(ERROR, "bogus PopOverrideSearchPath call");
3276 /* Pop the stack and free storage. */
3277 overrideStack = list_delete_first(overrideStack);
3278 list_free(entry->searchPath);
3281 /* Activate the next level down. */
3284 entry = (OverrideStackEntry *) linitial(overrideStack);
3285 activeSearchPath = entry->searchPath;
3286 activeCreationNamespace = entry->creationNamespace;
3287 activeTempCreationPending = false; /* XXX is this OK? */
3291 /* If not baseSearchPathValid, this is useless but harmless */
3292 activeSearchPath = baseSearchPath;
3293 activeCreationNamespace = baseCreationNamespace;
3294 activeTempCreationPending = baseTempCreationPending;
3300 * get_collation_oid - find a collation by possibly qualified name
3303 get_collation_oid(List *name, bool missing_ok)
3306 char *collation_name;
3307 int32 dbencoding = GetDatabaseEncoding();
3312 /* deconstruct the name list */
3313 DeconstructQualifiedName(name, &schemaname, &collation_name);
3317 /* use exact schema given */
3318 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3319 if (missing_ok && !OidIsValid(namespaceId))
3322 /* first try for encoding-specific entry, then any-encoding */
3323 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3324 PointerGetDatum(collation_name),
3325 Int32GetDatum(dbencoding),
3326 ObjectIdGetDatum(namespaceId));
3327 if (OidIsValid(colloid))
3329 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3330 PointerGetDatum(collation_name),
3332 ObjectIdGetDatum(namespaceId));
3333 if (OidIsValid(colloid))
3338 /* search for it in search path */
3339 recomputeNamespacePath();
3341 foreach(l, activeSearchPath)
3343 namespaceId = lfirst_oid(l);
3345 if (namespaceId == myTempNamespace)
3346 continue; /* do not look in temp namespace */
3348 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3349 PointerGetDatum(collation_name),
3350 Int32GetDatum(dbencoding),
3351 ObjectIdGetDatum(namespaceId));
3352 if (OidIsValid(colloid))
3354 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3355 PointerGetDatum(collation_name),
3357 ObjectIdGetDatum(namespaceId));
3358 if (OidIsValid(colloid))
3363 /* Not found in path */
3366 (errcode(ERRCODE_UNDEFINED_OBJECT),
3367 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3368 NameListToString(name), GetDatabaseEncodingName())));
3373 * get_conversion_oid - find a conversion by possibly qualified name
3376 get_conversion_oid(List *name, bool missing_ok)
3379 char *conversion_name;
3381 Oid conoid = InvalidOid;
3384 /* deconstruct the name list */
3385 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3389 /* use exact schema given */
3390 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3391 if (missing_ok && !OidIsValid(namespaceId))
3392 conoid = InvalidOid;
3394 conoid = GetSysCacheOid2(CONNAMENSP,
3395 PointerGetDatum(conversion_name),
3396 ObjectIdGetDatum(namespaceId));
3400 /* search for it in search path */
3401 recomputeNamespacePath();
3403 foreach(l, activeSearchPath)
3405 namespaceId = lfirst_oid(l);
3407 if (namespaceId == myTempNamespace)
3408 continue; /* do not look in temp namespace */
3410 conoid = GetSysCacheOid2(CONNAMENSP,
3411 PointerGetDatum(conversion_name),
3412 ObjectIdGetDatum(namespaceId));
3413 if (OidIsValid(conoid))
3418 /* Not found in path */
3419 if (!OidIsValid(conoid) && !missing_ok)
3421 (errcode(ERRCODE_UNDEFINED_OBJECT),
3422 errmsg("conversion \"%s\" does not exist",
3423 NameListToString(name))));
3428 * FindDefaultConversionProc - find default encoding conversion proc
3431 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3436 recomputeNamespacePath();
3438 foreach(l, activeSearchPath)
3440 Oid namespaceId = lfirst_oid(l);
3442 if (namespaceId == myTempNamespace)
3443 continue; /* do not look in temp namespace */
3445 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3446 if (OidIsValid(proc))
3450 /* Not found in path */
3455 * recomputeNamespacePath - recompute path derived variables if needed.
3458 recomputeNamespacePath(void)
3460 Oid roleid = GetUserId();
3468 MemoryContext oldcxt;
3470 /* Do nothing if an override search spec is active. */
3474 /* Do nothing if path is already valid. */
3475 if (baseSearchPathValid && namespaceUser == roleid)
3478 /* Need a modifiable copy of namespace_search_path string */
3479 rawname = pstrdup(namespace_search_path);
3481 /* Parse string into list of identifiers */
3482 if (!SplitIdentifierString(rawname, ',', &namelist))
3484 /* syntax error in name list */
3485 /* this should not happen if GUC checked check_search_path */
3486 elog(ERROR, "invalid list syntax");
3490 * Convert the list of names to a list of OIDs. If any names are not
3491 * recognizable or we don't have read access, just leave them out of the
3492 * list. (We can't raise an error, since the search_path setting has
3493 * already been accepted.) Don't make duplicate entries, either.
3496 temp_missing = false;
3497 foreach(l, namelist)
3499 char *curname = (char *) lfirst(l);
3502 if (strcmp(curname, "$user") == 0)
3504 /* $user --- substitute namespace matching user name, if any */
3507 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3508 if (HeapTupleIsValid(tuple))
3512 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3513 namespaceId = get_namespace_oid(rname, true);
3514 ReleaseSysCache(tuple);
3515 if (OidIsValid(namespaceId) &&
3516 !list_member_oid(oidlist, namespaceId) &&
3517 pg_namespace_aclcheck(namespaceId, roleid,
3518 ACL_USAGE) == ACLCHECK_OK &&
3519 InvokeNamespaceSearchHook(namespaceId, false))
3520 oidlist = lappend_oid(oidlist, namespaceId);
3523 else if (strcmp(curname, "pg_temp") == 0)
3525 /* pg_temp --- substitute temp namespace, if any */
3526 if (OidIsValid(myTempNamespace))
3528 if (!list_member_oid(oidlist, myTempNamespace) &&
3529 InvokeNamespaceSearchHook(myTempNamespace, false))
3530 oidlist = lappend_oid(oidlist, myTempNamespace);
3534 /* If it ought to be the creation namespace, set flag */
3536 temp_missing = true;
3541 /* normal namespace reference */
3542 namespaceId = get_namespace_oid(curname, true);
3543 if (OidIsValid(namespaceId) &&
3544 !list_member_oid(oidlist, namespaceId) &&
3545 pg_namespace_aclcheck(namespaceId, roleid,
3546 ACL_USAGE) == ACLCHECK_OK &&
3547 InvokeNamespaceSearchHook(namespaceId, false))
3548 oidlist = lappend_oid(oidlist, namespaceId);
3553 * Remember the first member of the explicit list. (Note: this is
3554 * nominally wrong if temp_missing, but we need it anyway to distinguish
3555 * explicit from implicit mention of pg_catalog.)
3558 firstNS = InvalidOid;
3560 firstNS = linitial_oid(oidlist);
3563 * Add any implicitly-searched namespaces to the list. Note these go on
3564 * the front, not the back; also notice that we do not check USAGE
3565 * permissions for these.
3567 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3568 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3570 if (OidIsValid(myTempNamespace) &&
3571 !list_member_oid(oidlist, myTempNamespace))
3572 oidlist = lcons_oid(myTempNamespace, oidlist);
3575 * Now that we've successfully built the new list of namespace OIDs, save
3576 * it in permanent storage.
3578 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3579 newpath = list_copy(oidlist);
3580 MemoryContextSwitchTo(oldcxt);
3582 /* Now safe to assign to state variables. */
3583 list_free(baseSearchPath);
3584 baseSearchPath = newpath;
3585 baseCreationNamespace = firstNS;
3586 baseTempCreationPending = temp_missing;
3588 /* Mark the path valid. */
3589 baseSearchPathValid = true;
3590 namespaceUser = roleid;
3592 /* And make it active. */
3593 activeSearchPath = baseSearchPath;
3594 activeCreationNamespace = baseCreationNamespace;
3595 activeTempCreationPending = baseTempCreationPending;
3599 list_free(namelist);
3604 * InitTempTableNamespace
3605 * Initialize temp table namespace on first use in a particular backend
3608 InitTempTableNamespace(void)
3610 char namespaceName[NAMEDATALEN];
3614 Assert(!OidIsValid(myTempNamespace));
3617 * First, do permission check to see if we are authorized to make temp
3618 * tables. We use a nonstandard error message here since "databasename:
3619 * permission denied" might be a tad cryptic.
3621 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3622 * that's necessary since current user ID could change during the session.
3623 * But there's no need to make the namespace in the first place until a
3624 * temp table creation request is made by someone with appropriate rights.
3626 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3627 ACL_CREATE_TEMP) != ACLCHECK_OK)
3629 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3630 errmsg("permission denied to create temporary tables in database \"%s\"",
3631 get_database_name(MyDatabaseId))));
3634 * Do not allow a Hot Standby slave session to make temp tables. Aside
3635 * from problems with modifying the system catalogs, there is a naming
3636 * conflict: pg_temp_N belongs to the session with BackendId N on the
3637 * master, not to a slave session with the same BackendId. We should not
3638 * be able to get here anyway due to XactReadOnly checks, but let's just
3639 * make real sure. Note that this also backstops various operations that
3640 * allow XactReadOnly transactions to modify temp tables; they'd need
3641 * RecoveryInProgress checks if not for this.
3643 if (RecoveryInProgress())
3645 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3646 errmsg("cannot create temporary tables during recovery")));
3648 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3650 namespaceId = get_namespace_oid(namespaceName, true);
3651 if (!OidIsValid(namespaceId))
3654 * First use of this temp namespace in this database; create it. The
3655 * temp namespaces are always owned by the superuser. We leave their
3656 * permissions at default --- i.e., no access except to superuser ---
3657 * to ensure that unprivileged users can't peek at other backends'
3658 * temp tables. This works because the places that access the temp
3659 * namespace for my own backend skip permissions checks on it.
3661 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3663 /* Advance command counter to make namespace visible */
3664 CommandCounterIncrement();
3669 * If the namespace already exists, clean it out (in case the former
3670 * owner crashed without doing so).
3672 RemoveTempRelations(namespaceId);
3676 * If the corresponding toast-table namespace doesn't exist yet, create
3677 * it. (We assume there is no need to clean it out if it does exist, since
3678 * dropping a parent table should make its toast table go away.)
3680 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3683 toastspaceId = get_namespace_oid(namespaceName, true);
3684 if (!OidIsValid(toastspaceId))
3686 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3688 /* Advance command counter to make namespace visible */
3689 CommandCounterIncrement();
3693 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3694 * so all our work could be undone by transaction rollback. Set flag for
3695 * AtEOXact_Namespace to know what to do.
3697 myTempNamespace = namespaceId;
3698 myTempToastNamespace = toastspaceId;
3700 /* It should not be done already. */
3701 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3702 myTempNamespaceSubID = GetCurrentSubTransactionId();
3704 baseSearchPathValid = false; /* need to rebuild list */
3708 * End-of-transaction cleanup for namespaces.
3711 AtEOXact_Namespace(bool isCommit)
3714 * If we abort the transaction in which a temp namespace was selected,
3715 * we'll have to do any creation or cleanout work over again. So, just
3716 * forget the namespace entirely until next time. On the other hand, if
3717 * we commit then register an exit callback to clean out the temp tables
3718 * at backend shutdown. (We only want to register the callback once per
3719 * session, so this is a good place to do it.)
3721 if (myTempNamespaceSubID != InvalidSubTransactionId)
3724 before_shmem_exit(RemoveTempRelationsCallback, 0);
3727 myTempNamespace = InvalidOid;
3728 myTempToastNamespace = InvalidOid;
3729 baseSearchPathValid = false; /* need to rebuild list */
3731 myTempNamespaceSubID = InvalidSubTransactionId;
3735 * Clean up if someone failed to do PopOverrideSearchPath
3740 elog(WARNING, "leaked override search path");
3741 while (overrideStack)
3743 OverrideStackEntry *entry;
3745 entry = (OverrideStackEntry *) linitial(overrideStack);
3746 overrideStack = list_delete_first(overrideStack);
3747 list_free(entry->searchPath);
3750 /* If not baseSearchPathValid, this is useless but harmless */
3751 activeSearchPath = baseSearchPath;
3752 activeCreationNamespace = baseCreationNamespace;
3753 activeTempCreationPending = baseTempCreationPending;
3758 * AtEOSubXact_Namespace
3760 * At subtransaction commit, propagate the temp-namespace-creation
3761 * flag to the parent subtransaction.
3763 * At subtransaction abort, forget the flag if we set it up.
3766 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3767 SubTransactionId parentSubid)
3769 OverrideStackEntry *entry;
3771 if (myTempNamespaceSubID == mySubid)
3774 myTempNamespaceSubID = parentSubid;
3777 myTempNamespaceSubID = InvalidSubTransactionId;
3778 /* TEMP namespace creation failed, so reset state */
3779 myTempNamespace = InvalidOid;
3780 myTempToastNamespace = InvalidOid;
3781 baseSearchPathValid = false; /* need to rebuild list */
3786 * Clean up if someone failed to do PopOverrideSearchPath
3788 while (overrideStack)
3790 entry = (OverrideStackEntry *) linitial(overrideStack);
3791 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3794 elog(WARNING, "leaked override search path");
3795 overrideStack = list_delete_first(overrideStack);
3796 list_free(entry->searchPath);
3800 /* Activate the next level down. */
3803 entry = (OverrideStackEntry *) linitial(overrideStack);
3804 activeSearchPath = entry->searchPath;
3805 activeCreationNamespace = entry->creationNamespace;
3806 activeTempCreationPending = false; /* XXX is this OK? */
3810 /* If not baseSearchPathValid, this is useless but harmless */
3811 activeSearchPath = baseSearchPath;
3812 activeCreationNamespace = baseCreationNamespace;
3813 activeTempCreationPending = baseTempCreationPending;
3818 * Remove all relations in the specified temp namespace.
3820 * This is called at backend shutdown (if we made any temp relations).
3821 * It is also called when we begin using a pre-existing temp namespace,
3822 * in order to clean out any relations that might have been created by
3823 * a crashed backend.
3826 RemoveTempRelations(Oid tempNamespaceId)
3828 ObjectAddress object;
3831 * We want to get rid of everything in the target namespace, but not the
3832 * namespace itself (deleting it only to recreate it later would be a
3833 * waste of cycles). We do this by finding everything that has a
3834 * dependency on the namespace.
3836 object.classId = NamespaceRelationId;
3837 object.objectId = tempNamespaceId;
3838 object.objectSubId = 0;
3840 deleteWhatDependsOn(&object, false);
3844 * Callback to remove temp relations at backend exit.
3847 RemoveTempRelationsCallback(int code, Datum arg)
3849 if (OidIsValid(myTempNamespace)) /* should always be true */
3851 /* Need to ensure we have a usable transaction. */
3852 AbortOutOfAnyTransaction();
3853 StartTransactionCommand();
3855 RemoveTempRelations(myTempNamespace);
3857 CommitTransactionCommand();
3862 * Remove all temp tables from the temporary namespace.
3865 ResetTempTableNamespace(void)
3867 if (OidIsValid(myTempNamespace))
3868 RemoveTempRelations(myTempNamespace);
3873 * Routines for handling the GUC variable 'search_path'.
3876 /* check_hook: validate new search_path value */
3878 check_search_path(char **newval, void **extra, GucSource source)
3883 /* Need a modifiable copy of string */
3884 rawname = pstrdup(*newval);
3886 /* Parse string into list of identifiers */
3887 if (!SplitIdentifierString(rawname, ',', &namelist))
3889 /* syntax error in name list */
3890 GUC_check_errdetail("List syntax is invalid.");
3892 list_free(namelist);
3897 * We used to try to check that the named schemas exist, but there are
3898 * many valid use-cases for having search_path settings that include
3899 * schemas that don't exist; and often, we are not inside a transaction
3900 * here and so can't consult the system catalogs anyway. So now, the only
3901 * requirement is syntactic validity of the identifier list.
3905 list_free(namelist);
3910 /* assign_hook: do extra actions as needed */
3912 assign_search_path(const char *newval, void *extra)
3915 * We mark the path as needing recomputation, but don't do anything until
3916 * it's needed. This avoids trying to do database access during GUC
3917 * initialization, or outside a transaction.
3919 baseSearchPathValid = false;
3923 * InitializeSearchPath: initialize module during InitPostgres.
3925 * This is called after we are up enough to be able to do catalog lookups.
3928 InitializeSearchPath(void)
3930 if (IsBootstrapProcessingMode())
3933 * In bootstrap mode, the search path must be 'pg_catalog' so that
3934 * tables are created in the proper namespace; ignore the GUC setting.
3936 MemoryContext oldcxt;
3938 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3939 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3940 MemoryContextSwitchTo(oldcxt);
3941 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3942 baseTempCreationPending = false;
3943 baseSearchPathValid = true;
3944 namespaceUser = GetUserId();
3945 activeSearchPath = baseSearchPath;
3946 activeCreationNamespace = baseCreationNamespace;
3947 activeTempCreationPending = baseTempCreationPending;
3952 * In normal mode, arrange for a callback on any syscache invalidation
3953 * of pg_namespace rows.
3955 CacheRegisterSyscacheCallback(NAMESPACEOID,
3958 /* Force search path to be recomputed on next use */
3959 baseSearchPathValid = false;
3965 * Syscache inval callback function
3968 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3970 /* Force search path to be recomputed on next use */
3971 baseSearchPathValid = false;
3975 * Fetch the active search path. The return value is a palloc'ed list
3976 * of OIDs; the caller is responsible for freeing this storage as
3979 * The returned list includes the implicitly-prepended namespaces only if
3980 * includeImplicit is true.
3982 * Note: calling this may result in a CommandCounterIncrement operation,
3983 * if we have to create or clean out the temp namespace.
3986 fetch_search_path(bool includeImplicit)
3990 recomputeNamespacePath();
3993 * If the temp namespace should be first, force it to exist. This is so
3994 * that callers can trust the result to reflect the actual default
3995 * creation namespace. It's a bit bogus to do this here, since
3996 * current_schema() is supposedly a stable function without side-effects,
3997 * but the alternatives seem worse.
3999 if (activeTempCreationPending)
4001 InitTempTableNamespace();
4002 recomputeNamespacePath();
4005 result = list_copy(activeSearchPath);
4006 if (!includeImplicit)
4008 while (result && linitial_oid(result) != activeCreationNamespace)
4009 result = list_delete_first(result);
4016 * Fetch the active search path into a caller-allocated array of OIDs.
4017 * Returns the number of path entries. (If this is more than sarray_len,
4018 * then the data didn't fit and is not all stored.)
4020 * The returned list always includes the implicitly-prepended namespaces,
4021 * but never includes the temp namespace. (This is suitable for existing
4022 * users, which would want to ignore the temp namespace anyway.) This
4023 * definition allows us to not worry about initializing the temp namespace.
4026 fetch_search_path_array(Oid *sarray, int sarray_len)
4031 recomputeNamespacePath();
4033 foreach(l, activeSearchPath)
4035 Oid namespaceId = lfirst_oid(l);
4037 if (namespaceId == myTempNamespace)
4038 continue; /* do not include temp namespace */
4040 if (count < sarray_len)
4041 sarray[count] = namespaceId;
4050 * Export the FooIsVisible functions as SQL-callable functions.
4052 * Note: as of Postgres 8.4, these will silently return NULL if called on
4053 * a nonexistent object OID, rather than failing. This is to avoid race
4054 * condition errors when a query that's scanning a catalog using an MVCC
4055 * snapshot uses one of these functions. The underlying IsVisible functions
4056 * always use an up-to-date snapshot and so might see the object as already
4057 * gone when it's still visible to the transaction snapshot. (There is no race
4058 * condition in the current coding because we don't accept sinval messages
4059 * between the SearchSysCacheExists test and the subsequent lookup.)
4063 pg_table_is_visible(PG_FUNCTION_ARGS)
4065 Oid oid = PG_GETARG_OID(0);
4067 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
4070 PG_RETURN_BOOL(RelationIsVisible(oid));
4074 pg_type_is_visible(PG_FUNCTION_ARGS)
4076 Oid oid = PG_GETARG_OID(0);
4078 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
4081 PG_RETURN_BOOL(TypeIsVisible(oid));
4085 pg_function_is_visible(PG_FUNCTION_ARGS)
4087 Oid oid = PG_GETARG_OID(0);
4089 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
4092 PG_RETURN_BOOL(FunctionIsVisible(oid));
4096 pg_operator_is_visible(PG_FUNCTION_ARGS)
4098 Oid oid = PG_GETARG_OID(0);
4100 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4103 PG_RETURN_BOOL(OperatorIsVisible(oid));
4107 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4109 Oid oid = PG_GETARG_OID(0);
4111 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4114 PG_RETURN_BOOL(OpclassIsVisible(oid));
4118 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4120 Oid oid = PG_GETARG_OID(0);
4122 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4125 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4129 pg_collation_is_visible(PG_FUNCTION_ARGS)
4131 Oid oid = PG_GETARG_OID(0);
4133 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4136 PG_RETURN_BOOL(CollationIsVisible(oid));
4140 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4142 Oid oid = PG_GETARG_OID(0);
4144 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4147 PG_RETURN_BOOL(ConversionIsVisible(oid));
4151 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4153 Oid oid = PG_GETARG_OID(0);
4155 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4158 PG_RETURN_BOOL(TSParserIsVisible(oid));
4162 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4164 Oid oid = PG_GETARG_OID(0);
4166 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4169 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4173 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4175 Oid oid = PG_GETARG_OID(0);
4177 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4180 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4184 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4186 Oid oid = PG_GETARG_OID(0);
4188 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4191 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4195 pg_my_temp_schema(PG_FUNCTION_ARGS)
4197 PG_RETURN_OID(myTempNamespace);
4201 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4203 Oid oid = PG_GETARG_OID(0);
4205 PG_RETURN_BOOL(isOtherTempNamespace(oid));