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 "catalog/dependency.h"
25 #include "catalog/objectaccess.h"
26 #include "catalog/pg_authid.h"
27 #include "catalog/pg_collation.h"
28 #include "catalog/pg_conversion.h"
29 #include "catalog/pg_conversion_fn.h"
30 #include "catalog/pg_namespace.h"
31 #include "catalog/pg_opclass.h"
32 #include "catalog/pg_operator.h"
33 #include "catalog/pg_opfamily.h"
34 #include "catalog/pg_proc.h"
35 #include "catalog/pg_ts_config.h"
36 #include "catalog/pg_ts_dict.h"
37 #include "catalog/pg_ts_parser.h"
38 #include "catalog/pg_ts_template.h"
39 #include "catalog/pg_type.h"
40 #include "commands/dbcommands.h"
42 #include "mb/pg_wchar.h"
43 #include "miscadmin.h"
44 #include "nodes/makefuncs.h"
45 #include "parser/parse_func.h"
46 #include "storage/ipc.h"
47 #include "storage/lmgr.h"
48 #include "storage/sinval.h"
49 #include "utils/acl.h"
50 #include "utils/builtins.h"
51 #include "utils/catcache.h"
52 #include "utils/guc.h"
53 #include "utils/inval.h"
54 #include "utils/lsyscache.h"
55 #include "utils/memutils.h"
56 #include "utils/syscache.h"
60 * The namespace search path is a possibly-empty list of namespace OIDs.
61 * In addition to the explicit list, implicitly-searched namespaces
64 * 1. If a TEMP table namespace has been initialized in this session, it
65 * is implicitly searched first. (The only time this doesn't happen is
66 * when we are obeying an override search path spec that says not to use the
67 * temp namespace, or the temp namespace is included in the explicit list.)
69 * 2. The system catalog namespace is always searched. If the system
70 * namespace is present in the explicit path then it will be searched in
71 * the specified order; otherwise it will be searched after TEMP tables and
72 * *before* the explicit list. (It might seem that the system namespace
73 * should be implicitly last, but this behavior appears to be required by
74 * SQL99. Also, this provides a way to search the system namespace first
75 * without thereby making it the default creation target namespace.)
77 * For security reasons, searches using the search path will ignore the temp
78 * namespace when searching for any object type other than relations and
79 * types. (We must allow types since temp tables have rowtypes.)
81 * The default creation target namespace is always the first element of the
82 * explicit list. If the explicit list is empty, there is no default target.
84 * The textual specification of search_path can include "$user" to refer to
85 * the namespace named the same as the current user, if any. (This is just
86 * ignored if there is no such namespace.) Also, it can include "pg_temp"
87 * to refer to the current backend's temp namespace. This is usually also
88 * ignorable if the temp namespace hasn't been set up, but there's a special
89 * case: if "pg_temp" appears first then it should be the default creation
90 * target. We kluge this case a little bit so that the temp namespace isn't
91 * set up until the first attempt to create something in it. (The reason for
92 * klugery is that we can't create the temp namespace outside a transaction,
93 * but initial GUC processing of search_path happens outside a transaction.)
94 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
95 * but is not reflected in activeCreationNamespace because the namespace isn't
98 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
99 * the system namespace is the only one searched or inserted into.
100 * initdb is also careful to set search_path to "pg_catalog" for its
101 * post-bootstrap standalone backend runs. Otherwise the default search
102 * path is determined by GUC. The factory default path contains the PUBLIC
103 * namespace (if it exists), preceded by the user's personal namespace
106 * We support a stack of "override" search path settings for use within
107 * specific sections of backend code. namespace_search_path is ignored
108 * whenever the override stack is nonempty. activeSearchPath is always
109 * the actually active path; it points either to the search list of the
110 * topmost stack entry, or to baseSearchPath which is the list derived
111 * from namespace_search_path.
113 * If baseSearchPathValid is false, then baseSearchPath (and other
114 * derived variables) need to be recomputed from namespace_search_path.
115 * We mark it invalid upon an assignment to namespace_search_path or receipt
116 * of a syscache invalidation event for pg_namespace. The recomputation
117 * is done during the next non-overridden lookup attempt. Note that an
118 * override spec is never subject to recomputation.
120 * Any namespaces mentioned in namespace_search_path that are not readable
121 * by the current user ID are simply left out of baseSearchPath; so
122 * we have to be willing to recompute the path when current userid changes.
123 * namespaceUser is the userid the path has been computed for.
125 * Note: all data pointed to by these List variables is in TopMemoryContext.
128 /* These variables define the actually active state: */
130 static List *activeSearchPath = NIL;
132 /* default place to create stuff; if InvalidOid, no default */
133 static Oid activeCreationNamespace = InvalidOid;
135 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
136 static bool activeTempCreationPending = false;
138 /* These variables are the values last derived from namespace_search_path: */
140 static List *baseSearchPath = NIL;
142 static Oid baseCreationNamespace = InvalidOid;
144 static bool baseTempCreationPending = false;
146 static Oid namespaceUser = InvalidOid;
148 /* The above four values are valid only if baseSearchPathValid */
149 static bool baseSearchPathValid = true;
151 /* Override requests are remembered in a stack of OverrideStackEntry structs */
155 List *searchPath; /* the desired search path */
156 Oid creationNamespace; /* the desired creation namespace */
157 int nestLevel; /* subtransaction nesting level */
158 } OverrideStackEntry;
160 static List *overrideStack = NIL;
163 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
164 * in a particular backend session (this happens when a CREATE TEMP TABLE
165 * command is first executed). Thereafter it's the OID of the temp namespace.
167 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
168 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
170 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
171 * current subtransaction. The flag propagates up the subtransaction tree,
172 * so the main transaction will correctly recognize the flag if all
173 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
174 * we either haven't made the TEMP namespace yet, or have successfully
175 * committed its creation, depending on whether myTempNamespace is valid.
177 static Oid myTempNamespace = InvalidOid;
179 static Oid myTempToastNamespace = InvalidOid;
181 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
184 * This is the user's textual search path specification --- it's the value
185 * of the GUC variable 'search_path'.
187 char *namespace_search_path = NULL;
190 /* Local functions */
191 static void recomputeNamespacePath(void);
192 static void InitTempTableNamespace(void);
193 static void RemoveTempRelations(Oid tempNamespaceId);
194 static void RemoveTempRelationsCallback(int code, Datum arg);
195 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
196 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
199 /* These don't really need to appear in any header file */
200 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
210 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
211 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
212 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
213 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
218 * Given a RangeVar describing an existing relation,
219 * select the proper namespace and look up the relation OID.
221 * If the schema or relation is not found, return InvalidOid if missing_ok
222 * = true, otherwise raise an error.
224 * If nowait = true, throw an error if we'd have to wait for a lock.
226 * Callback allows caller to check permissions or acquire additional locks
227 * prior to grabbing the relation lock.
230 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
231 bool missing_ok, bool nowait,
232 RangeVarGetRelidCallback callback, void *callback_arg)
236 Oid oldRelId = InvalidOid;
240 * We check the catalog name and then ignore it.
242 if (relation->catalogname)
244 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
246 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
247 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
248 relation->catalogname, relation->schemaname,
249 relation->relname)));
253 * DDL operations can change the results of a name lookup. Since all such
254 * operations will generate invalidation messages, we keep track of
255 * whether any such messages show up while we're performing the operation,
256 * and retry until either (1) no more invalidation messages show up or (2)
257 * the answer doesn't change.
259 * But if lockmode = NoLock, then we assume that either the caller is OK
260 * with the answer changing under them, or that they already hold some
261 * appropriate lock, and therefore return the first answer we get without
262 * checking for invalidation messages. Also, if the requested lock is
263 * already held, no LockRelationOid will not AcceptInvalidationMessages,
264 * so we may fail to notice a change. We could protect against that case
265 * by calling AcceptInvalidationMessages() before beginning this loop, but
266 * that would add a significant amount overhead, so for now we don't.
271 * Remember this value, so that, after looking up the relation name
272 * and locking its OID, we can check whether any invalidation messages
273 * have been processed that might require a do-over.
275 inval_count = SharedInvalidMessageCounter;
278 * Some non-default relpersistence value may have been specified. The
279 * parser never generates such a RangeVar in simple DML, but it can
280 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
281 * KEY)". Such a command will generate an added CREATE INDEX
282 * operation, which must be careful to find the temp table, even when
283 * pg_temp is not first in the search path.
285 if (relation->relpersistence == RELPERSISTENCE_TEMP)
287 if (!OidIsValid(myTempNamespace))
288 relId = InvalidOid; /* this probably can't happen? */
291 if (relation->schemaname)
295 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
298 * For missing_ok, allow a non-existant schema name to
301 if (namespaceId != myTempNamespace)
303 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
304 errmsg("temporary tables cannot specify a schema name")));
307 relId = get_relname_relid(relation->relname, myTempNamespace);
310 else if (relation->schemaname)
314 /* use exact schema given */
315 namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
316 if (missing_ok && !OidIsValid(namespaceId))
319 relId = get_relname_relid(relation->relname, namespaceId);
323 /* search the namespace path */
324 relId = RelnameGetRelid(relation->relname);
328 * Invoke caller-supplied callback, if any.
330 * This callback is a good place to check permissions: we haven't
331 * taken the table lock yet (and it's really best to check permissions
332 * before locking anything!), but we've gotten far enough to know what
333 * OID we think we should lock. Of course, concurrent DDL might
334 * change things while we're waiting for the lock, but in that case
335 * the callback will be invoked again for the new OID.
338 callback(relation, relId, oldRelId, callback_arg);
341 * If no lock requested, we assume the caller knows what they're
342 * doing. They should have already acquired a heavyweight lock on
343 * this relation earlier in the processing of this same statement, so
344 * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
345 * that might pull the rug out from under them.
347 if (lockmode == NoLock)
351 * If, upon retry, we get back the same OID we did last time, then the
352 * invalidation messages we processed did not change the final answer.
355 * If we got a different OID, we've locked the relation that used to
356 * have this name rather than the one that does now. So release the
361 if (relId == oldRelId)
363 if (OidIsValid(oldRelId))
364 UnlockRelationOid(oldRelId, lockmode);
368 * Lock relation. This will also accept any pending invalidation
369 * messages. If we got back InvalidOid, indicating not found, then
370 * there's nothing to lock, but we accept invalidation messages
371 * anyway, to flush any negative catcache entries that may be
374 if (!OidIsValid(relId))
375 AcceptInvalidationMessages();
377 LockRelationOid(relId, lockmode);
378 else if (!ConditionalLockRelationOid(relId, lockmode))
380 if (relation->schemaname)
382 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
383 errmsg("could not obtain lock on relation \"%s.%s\"",
384 relation->schemaname, relation->relname)));
387 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
388 errmsg("could not obtain lock on relation \"%s\"",
389 relation->relname)));
393 * If no invalidation message were processed, we're done!
395 if (inval_count == SharedInvalidMessageCounter)
399 * Something may have changed. Let's repeat the name lookup, to make
400 * sure this name still references the same relation it did
407 if (!OidIsValid(relId) && !missing_ok)
409 if (relation->schemaname)
411 (errcode(ERRCODE_UNDEFINED_TABLE),
412 errmsg("relation \"%s.%s\" does not exist",
413 relation->schemaname, relation->relname)));
416 (errcode(ERRCODE_UNDEFINED_TABLE),
417 errmsg("relation \"%s\" does not exist",
418 relation->relname)));
424 * RangeVarGetCreationNamespace
425 * Given a RangeVar describing a to-be-created relation,
426 * choose which namespace to create it in.
428 * Note: calling this may result in a CommandCounterIncrement operation.
429 * That will happen on the first request for a temp table in any particular
430 * backend run; we will need to either create or clean out the temp schema.
433 RangeVarGetCreationNamespace(const RangeVar *newRelation)
438 * We check the catalog name and then ignore it.
440 if (newRelation->catalogname)
442 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
444 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
445 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
446 newRelation->catalogname, newRelation->schemaname,
447 newRelation->relname)));
450 if (newRelation->schemaname)
452 /* check for pg_temp alias */
453 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
455 /* Initialize temp namespace if first time through */
456 if (!OidIsValid(myTempNamespace))
457 InitTempTableNamespace();
458 return myTempNamespace;
460 /* use exact schema given */
461 namespaceId = get_namespace_oid(newRelation->schemaname, false);
462 /* we do not check for USAGE rights here! */
464 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
466 /* Initialize temp namespace if first time through */
467 if (!OidIsValid(myTempNamespace))
468 InitTempTableNamespace();
469 return myTempNamespace;
473 /* use the default creation namespace */
474 recomputeNamespacePath();
475 if (activeTempCreationPending)
477 /* Need to initialize temp namespace */
478 InitTempTableNamespace();
479 return myTempNamespace;
481 namespaceId = activeCreationNamespace;
482 if (!OidIsValid(namespaceId))
484 (errcode(ERRCODE_UNDEFINED_SCHEMA),
485 errmsg("no schema has been selected to create in")));
488 /* Note: callers will check for CREATE rights when appropriate */
494 * RangeVarGetAndCheckCreationNamespace
496 * This function returns the OID of the namespace in which a new relation
497 * with a given name should be created. If the user does not have CREATE
498 * permission on the target namespace, this function will instead signal
501 * If non-NULL, *existing_oid is set to the OID of any existing relation with
502 * the same name which already exists in that namespace, or to InvalidOid if
503 * no such relation exists.
505 * If lockmode != NoLock, the specified lock mode is acquire on the existing
506 * relation, if any, provided that the current user owns the target relation.
507 * However, if lockmode != NoLock and the user does not own the target
508 * relation, we throw an ERROR, as we must not try to lock relations the
509 * user does not have permissions on.
511 * As a side effect, this function acquires AccessShareLock on the target
512 * namespace. Without this, the namespace could be dropped before our
513 * transaction commits, leaving behind relations with relnamespace pointing
514 * to a no-longer-exstant namespace.
516 * As a further side-effect, if the select namespace is a temporary namespace,
517 * we mark the RangeVar as RELPERSISTENCE_TEMP.
520 RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
522 Oid *existing_relation_id)
526 Oid oldrelid = InvalidOid;
528 Oid oldnspid = InvalidOid;
532 * We check the catalog name and then ignore it.
534 if (relation->catalogname)
536 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
538 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
539 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
540 relation->catalogname, relation->schemaname,
541 relation->relname)));
545 * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
546 * operations by tracking whether any invalidation messages are processed
547 * while we're doing the name lookups and acquiring locks. See comments
548 * in that function for a more detailed explanation of this logic.
554 inval_count = SharedInvalidMessageCounter;
556 /* Look up creation namespace and check for existing relation. */
557 nspid = RangeVarGetCreationNamespace(relation);
558 Assert(OidIsValid(nspid));
559 if (existing_relation_id != NULL)
560 relid = get_relname_relid(relation->relname, nspid);
565 * In bootstrap processing mode, we don't bother with permissions or
566 * locking. Permissions might not be working yet, and locking is
569 if (IsBootstrapProcessingMode())
572 /* Check namespace permissions. */
573 aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
574 if (aclresult != ACLCHECK_OK)
575 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
576 get_namespace_name(nspid));
580 /* If nothing changed, we're done. */
581 if (relid == oldrelid && nspid == oldnspid)
583 /* If creation namespace has changed, give up old lock. */
584 if (nspid != oldnspid)
585 UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
587 /* If name points to something different, give up old lock. */
588 if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
589 UnlockRelationOid(oldrelid, lockmode);
592 /* Lock namespace. */
593 if (nspid != oldnspid)
594 LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
596 /* Lock relation, if required if and we have permission. */
597 if (lockmode != NoLock && OidIsValid(relid))
599 if (!pg_class_ownercheck(relid, GetUserId()))
600 aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
602 if (relid != oldrelid)
603 LockRelationOid(relid, lockmode);
606 /* If no invalidation message were processed, we're done! */
607 if (inval_count == SharedInvalidMessageCounter)
610 /* Something may have changed, so recheck our work. */
616 RangeVarAdjustRelationPersistence(relation, nspid);
617 if (existing_relation_id != NULL)
618 *existing_relation_id = relid;
623 * Adjust the relpersistence for an about-to-be-created relation based on the
624 * creation namespace, and throw an error for invalid combinations.
627 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
629 switch (newRelation->relpersistence)
631 case RELPERSISTENCE_TEMP:
632 if (!isTempOrToastNamespace(nspid))
634 if (isAnyTempNamespace(nspid))
636 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
637 errmsg("cannot create relations in temporary schemas of other sessions")));
640 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
641 errmsg("cannot create temporary relation in non-temporary schema")));
644 case RELPERSISTENCE_PERMANENT:
645 if (isTempOrToastNamespace(nspid))
646 newRelation->relpersistence = RELPERSISTENCE_TEMP;
647 else if (isAnyTempNamespace(nspid))
649 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
650 errmsg("cannot create relations in temporary schemas of other sessions")));
653 if (isAnyTempNamespace(nspid))
655 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
656 errmsg("only temporary relations may be created in temporary schemas")));
662 * Try to resolve an unqualified relation name.
663 * Returns OID if relation found in search path, else InvalidOid.
666 RelnameGetRelid(const char *relname)
671 recomputeNamespacePath();
673 foreach(l, activeSearchPath)
675 Oid namespaceId = lfirst_oid(l);
677 relid = get_relname_relid(relname, namespaceId);
678 if (OidIsValid(relid))
682 /* Not found in path */
689 * Determine whether a relation (identified by OID) is visible in the
690 * current search path. Visible means "would be found by searching
691 * for the unqualified relation name".
694 RelationIsVisible(Oid relid)
697 Form_pg_class relform;
701 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
702 if (!HeapTupleIsValid(reltup))
703 elog(ERROR, "cache lookup failed for relation %u", relid);
704 relform = (Form_pg_class) GETSTRUCT(reltup);
706 recomputeNamespacePath();
709 * Quick check: if it ain't in the path at all, it ain't visible. Items in
710 * the system namespace are surely in the path and so we needn't even do
711 * list_member_oid() for them.
713 relnamespace = relform->relnamespace;
714 if (relnamespace != PG_CATALOG_NAMESPACE &&
715 !list_member_oid(activeSearchPath, relnamespace))
720 * If it is in the path, it might still not be visible; it could be
721 * hidden by another relation of the same name earlier in the path. So
722 * we must do a slow check for conflicting relations.
724 char *relname = NameStr(relform->relname);
728 foreach(l, activeSearchPath)
730 Oid namespaceId = lfirst_oid(l);
732 if (namespaceId == relnamespace)
734 /* Found it first in path */
738 if (OidIsValid(get_relname_relid(relname, namespaceId)))
740 /* Found something else first in path */
746 ReleaseSysCache(reltup);
754 * Try to resolve an unqualified datatype name.
755 * Returns OID if type found in search path, else InvalidOid.
757 * This is essentially the same as RelnameGetRelid.
760 TypenameGetTypid(const char *typname)
765 recomputeNamespacePath();
767 foreach(l, activeSearchPath)
769 Oid namespaceId = lfirst_oid(l);
771 typid = GetSysCacheOid2(TYPENAMENSP,
772 PointerGetDatum(typname),
773 ObjectIdGetDatum(namespaceId));
774 if (OidIsValid(typid))
778 /* Not found in path */
784 * Determine whether a type (identified by OID) is visible in the
785 * current search path. Visible means "would be found by searching
786 * for the unqualified type name".
789 TypeIsVisible(Oid typid)
792 Form_pg_type typform;
796 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
797 if (!HeapTupleIsValid(typtup))
798 elog(ERROR, "cache lookup failed for type %u", typid);
799 typform = (Form_pg_type) GETSTRUCT(typtup);
801 recomputeNamespacePath();
804 * Quick check: if it ain't in the path at all, it ain't visible. Items in
805 * the system namespace are surely in the path and so we needn't even do
806 * list_member_oid() for them.
808 typnamespace = typform->typnamespace;
809 if (typnamespace != PG_CATALOG_NAMESPACE &&
810 !list_member_oid(activeSearchPath, typnamespace))
815 * If it is in the path, it might still not be visible; it could be
816 * hidden by another type of the same name earlier in the path. So we
817 * must do a slow check for conflicting types.
819 char *typname = NameStr(typform->typname);
823 foreach(l, activeSearchPath)
825 Oid namespaceId = lfirst_oid(l);
827 if (namespaceId == typnamespace)
829 /* Found it first in path */
833 if (SearchSysCacheExists2(TYPENAMENSP,
834 PointerGetDatum(typname),
835 ObjectIdGetDatum(namespaceId)))
837 /* Found something else first in path */
843 ReleaseSysCache(typtup);
850 * FuncnameGetCandidates
851 * Given a possibly-qualified function name and argument count,
852 * retrieve a list of the possible matches.
854 * If nargs is -1, we return all functions matching the given name,
855 * regardless of argument count. (argnames must be NIL, and expand_variadic
856 * and expand_defaults must be false, in this case.)
858 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
859 * and only functions having all the listed argument names will be returned.
860 * (We assume that length(argnames) <= nargs and all the passed-in names are
861 * distinct.) The returned structs will include an argnumbers array showing
862 * the actual argument index for each logical argument position.
864 * If expand_variadic is true, then variadic functions having the same number
865 * or fewer arguments will be retrieved, with the variadic argument and any
866 * additional argument positions filled with the variadic element type.
867 * nvargs in the returned struct is set to the number of such arguments.
868 * If expand_variadic is false, variadic arguments are not treated specially,
869 * and the returned nvargs will always be zero.
871 * If expand_defaults is true, functions that could match after insertion of
872 * default argument values will also be retrieved. In this case the returned
873 * structs could have nargs > passed-in nargs, and ndargs is set to the number
874 * of additional args (which can be retrieved from the function's
875 * proargdefaults entry).
877 * It is not possible for nvargs and ndargs to both be nonzero in the same
878 * list entry, since default insertion allows matches to functions with more
879 * than nargs arguments while the variadic transformation requires the same
882 * When argnames isn't NIL, the returned args[] type arrays are not ordered
883 * according to the functions' declarations, but rather according to the call:
884 * first any positional arguments, then the named arguments, then defaulted
885 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
886 * array can be used to map this back to the catalog information.
887 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
889 * We search a single namespace if the function name is qualified, else
890 * all namespaces in the search path. In the multiple-namespace case,
891 * we arrange for entries in earlier namespaces to mask identical entries in
894 * When expanding variadics, we arrange for non-variadic functions to mask
895 * variadic ones if the expanded argument list is the same. It is still
896 * possible for there to be conflicts between different variadic functions,
899 * It is guaranteed that the return list will never contain multiple entries
900 * with identical argument lists. When expand_defaults is true, the entries
901 * could have more than nargs positions, but we still guarantee that they are
902 * distinct in the first nargs positions. However, if argnames isn't NIL or
903 * either expand_variadic or expand_defaults is true, there might be multiple
904 * candidate functions that expand to identical argument lists. Rather than
905 * throw error here, we report such situations by returning a single entry
906 * with oid = 0 that represents a set of such conflicting candidates.
907 * The caller might end up discarding such an entry anyway, but if it selects
908 * such an entry it should react as though the call were ambiguous.
910 * If missing_ok is true, an empty list (NULL) is returned if the name was
911 * schema- qualified with a schema that does not exist. Likewise if no
912 * candidate is found for other reasons.
915 FuncnameGetCandidates(List *names, int nargs, List *argnames,
916 bool expand_variadic, bool expand_defaults,
919 FuncCandidateList resultList = NULL;
920 bool any_special = false;
927 /* check for caller error */
928 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
930 /* deconstruct the name list */
931 DeconstructQualifiedName(names, &schemaname, &funcname);
935 /* use exact schema given */
936 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
937 if (!OidIsValid(namespaceId))
942 /* flag to indicate we need namespace search */
943 namespaceId = InvalidOid;
944 recomputeNamespacePath();
947 /* Search syscache by name only */
948 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
950 for (i = 0; i < catlist->n_members; i++)
952 HeapTuple proctup = &catlist->members[i]->tuple;
953 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
954 int pronargs = procform->pronargs;
960 int *argnumbers = NULL;
961 FuncCandidateList newResult;
963 if (OidIsValid(namespaceId))
965 /* Consider only procs in specified namespace */
966 if (procform->pronamespace != namespaceId)
972 * Consider only procs that are in the search path and are not in
973 * the temp namespace.
977 foreach(nsp, activeSearchPath)
979 if (procform->pronamespace == lfirst_oid(nsp) &&
980 procform->pronamespace != myTempNamespace)
985 continue; /* proc is not in search path */
991 * Call uses named or mixed notation
993 * Named or mixed notation can match a variadic function only if
994 * expand_variadic is off; otherwise there is no way to match the
995 * presumed-nameless parameters expanded from the variadic array.
997 if (OidIsValid(procform->provariadic) && expand_variadic)
999 va_elem_type = InvalidOid;
1003 * Check argument count.
1005 Assert(nargs >= 0); /* -1 not supported with argnames */
1007 if (pronargs > nargs && expand_defaults)
1009 /* Ignore if not enough default expressions */
1010 if (nargs + procform->pronargdefaults < pronargs)
1012 use_defaults = true;
1015 use_defaults = false;
1017 /* Ignore if it doesn't match requested argument count */
1018 if (pronargs != nargs && !use_defaults)
1021 /* Check for argument name match, generate positional mapping */
1022 if (!MatchNamedCall(proctup, nargs, argnames,
1026 /* Named argument matching is always "special" */
1032 * Call uses positional notation
1034 * Check if function is variadic, and get variadic element type if
1035 * so. If expand_variadic is false, we should just ignore
1038 if (pronargs <= nargs && expand_variadic)
1040 va_elem_type = procform->provariadic;
1041 variadic = OidIsValid(va_elem_type);
1042 any_special |= variadic;
1046 va_elem_type = InvalidOid;
1051 * Check if function can match by using parameter defaults.
1053 if (pronargs > nargs && expand_defaults)
1055 /* Ignore if not enough default expressions */
1056 if (nargs + procform->pronargdefaults < pronargs)
1058 use_defaults = true;
1062 use_defaults = false;
1064 /* Ignore if it doesn't match requested argument count */
1065 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1070 * We must compute the effective argument list so that we can easily
1071 * compare it to earlier results. We waste a palloc cycle if it gets
1072 * masked by an earlier result, but really that's a pretty infrequent
1073 * case so it's not worth worrying about.
1075 effective_nargs = Max(pronargs, nargs);
1076 newResult = (FuncCandidateList)
1077 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
1078 + effective_nargs * sizeof(Oid));
1079 newResult->pathpos = pathpos;
1080 newResult->oid = HeapTupleGetOid(proctup);
1081 newResult->nargs = effective_nargs;
1082 newResult->argnumbers = argnumbers;
1085 /* Re-order the argument types into call's logical order */
1086 Oid *proargtypes = procform->proargtypes.values;
1089 for (i = 0; i < pronargs; i++)
1090 newResult->args[i] = proargtypes[argnumbers[i]];
1094 /* Simple positional case, just copy proargtypes as-is */
1095 memcpy(newResult->args, procform->proargtypes.values,
1096 pronargs * sizeof(Oid));
1102 newResult->nvargs = effective_nargs - pronargs + 1;
1103 /* Expand variadic argument into N copies of element type */
1104 for (i = pronargs - 1; i < effective_nargs; i++)
1105 newResult->args[i] = va_elem_type;
1108 newResult->nvargs = 0;
1109 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1112 * Does it have the same arguments as something we already accepted?
1113 * If so, decide what to do to avoid returning duplicate argument
1114 * lists. We can skip this check for the single-namespace case if no
1115 * special (named, variadic or defaults) match has been made, since
1116 * then the unique index on pg_proc guarantees all the matches have
1117 * different argument lists.
1119 if (resultList != NULL &&
1120 (any_special || !OidIsValid(namespaceId)))
1123 * If we have an ordered list from SearchSysCacheList (the normal
1124 * case), then any conflicting proc must immediately adjoin this
1125 * one in the list, so we only need to look at the newest result
1126 * item. If we have an unordered list, we have to scan the whole
1127 * result list. Also, if either the current candidate or any
1128 * previous candidate is a special match, we can't assume that
1129 * conflicts are adjacent.
1131 * We ignore defaulted arguments in deciding what is a match.
1133 FuncCandidateList prevResult;
1135 if (catlist->ordered && !any_special)
1137 /* ndargs must be 0 if !any_special */
1138 if (effective_nargs == resultList->nargs &&
1139 memcmp(newResult->args,
1141 effective_nargs * sizeof(Oid)) == 0)
1142 prevResult = resultList;
1148 int cmp_nargs = newResult->nargs - newResult->ndargs;
1150 for (prevResult = resultList;
1152 prevResult = prevResult->next)
1154 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1155 memcmp(newResult->args,
1157 cmp_nargs * sizeof(Oid)) == 0)
1165 * We have a match with a previous result. Decide which one
1166 * to keep, or mark it ambiguous if we can't decide. The
1167 * logic here is preference > 0 means prefer the old result,
1168 * preference < 0 means prefer the new, preference = 0 means
1173 if (pathpos != prevResult->pathpos)
1176 * Prefer the one that's earlier in the search path.
1178 preference = pathpos - prevResult->pathpos;
1180 else if (variadic && prevResult->nvargs == 0)
1183 * With variadic functions we could have, for example,
1184 * both foo(numeric) and foo(variadic numeric[]) in the
1185 * same namespace; if so we prefer the non-variadic match
1186 * on efficiency grounds.
1190 else if (!variadic && prevResult->nvargs > 0)
1197 * We can't decide. This can happen with, for example,
1198 * both foo(numeric, variadic numeric[]) and
1199 * foo(variadic numeric[]) in the same namespace, or
1200 * both foo(int) and foo (int, int default something)
1201 * in the same namespace, or both foo(a int, b text)
1202 * and foo(b text, a int) in the same namespace.
1210 /* keep previous result */
1214 else if (preference < 0)
1216 /* remove previous result from the list */
1217 if (prevResult == resultList)
1218 resultList = prevResult->next;
1221 FuncCandidateList prevPrevResult;
1223 for (prevPrevResult = resultList;
1225 prevPrevResult = prevPrevResult->next)
1227 if (prevResult == prevPrevResult->next)
1229 prevPrevResult->next = prevResult->next;
1233 Assert(prevPrevResult); /* assert we found it */
1236 /* fall through to add newResult to list */
1240 /* mark old result as ambiguous, discard new */
1241 prevResult->oid = InvalidOid;
1249 * Okay to add it to result list
1251 newResult->next = resultList;
1252 resultList = newResult;
1255 ReleaseSysCacheList(catlist);
1262 * Given a pg_proc heap tuple and a call's list of argument names,
1263 * check whether the function could match the call.
1265 * The call could match if all supplied argument names are accepted by
1266 * the function, in positions after the last positional argument, and there
1267 * are defaults for all unsupplied arguments.
1269 * The number of positional arguments is nargs - list_length(argnames).
1270 * Note caller has already done basic checks on argument count.
1272 * On match, return true and fill *argnumbers with a palloc'd array showing
1273 * the mapping from call argument positions to actual function argument
1274 * numbers. Defaulted arguments are included in this map, at positions
1275 * after the last supplied argument.
1278 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1281 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1282 int pronargs = procform->pronargs;
1283 int numposargs = nargs - list_length(argnames);
1288 bool arggiven[FUNC_MAX_ARGS];
1290 int ap; /* call args position */
1291 int pp; /* proargs position */
1294 Assert(argnames != NIL);
1295 Assert(numposargs >= 0);
1296 Assert(nargs <= pronargs);
1298 /* Ignore this function if its proargnames is null */
1299 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1304 /* OK, let's extract the argument names and types */
1305 pronallargs = get_func_arg_info(proctup,
1306 &p_argtypes, &p_argnames, &p_argmodes);
1307 Assert(p_argnames != NULL);
1309 /* initialize state for matching */
1310 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1311 memset(arggiven, false, pronargs * sizeof(bool));
1313 /* there are numposargs positional args before the named args */
1314 for (ap = 0; ap < numposargs; ap++)
1316 (*argnumbers)[ap] = ap;
1317 arggiven[ap] = true;
1320 /* now examine the named args */
1321 foreach(lc, argnames)
1323 char *argname = (char *) lfirst(lc);
1329 for (i = 0; i < pronallargs; i++)
1331 /* consider only input parameters */
1333 (p_argmodes[i] != FUNC_PARAM_IN &&
1334 p_argmodes[i] != FUNC_PARAM_INOUT &&
1335 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1337 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1339 /* fail if argname matches a positional argument */
1342 arggiven[pp] = true;
1343 (*argnumbers)[ap] = pp;
1347 /* increase pp only for input parameters */
1350 /* if name isn't in proargnames, fail */
1356 Assert(ap == nargs); /* processed all actual parameters */
1358 /* Check for default arguments */
1359 if (nargs < pronargs)
1361 int first_arg_with_default = pronargs - procform->pronargdefaults;
1363 for (pp = numposargs; pp < pronargs; pp++)
1367 /* fail if arg not given and no default available */
1368 if (pp < first_arg_with_default)
1370 (*argnumbers)[ap++] = pp;
1374 Assert(ap == pronargs); /* processed all function parameters */
1381 * Determine whether a function (identified by OID) is visible in the
1382 * current search path. Visible means "would be found by searching
1383 * for the unqualified function name with exact argument matches".
1386 FunctionIsVisible(Oid funcid)
1389 Form_pg_proc procform;
1393 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1394 if (!HeapTupleIsValid(proctup))
1395 elog(ERROR, "cache lookup failed for function %u", funcid);
1396 procform = (Form_pg_proc) GETSTRUCT(proctup);
1398 recomputeNamespacePath();
1401 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1402 * the system namespace are surely in the path and so we needn't even do
1403 * list_member_oid() for them.
1405 pronamespace = procform->pronamespace;
1406 if (pronamespace != PG_CATALOG_NAMESPACE &&
1407 !list_member_oid(activeSearchPath, pronamespace))
1412 * If it is in the path, it might still not be visible; it could be
1413 * hidden by another proc of the same name and arguments earlier in
1414 * the path. So we must do a slow check to see if this is the same
1415 * proc that would be found by FuncnameGetCandidates.
1417 char *proname = NameStr(procform->proname);
1418 int nargs = procform->pronargs;
1419 FuncCandidateList clist;
1423 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1424 nargs, NIL, false, false, false);
1426 for (; clist; clist = clist->next)
1428 if (memcmp(clist->args, procform->proargtypes.values,
1429 nargs * sizeof(Oid)) == 0)
1431 /* Found the expected entry; is it the right proc? */
1432 visible = (clist->oid == funcid);
1438 ReleaseSysCache(proctup);
1446 * Given a possibly-qualified operator name and exact input datatypes,
1447 * look up the operator. Returns InvalidOid if not found.
1449 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1452 * If the operator name is not schema-qualified, it is sought in the current
1453 * namespace search path. If the name is schema-qualified and the given
1454 * schema does not exist, InvalidOid is returned.
1457 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1464 /* deconstruct the name list */
1465 DeconstructQualifiedName(names, &schemaname, &opername);
1469 /* search only in exact schema given */
1472 namespaceId = LookupExplicitNamespace(schemaname, true);
1473 if (OidIsValid(namespaceId))
1477 opertup = SearchSysCache4(OPERNAMENSP,
1478 CStringGetDatum(opername),
1479 ObjectIdGetDatum(oprleft),
1480 ObjectIdGetDatum(oprright),
1481 ObjectIdGetDatum(namespaceId));
1482 if (HeapTupleIsValid(opertup))
1484 Oid result = HeapTupleGetOid(opertup);
1486 ReleaseSysCache(opertup);
1494 /* Search syscache by name and argument types */
1495 catlist = SearchSysCacheList3(OPERNAMENSP,
1496 CStringGetDatum(opername),
1497 ObjectIdGetDatum(oprleft),
1498 ObjectIdGetDatum(oprright));
1500 if (catlist->n_members == 0)
1502 /* no hope, fall out early */
1503 ReleaseSysCacheList(catlist);
1508 * We have to find the list member that is first in the search path, if
1509 * there's more than one. This doubly-nested loop looks ugly, but in
1510 * practice there should usually be few catlist members.
1512 recomputeNamespacePath();
1514 foreach(l, activeSearchPath)
1516 Oid namespaceId = lfirst_oid(l);
1519 if (namespaceId == myTempNamespace)
1520 continue; /* do not look in temp namespace */
1522 for (i = 0; i < catlist->n_members; i++)
1524 HeapTuple opertup = &catlist->members[i]->tuple;
1525 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1527 if (operform->oprnamespace == namespaceId)
1529 Oid result = HeapTupleGetOid(opertup);
1531 ReleaseSysCacheList(catlist);
1537 ReleaseSysCacheList(catlist);
1542 * OpernameGetCandidates
1543 * Given a possibly-qualified operator name and operator kind,
1544 * retrieve a list of the possible matches.
1546 * If oprkind is '\0', we return all operators matching the given name,
1547 * regardless of arguments.
1549 * We search a single namespace if the operator name is qualified, else
1550 * all namespaces in the search path. The return list will never contain
1551 * multiple entries with identical argument lists --- in the multiple-
1552 * namespace case, we arrange for entries in earlier namespaces to mask
1553 * identical entries in later namespaces.
1555 * The returned items always have two args[] entries --- one or the other
1556 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1559 OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
1561 FuncCandidateList resultList = NULL;
1562 char *resultSpace = NULL;
1570 /* deconstruct the name list */
1571 DeconstructQualifiedName(names, &schemaname, &opername);
1575 /* use exact schema given */
1576 namespaceId = LookupExplicitNamespace(schemaname, missing_schema_ok);
1577 if (missing_schema_ok && !OidIsValid(namespaceId))
1582 /* flag to indicate we need namespace search */
1583 namespaceId = InvalidOid;
1584 recomputeNamespacePath();
1587 /* Search syscache by name only */
1588 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1591 * In typical scenarios, most if not all of the operators found by the
1592 * catcache search will end up getting returned; and there can be quite a
1593 * few, for common operator names such as '=' or '+'. To reduce the time
1594 * spent in palloc, we allocate the result space as an array large enough
1595 * to hold all the operators. The original coding of this routine did a
1596 * separate palloc for each operator, but profiling revealed that the
1597 * pallocs used an unreasonably large fraction of parsing time.
1599 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1601 if (catlist->n_members > 0)
1602 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1604 for (i = 0; i < catlist->n_members; i++)
1606 HeapTuple opertup = &catlist->members[i]->tuple;
1607 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1609 FuncCandidateList newResult;
1611 /* Ignore operators of wrong kind, if specific kind requested */
1612 if (oprkind && operform->oprkind != oprkind)
1615 if (OidIsValid(namespaceId))
1617 /* Consider only opers in specified namespace */
1618 if (operform->oprnamespace != namespaceId)
1620 /* No need to check args, they must all be different */
1625 * Consider only opers that are in the search path and are not in
1626 * the temp namespace.
1630 foreach(nsp, activeSearchPath)
1632 if (operform->oprnamespace == lfirst_oid(nsp) &&
1633 operform->oprnamespace != myTempNamespace)
1638 continue; /* oper is not in search path */
1641 * Okay, it's in the search path, but does it have the same
1642 * arguments as something we already accepted? If so, keep only
1643 * the one that appears earlier in the search path.
1645 * If we have an ordered list from SearchSysCacheList (the normal
1646 * case), then any conflicting oper must immediately adjoin this
1647 * one in the list, so we only need to look at the newest result
1648 * item. If we have an unordered list, we have to scan the whole
1653 FuncCandidateList prevResult;
1655 if (catlist->ordered)
1657 if (operform->oprleft == resultList->args[0] &&
1658 operform->oprright == resultList->args[1])
1659 prevResult = resultList;
1665 for (prevResult = resultList;
1667 prevResult = prevResult->next)
1669 if (operform->oprleft == prevResult->args[0] &&
1670 operform->oprright == prevResult->args[1])
1676 /* We have a match with a previous result */
1677 Assert(pathpos != prevResult->pathpos);
1678 if (pathpos > prevResult->pathpos)
1679 continue; /* keep previous result */
1680 /* replace previous result */
1681 prevResult->pathpos = pathpos;
1682 prevResult->oid = HeapTupleGetOid(opertup);
1683 continue; /* args are same, of course */
1689 * Okay to add it to result list
1691 newResult = (FuncCandidateList) (resultSpace + nextResult);
1692 nextResult += SPACE_PER_OP;
1694 newResult->pathpos = pathpos;
1695 newResult->oid = HeapTupleGetOid(opertup);
1696 newResult->nargs = 2;
1697 newResult->nvargs = 0;
1698 newResult->ndargs = 0;
1699 newResult->argnumbers = NULL;
1700 newResult->args[0] = operform->oprleft;
1701 newResult->args[1] = operform->oprright;
1702 newResult->next = resultList;
1703 resultList = newResult;
1706 ReleaseSysCacheList(catlist);
1713 * Determine whether an operator (identified by OID) is visible in the
1714 * current search path. Visible means "would be found by searching
1715 * for the unqualified operator name with exact argument matches".
1718 OperatorIsVisible(Oid oprid)
1721 Form_pg_operator oprform;
1725 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1726 if (!HeapTupleIsValid(oprtup))
1727 elog(ERROR, "cache lookup failed for operator %u", oprid);
1728 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1730 recomputeNamespacePath();
1733 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1734 * the system namespace are surely in the path and so we needn't even do
1735 * list_member_oid() for them.
1737 oprnamespace = oprform->oprnamespace;
1738 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1739 !list_member_oid(activeSearchPath, oprnamespace))
1744 * If it is in the path, it might still not be visible; it could be
1745 * hidden by another operator of the same name and arguments earlier
1746 * in the path. So we must do a slow check to see if this is the same
1747 * operator that would be found by OpernameGetOprid.
1749 char *oprname = NameStr(oprform->oprname);
1751 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1752 oprform->oprleft, oprform->oprright)
1756 ReleaseSysCache(oprtup);
1763 * OpclassnameGetOpcid
1764 * Try to resolve an unqualified index opclass name.
1765 * Returns OID if opclass found in search path, else InvalidOid.
1767 * This is essentially the same as TypenameGetTypid, but we have to have
1768 * an extra argument for the index AM OID.
1771 OpclassnameGetOpcid(Oid amid, const char *opcname)
1776 recomputeNamespacePath();
1778 foreach(l, activeSearchPath)
1780 Oid namespaceId = lfirst_oid(l);
1782 if (namespaceId == myTempNamespace)
1783 continue; /* do not look in temp namespace */
1785 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1786 ObjectIdGetDatum(amid),
1787 PointerGetDatum(opcname),
1788 ObjectIdGetDatum(namespaceId));
1789 if (OidIsValid(opcid))
1793 /* Not found in path */
1799 * Determine whether an opclass (identified by OID) is visible in the
1800 * current search path. Visible means "would be found by searching
1801 * for the unqualified opclass name".
1804 OpclassIsVisible(Oid opcid)
1807 Form_pg_opclass opcform;
1811 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1812 if (!HeapTupleIsValid(opctup))
1813 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1814 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1816 recomputeNamespacePath();
1819 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1820 * the system namespace are surely in the path and so we needn't even do
1821 * list_member_oid() for them.
1823 opcnamespace = opcform->opcnamespace;
1824 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1825 !list_member_oid(activeSearchPath, opcnamespace))
1830 * If it is in the path, it might still not be visible; it could be
1831 * hidden by another opclass of the same name earlier in the path. So
1832 * we must do a slow check to see if this opclass would be found by
1833 * OpclassnameGetOpcid.
1835 char *opcname = NameStr(opcform->opcname);
1837 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1840 ReleaseSysCache(opctup);
1846 * OpfamilynameGetOpfid
1847 * Try to resolve an unqualified index opfamily name.
1848 * Returns OID if opfamily found in search path, else InvalidOid.
1850 * This is essentially the same as TypenameGetTypid, but we have to have
1851 * an extra argument for the index AM OID.
1854 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1859 recomputeNamespacePath();
1861 foreach(l, activeSearchPath)
1863 Oid namespaceId = lfirst_oid(l);
1865 if (namespaceId == myTempNamespace)
1866 continue; /* do not look in temp namespace */
1868 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1869 ObjectIdGetDatum(amid),
1870 PointerGetDatum(opfname),
1871 ObjectIdGetDatum(namespaceId));
1872 if (OidIsValid(opfid))
1876 /* Not found in path */
1882 * Determine whether an opfamily (identified by OID) is visible in the
1883 * current search path. Visible means "would be found by searching
1884 * for the unqualified opfamily name".
1887 OpfamilyIsVisible(Oid opfid)
1890 Form_pg_opfamily opfform;
1894 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1895 if (!HeapTupleIsValid(opftup))
1896 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1897 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1899 recomputeNamespacePath();
1902 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1903 * the system namespace are surely in the path and so we needn't even do
1904 * list_member_oid() for them.
1906 opfnamespace = opfform->opfnamespace;
1907 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1908 !list_member_oid(activeSearchPath, opfnamespace))
1913 * If it is in the path, it might still not be visible; it could be
1914 * hidden by another opfamily of the same name earlier in the path. So
1915 * we must do a slow check to see if this opfamily would be found by
1916 * OpfamilynameGetOpfid.
1918 char *opfname = NameStr(opfform->opfname);
1920 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1923 ReleaseSysCache(opftup);
1929 * CollationGetCollid
1930 * Try to resolve an unqualified collation name.
1931 * Returns OID if collation found in search path, else InvalidOid.
1934 CollationGetCollid(const char *collname)
1936 int32 dbencoding = GetDatabaseEncoding();
1939 recomputeNamespacePath();
1941 foreach(l, activeSearchPath)
1943 Oid namespaceId = lfirst_oid(l);
1946 if (namespaceId == myTempNamespace)
1947 continue; /* do not look in temp namespace */
1949 /* Check for database-encoding-specific entry */
1950 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1951 PointerGetDatum(collname),
1952 Int32GetDatum(dbencoding),
1953 ObjectIdGetDatum(namespaceId));
1954 if (OidIsValid(collid))
1957 /* Check for any-encoding entry */
1958 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1959 PointerGetDatum(collname),
1961 ObjectIdGetDatum(namespaceId));
1962 if (OidIsValid(collid))
1966 /* Not found in path */
1971 * CollationIsVisible
1972 * Determine whether a collation (identified by OID) is visible in the
1973 * current search path. Visible means "would be found by searching
1974 * for the unqualified collation name".
1977 CollationIsVisible(Oid collid)
1980 Form_pg_collation collform;
1984 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1985 if (!HeapTupleIsValid(colltup))
1986 elog(ERROR, "cache lookup failed for collation %u", collid);
1987 collform = (Form_pg_collation) GETSTRUCT(colltup);
1989 recomputeNamespacePath();
1992 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1993 * the system namespace are surely in the path and so we needn't even do
1994 * list_member_oid() for them.
1996 collnamespace = collform->collnamespace;
1997 if (collnamespace != PG_CATALOG_NAMESPACE &&
1998 !list_member_oid(activeSearchPath, collnamespace))
2003 * If it is in the path, it might still not be visible; it could be
2004 * hidden by another conversion of the same name earlier in the path.
2005 * So we must do a slow check to see if this conversion would be found
2006 * by CollationGetCollid.
2008 char *collname = NameStr(collform->collname);
2010 visible = (CollationGetCollid(collname) == collid);
2013 ReleaseSysCache(colltup);
2020 * ConversionGetConid
2021 * Try to resolve an unqualified conversion name.
2022 * Returns OID if conversion found in search path, else InvalidOid.
2024 * This is essentially the same as RelnameGetRelid.
2027 ConversionGetConid(const char *conname)
2032 recomputeNamespacePath();
2034 foreach(l, activeSearchPath)
2036 Oid namespaceId = lfirst_oid(l);
2038 if (namespaceId == myTempNamespace)
2039 continue; /* do not look in temp namespace */
2041 conid = GetSysCacheOid2(CONNAMENSP,
2042 PointerGetDatum(conname),
2043 ObjectIdGetDatum(namespaceId));
2044 if (OidIsValid(conid))
2048 /* Not found in path */
2053 * ConversionIsVisible
2054 * Determine whether a conversion (identified by OID) is visible in the
2055 * current search path. Visible means "would be found by searching
2056 * for the unqualified conversion name".
2059 ConversionIsVisible(Oid conid)
2062 Form_pg_conversion conform;
2066 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2067 if (!HeapTupleIsValid(contup))
2068 elog(ERROR, "cache lookup failed for conversion %u", conid);
2069 conform = (Form_pg_conversion) GETSTRUCT(contup);
2071 recomputeNamespacePath();
2074 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2075 * the system namespace are surely in the path and so we needn't even do
2076 * list_member_oid() for them.
2078 connamespace = conform->connamespace;
2079 if (connamespace != PG_CATALOG_NAMESPACE &&
2080 !list_member_oid(activeSearchPath, connamespace))
2085 * If it is in the path, it might still not be visible; it could be
2086 * hidden by another conversion of the same name earlier in the path.
2087 * So we must do a slow check to see if this conversion would be found
2088 * by ConversionGetConid.
2090 char *conname = NameStr(conform->conname);
2092 visible = (ConversionGetConid(conname) == conid);
2095 ReleaseSysCache(contup);
2101 * get_ts_parser_oid - find a TS parser by possibly qualified name
2103 * If not found, returns InvalidOid if missing_ok, else throws error
2106 get_ts_parser_oid(List *names, bool missing_ok)
2111 Oid prsoid = InvalidOid;
2114 /* deconstruct the name list */
2115 DeconstructQualifiedName(names, &schemaname, &parser_name);
2119 /* use exact schema given */
2120 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2121 if (missing_ok && !OidIsValid(namespaceId))
2122 prsoid = InvalidOid;
2124 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2125 PointerGetDatum(parser_name),
2126 ObjectIdGetDatum(namespaceId));
2130 /* search for it in search path */
2131 recomputeNamespacePath();
2133 foreach(l, activeSearchPath)
2135 namespaceId = lfirst_oid(l);
2137 if (namespaceId == myTempNamespace)
2138 continue; /* do not look in temp namespace */
2140 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2141 PointerGetDatum(parser_name),
2142 ObjectIdGetDatum(namespaceId));
2143 if (OidIsValid(prsoid))
2148 if (!OidIsValid(prsoid) && !missing_ok)
2150 (errcode(ERRCODE_UNDEFINED_OBJECT),
2151 errmsg("text search parser \"%s\" does not exist",
2152 NameListToString(names))));
2159 * Determine whether a parser (identified by OID) is visible in the
2160 * current search path. Visible means "would be found by searching
2161 * for the unqualified parser name".
2164 TSParserIsVisible(Oid prsId)
2167 Form_pg_ts_parser form;
2171 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2172 if (!HeapTupleIsValid(tup))
2173 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2174 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2176 recomputeNamespacePath();
2179 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2180 * the system namespace are surely in the path and so we needn't even do
2181 * list_member_oid() for them.
2183 namespace = form->prsnamespace;
2184 if (namespace != PG_CATALOG_NAMESPACE &&
2185 !list_member_oid(activeSearchPath, namespace))
2190 * If it is in the path, it might still not be visible; it could be
2191 * hidden by another parser of the same name earlier in the path. So
2192 * we must do a slow check for conflicting parsers.
2194 char *name = NameStr(form->prsname);
2198 foreach(l, activeSearchPath)
2200 Oid namespaceId = lfirst_oid(l);
2202 if (namespaceId == myTempNamespace)
2203 continue; /* do not look in temp namespace */
2205 if (namespaceId == namespace)
2207 /* Found it first in path */
2211 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2212 PointerGetDatum(name),
2213 ObjectIdGetDatum(namespaceId)))
2215 /* Found something else first in path */
2221 ReleaseSysCache(tup);
2227 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2229 * If not found, returns InvalidOid if failOK, else throws error
2232 get_ts_dict_oid(List *names, bool missing_ok)
2237 Oid dictoid = InvalidOid;
2240 /* deconstruct the name list */
2241 DeconstructQualifiedName(names, &schemaname, &dict_name);
2245 /* use exact schema given */
2246 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2247 if (missing_ok && !OidIsValid(namespaceId))
2248 dictoid = InvalidOid;
2250 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2251 PointerGetDatum(dict_name),
2252 ObjectIdGetDatum(namespaceId));
2256 /* search for it in search path */
2257 recomputeNamespacePath();
2259 foreach(l, activeSearchPath)
2261 namespaceId = lfirst_oid(l);
2263 if (namespaceId == myTempNamespace)
2264 continue; /* do not look in temp namespace */
2266 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2267 PointerGetDatum(dict_name),
2268 ObjectIdGetDatum(namespaceId));
2269 if (OidIsValid(dictoid))
2274 if (!OidIsValid(dictoid) && !missing_ok)
2276 (errcode(ERRCODE_UNDEFINED_OBJECT),
2277 errmsg("text search dictionary \"%s\" does not exist",
2278 NameListToString(names))));
2284 * TSDictionaryIsVisible
2285 * Determine whether a dictionary (identified by OID) is visible in the
2286 * current search path. Visible means "would be found by searching
2287 * for the unqualified dictionary name".
2290 TSDictionaryIsVisible(Oid dictId)
2293 Form_pg_ts_dict form;
2297 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2298 if (!HeapTupleIsValid(tup))
2299 elog(ERROR, "cache lookup failed for text search dictionary %u",
2301 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2303 recomputeNamespacePath();
2306 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2307 * the system namespace are surely in the path and so we needn't even do
2308 * list_member_oid() for them.
2310 namespace = form->dictnamespace;
2311 if (namespace != PG_CATALOG_NAMESPACE &&
2312 !list_member_oid(activeSearchPath, namespace))
2317 * If it is in the path, it might still not be visible; it could be
2318 * hidden by another dictionary of the same name earlier in the path.
2319 * So we must do a slow check for conflicting dictionaries.
2321 char *name = NameStr(form->dictname);
2325 foreach(l, activeSearchPath)
2327 Oid namespaceId = lfirst_oid(l);
2329 if (namespaceId == myTempNamespace)
2330 continue; /* do not look in temp namespace */
2332 if (namespaceId == namespace)
2334 /* Found it first in path */
2338 if (SearchSysCacheExists2(TSDICTNAMENSP,
2339 PointerGetDatum(name),
2340 ObjectIdGetDatum(namespaceId)))
2342 /* Found something else first in path */
2348 ReleaseSysCache(tup);
2354 * get_ts_template_oid - find a TS template by possibly qualified name
2356 * If not found, returns InvalidOid if missing_ok, else throws error
2359 get_ts_template_oid(List *names, bool missing_ok)
2362 char *template_name;
2364 Oid tmploid = InvalidOid;
2367 /* deconstruct the name list */
2368 DeconstructQualifiedName(names, &schemaname, &template_name);
2372 /* use exact schema given */
2373 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2374 if (missing_ok && !OidIsValid(namespaceId))
2375 tmploid = InvalidOid;
2377 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2378 PointerGetDatum(template_name),
2379 ObjectIdGetDatum(namespaceId));
2383 /* search for it in search path */
2384 recomputeNamespacePath();
2386 foreach(l, activeSearchPath)
2388 namespaceId = lfirst_oid(l);
2390 if (namespaceId == myTempNamespace)
2391 continue; /* do not look in temp namespace */
2393 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2394 PointerGetDatum(template_name),
2395 ObjectIdGetDatum(namespaceId));
2396 if (OidIsValid(tmploid))
2401 if (!OidIsValid(tmploid) && !missing_ok)
2403 (errcode(ERRCODE_UNDEFINED_OBJECT),
2404 errmsg("text search template \"%s\" does not exist",
2405 NameListToString(names))));
2411 * TSTemplateIsVisible
2412 * Determine whether a template (identified by OID) is visible in the
2413 * current search path. Visible means "would be found by searching
2414 * for the unqualified template name".
2417 TSTemplateIsVisible(Oid tmplId)
2420 Form_pg_ts_template form;
2424 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2425 if (!HeapTupleIsValid(tup))
2426 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2427 form = (Form_pg_ts_template) GETSTRUCT(tup);
2429 recomputeNamespacePath();
2432 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2433 * the system namespace are surely in the path and so we needn't even do
2434 * list_member_oid() for them.
2436 namespace = form->tmplnamespace;
2437 if (namespace != PG_CATALOG_NAMESPACE &&
2438 !list_member_oid(activeSearchPath, namespace))
2443 * If it is in the path, it might still not be visible; it could be
2444 * hidden by another template of the same name earlier in the path. So
2445 * we must do a slow check for conflicting templates.
2447 char *name = NameStr(form->tmplname);
2451 foreach(l, activeSearchPath)
2453 Oid namespaceId = lfirst_oid(l);
2455 if (namespaceId == myTempNamespace)
2456 continue; /* do not look in temp namespace */
2458 if (namespaceId == namespace)
2460 /* Found it first in path */
2464 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2465 PointerGetDatum(name),
2466 ObjectIdGetDatum(namespaceId)))
2468 /* Found something else first in path */
2474 ReleaseSysCache(tup);
2480 * get_ts_config_oid - find a TS config by possibly qualified name
2482 * If not found, returns InvalidOid if missing_ok, else throws error
2485 get_ts_config_oid(List *names, bool missing_ok)
2490 Oid cfgoid = InvalidOid;
2493 /* deconstruct the name list */
2494 DeconstructQualifiedName(names, &schemaname, &config_name);
2498 /* use exact schema given */
2499 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2500 if (missing_ok && !OidIsValid(namespaceId))
2501 cfgoid = InvalidOid;
2503 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2504 PointerGetDatum(config_name),
2505 ObjectIdGetDatum(namespaceId));
2509 /* search for it in search path */
2510 recomputeNamespacePath();
2512 foreach(l, activeSearchPath)
2514 namespaceId = lfirst_oid(l);
2516 if (namespaceId == myTempNamespace)
2517 continue; /* do not look in temp namespace */
2519 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2520 PointerGetDatum(config_name),
2521 ObjectIdGetDatum(namespaceId));
2522 if (OidIsValid(cfgoid))
2527 if (!OidIsValid(cfgoid) && !missing_ok)
2529 (errcode(ERRCODE_UNDEFINED_OBJECT),
2530 errmsg("text search configuration \"%s\" does not exist",
2531 NameListToString(names))));
2538 * Determine whether a text search configuration (identified by OID)
2539 * is visible in the current search path. Visible means "would be found
2540 * by searching for the unqualified text search configuration name".
2543 TSConfigIsVisible(Oid cfgid)
2546 Form_pg_ts_config form;
2550 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2551 if (!HeapTupleIsValid(tup))
2552 elog(ERROR, "cache lookup failed for text search configuration %u",
2554 form = (Form_pg_ts_config) GETSTRUCT(tup);
2556 recomputeNamespacePath();
2559 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2560 * the system namespace are surely in the path and so we needn't even do
2561 * list_member_oid() for them.
2563 namespace = form->cfgnamespace;
2564 if (namespace != PG_CATALOG_NAMESPACE &&
2565 !list_member_oid(activeSearchPath, namespace))
2570 * If it is in the path, it might still not be visible; it could be
2571 * hidden by another configuration of the same name earlier in the
2572 * path. So we must do a slow check for conflicting configurations.
2574 char *name = NameStr(form->cfgname);
2578 foreach(l, activeSearchPath)
2580 Oid namespaceId = lfirst_oid(l);
2582 if (namespaceId == myTempNamespace)
2583 continue; /* do not look in temp namespace */
2585 if (namespaceId == namespace)
2587 /* Found it first in path */
2591 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2592 PointerGetDatum(name),
2593 ObjectIdGetDatum(namespaceId)))
2595 /* Found something else first in path */
2601 ReleaseSysCache(tup);
2608 * DeconstructQualifiedName
2609 * Given a possibly-qualified name expressed as a list of String nodes,
2610 * extract the schema name and object name.
2612 * *nspname_p is set to NULL if there is no explicit schema name.
2615 DeconstructQualifiedName(List *names,
2620 char *schemaname = NULL;
2621 char *objname = NULL;
2623 switch (list_length(names))
2626 objname = strVal(linitial(names));
2629 schemaname = strVal(linitial(names));
2630 objname = strVal(lsecond(names));
2633 catalogname = strVal(linitial(names));
2634 schemaname = strVal(lsecond(names));
2635 objname = strVal(lthird(names));
2638 * We check the catalog name and then ignore it.
2640 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2642 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2643 errmsg("cross-database references are not implemented: %s",
2644 NameListToString(names))));
2648 (errcode(ERRCODE_SYNTAX_ERROR),
2649 errmsg("improper qualified name (too many dotted names): %s",
2650 NameListToString(names))));
2654 *nspname_p = schemaname;
2655 *objname_p = objname;
2659 * LookupNamespaceNoError
2660 * Look up a schema name.
2662 * Returns the namespace OID, or InvalidOid if not found.
2664 * Note this does NOT perform any permissions check --- callers are
2665 * responsible for being sure that an appropriate check is made.
2666 * In the majority of cases LookupExplicitNamespace is preferable.
2669 LookupNamespaceNoError(const char *nspname)
2671 /* check for pg_temp alias */
2672 if (strcmp(nspname, "pg_temp") == 0)
2674 if (OidIsValid(myTempNamespace))
2676 InvokeNamespaceSearchHook(myTempNamespace, true);
2677 return myTempNamespace;
2681 * Since this is used only for looking up existing objects, there is
2682 * no point in trying to initialize the temp namespace here; and doing
2683 * so might create problems for some callers. Just report "not found".
2688 return get_namespace_oid(nspname, true);
2692 * LookupExplicitNamespace
2693 * Process an explicitly-specified schema name: look up the schema
2694 * and verify we have USAGE (lookup) rights in it.
2696 * Returns the namespace OID
2699 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2702 AclResult aclresult;
2704 /* check for pg_temp alias */
2705 if (strcmp(nspname, "pg_temp") == 0)
2707 if (OidIsValid(myTempNamespace))
2708 return myTempNamespace;
2711 * Since this is used only for looking up existing objects, there is
2712 * no point in trying to initialize the temp namespace here; and doing
2713 * so might create problems for some callers --- just fall through.
2717 namespaceId = get_namespace_oid(nspname, missing_ok);
2718 if (missing_ok && !OidIsValid(namespaceId))
2721 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2722 if (aclresult != ACLCHECK_OK)
2723 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2725 /* Schema search hook for this lookup */
2726 InvokeNamespaceSearchHook(namespaceId, true);
2732 * LookupCreationNamespace
2733 * Look up the schema and verify we have CREATE rights on it.
2735 * This is just like LookupExplicitNamespace except for the different
2736 * permission check, and that we are willing to create pg_temp if needed.
2738 * Note: calling this may result in a CommandCounterIncrement operation,
2739 * if we have to create or clean out the temp namespace.
2742 LookupCreationNamespace(const char *nspname)
2745 AclResult aclresult;
2747 /* check for pg_temp alias */
2748 if (strcmp(nspname, "pg_temp") == 0)
2750 /* Initialize temp namespace if first time through */
2751 if (!OidIsValid(myTempNamespace))
2752 InitTempTableNamespace();
2753 return myTempNamespace;
2756 namespaceId = get_namespace_oid(nspname, false);
2758 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2759 if (aclresult != ACLCHECK_OK)
2760 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2767 * Common checks on switching namespaces.
2769 * We complain if (1) the old and new namespaces are the same, (2) either the
2770 * old or new namespaces is a temporary schema (or temporary toast schema), or
2771 * (3) either the old or new namespaces is the TOAST schema.
2774 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2776 if (oldNspOid == nspOid)
2778 (classid == RelationRelationId ?
2779 errcode(ERRCODE_DUPLICATE_TABLE) :
2780 classid == ProcedureRelationId ?
2781 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2782 errcode(ERRCODE_DUPLICATE_OBJECT),
2783 errmsg("%s is already in schema \"%s\"",
2784 getObjectDescriptionOids(classid, objid),
2785 get_namespace_name(nspOid))));
2787 /* disallow renaming into or out of temp schemas */
2788 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2790 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2791 errmsg("cannot move objects into or out of temporary schemas")));
2793 /* same for TOAST schema */
2794 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2796 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2797 errmsg("cannot move objects into or out of TOAST schema")));
2801 * QualifiedNameGetCreationNamespace
2802 * Given a possibly-qualified name for an object (in List-of-Values
2803 * format), determine what namespace the object should be created in.
2804 * Also extract and return the object name (last component of list).
2806 * Note: this does not apply any permissions check. Callers must check
2807 * for CREATE rights on the selected namespace when appropriate.
2809 * Note: calling this may result in a CommandCounterIncrement operation,
2810 * if we have to create or clean out the temp namespace.
2813 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2818 /* deconstruct the name list */
2819 DeconstructQualifiedName(names, &schemaname, objname_p);
2823 /* check for pg_temp alias */
2824 if (strcmp(schemaname, "pg_temp") == 0)
2826 /* Initialize temp namespace if first time through */
2827 if (!OidIsValid(myTempNamespace))
2828 InitTempTableNamespace();
2829 return myTempNamespace;
2831 /* use exact schema given */
2832 namespaceId = get_namespace_oid(schemaname, false);
2833 /* we do not check for USAGE rights here! */
2837 /* use the default creation namespace */
2838 recomputeNamespacePath();
2839 if (activeTempCreationPending)
2841 /* Need to initialize temp namespace */
2842 InitTempTableNamespace();
2843 return myTempNamespace;
2845 namespaceId = activeCreationNamespace;
2846 if (!OidIsValid(namespaceId))
2848 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2849 errmsg("no schema has been selected to create in")));
2856 * get_namespace_oid - given a namespace name, look up the OID
2858 * If missing_ok is false, throw an error if namespace name not found. If
2859 * true, just return InvalidOid.
2862 get_namespace_oid(const char *nspname, bool missing_ok)
2866 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2867 if (!OidIsValid(oid) && !missing_ok)
2869 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2870 errmsg("schema \"%s\" does not exist", nspname)));
2876 * makeRangeVarFromNameList
2877 * Utility routine to convert a qualified-name list into RangeVar form.
2880 makeRangeVarFromNameList(List *names)
2882 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2884 switch (list_length(names))
2887 rel->relname = strVal(linitial(names));
2890 rel->schemaname = strVal(linitial(names));
2891 rel->relname = strVal(lsecond(names));
2894 rel->catalogname = strVal(linitial(names));
2895 rel->schemaname = strVal(lsecond(names));
2896 rel->relname = strVal(lthird(names));
2900 (errcode(ERRCODE_SYNTAX_ERROR),
2901 errmsg("improper relation name (too many dotted names): %s",
2902 NameListToString(names))));
2911 * Utility routine to convert a qualified-name list into a string.
2913 * This is used primarily to form error messages, and so we do not quote
2914 * the list elements, for the sake of legibility.
2916 * In most scenarios the list elements should always be Value strings,
2917 * but we also allow A_Star for the convenience of ColumnRef processing.
2920 NameListToString(List *names)
2922 StringInfoData string;
2925 initStringInfo(&string);
2929 Node *name = (Node *) lfirst(l);
2931 if (l != list_head(names))
2932 appendStringInfoChar(&string, '.');
2934 if (IsA(name, String))
2935 appendStringInfoString(&string, strVal(name));
2936 else if (IsA(name, A_Star))
2937 appendStringInfoString(&string, "*");
2939 elog(ERROR, "unexpected node type in name list: %d",
2940 (int) nodeTag(name));
2947 * NameListToQuotedString
2948 * Utility routine to convert a qualified-name list into a string.
2950 * Same as above except that names will be double-quoted where necessary,
2951 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2954 NameListToQuotedString(List *names)
2956 StringInfoData string;
2959 initStringInfo(&string);
2963 if (l != list_head(names))
2964 appendStringInfoChar(&string, '.');
2965 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2972 * isTempNamespace - is the given namespace my temporary-table namespace?
2975 isTempNamespace(Oid namespaceId)
2977 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2983 * isTempToastNamespace - is the given namespace my temporary-toast-table
2987 isTempToastNamespace(Oid namespaceId)
2989 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2995 * isTempOrToastNamespace - is the given namespace my temporary-table
2996 * namespace or my temporary-toast-table namespace?
2999 isTempOrToastNamespace(Oid namespaceId)
3001 if (OidIsValid(myTempNamespace) &&
3002 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3008 * isAnyTempNamespace - is the given namespace a temporary-table namespace
3009 * (either my own, or another backend's)? Temporary-toast-table namespaces
3010 * are included, too.
3013 isAnyTempNamespace(Oid namespaceId)
3018 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3019 nspname = get_namespace_name(namespaceId);
3021 return false; /* no such namespace? */
3022 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3023 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3029 * isOtherTempNamespace - is the given namespace some other backend's
3030 * temporary-table namespace (including temporary-toast-table namespaces)?
3032 * Note: for most purposes in the C code, this function is obsolete. Use
3033 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3036 isOtherTempNamespace(Oid namespaceId)
3038 /* If it's my own temp namespace, say "false" */
3039 if (isTempOrToastNamespace(namespaceId))
3041 /* Else, if it's any temp namespace, say "true" */
3042 return isAnyTempNamespace(namespaceId);
3046 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3047 * namespace (either my own, or another backend's), return the BackendId
3048 * that owns it. Temporary-toast-table namespaces are included, too.
3049 * If it isn't a temp namespace, return InvalidBackendId.
3052 GetTempNamespaceBackendId(Oid namespaceId)
3057 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3058 nspname = get_namespace_name(namespaceId);
3060 return InvalidBackendId; /* no such namespace? */
3061 if (strncmp(nspname, "pg_temp_", 8) == 0)
3062 result = atoi(nspname + 8);
3063 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3064 result = atoi(nspname + 14);
3066 result = InvalidBackendId;
3072 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3073 * which must already be assigned. (This is only used when creating a toast
3074 * table for a temp table, so we must have already done InitTempTableNamespace)
3077 GetTempToastNamespace(void)
3079 Assert(OidIsValid(myTempToastNamespace));
3080 return myTempToastNamespace;
3085 * GetOverrideSearchPath - fetch current search path definition in form
3086 * used by PushOverrideSearchPath.
3088 * The result structure is allocated in the specified memory context
3089 * (which might or might not be equal to CurrentMemoryContext); but any
3090 * junk created by revalidation calculations will be in CurrentMemoryContext.
3092 OverrideSearchPath *
3093 GetOverrideSearchPath(MemoryContext context)
3095 OverrideSearchPath *result;
3097 MemoryContext oldcxt;
3099 recomputeNamespacePath();
3101 oldcxt = MemoryContextSwitchTo(context);
3103 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3104 schemas = list_copy(activeSearchPath);
3105 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3107 if (linitial_oid(schemas) == myTempNamespace)
3108 result->addTemp = true;
3111 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3112 result->addCatalog = true;
3114 schemas = list_delete_first(schemas);
3116 result->schemas = schemas;
3118 MemoryContextSwitchTo(oldcxt);
3124 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3126 * The result structure is allocated in CurrentMemoryContext.
3128 OverrideSearchPath *
3129 CopyOverrideSearchPath(OverrideSearchPath *path)
3131 OverrideSearchPath *result;
3133 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3134 result->schemas = list_copy(path->schemas);
3135 result->addCatalog = path->addCatalog;
3136 result->addTemp = path->addTemp;
3142 * OverrideSearchPathMatchesCurrent - does path match current setting?
3145 OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
3147 /* Easiest way to do this is GetOverrideSearchPath() and compare */
3149 OverrideSearchPath *cur;
3151 cur = GetOverrideSearchPath(CurrentMemoryContext);
3152 if (path->addCatalog == cur->addCatalog &&
3153 path->addTemp == cur->addTemp &&
3154 equal(path->schemas, cur->schemas))
3158 list_free(cur->schemas);
3164 * PushOverrideSearchPath - temporarily override the search path
3166 * We allow nested overrides, hence the push/pop terminology. The GUC
3167 * search_path variable is ignored while an override is active.
3169 * It's possible that newpath->useTemp is set but there is no longer any
3170 * active temp namespace, if the path was saved during a transaction that
3171 * created a temp namespace and was later rolled back. In that case we just
3172 * ignore useTemp. A plausible alternative would be to create a new temp
3173 * namespace, but for existing callers that's not necessary because an empty
3174 * temp namespace wouldn't affect their results anyway.
3176 * It's also worth noting that other schemas listed in newpath might not
3177 * exist anymore either. We don't worry about this because OIDs that match
3178 * no existing namespace will simply not produce any hits during searches.
3181 PushOverrideSearchPath(OverrideSearchPath *newpath)
3183 OverrideStackEntry *entry;
3186 MemoryContext oldcxt;
3189 * Copy the list for safekeeping, and insert implicitly-searched
3190 * namespaces as needed. This code should track recomputeNamespacePath.
3192 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3194 oidlist = list_copy(newpath->schemas);
3197 * Remember the first member of the explicit list.
3200 firstNS = InvalidOid;
3202 firstNS = linitial_oid(oidlist);
3205 * Add any implicitly-searched namespaces to the list. Note these go on
3206 * the front, not the back; also notice that we do not check USAGE
3207 * permissions for these.
3209 if (newpath->addCatalog)
3210 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3212 if (newpath->addTemp && OidIsValid(myTempNamespace))
3213 oidlist = lcons_oid(myTempNamespace, oidlist);
3216 * Build the new stack entry, then insert it at the head of the list.
3218 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3219 entry->searchPath = oidlist;
3220 entry->creationNamespace = firstNS;
3221 entry->nestLevel = GetCurrentTransactionNestLevel();
3223 overrideStack = lcons(entry, overrideStack);
3225 /* And make it active. */
3226 activeSearchPath = entry->searchPath;
3227 activeCreationNamespace = entry->creationNamespace;
3228 activeTempCreationPending = false; /* XXX is this OK? */
3230 MemoryContextSwitchTo(oldcxt);
3234 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3236 * Any push during a (sub)transaction will be popped automatically at abort.
3237 * But it's caller error if a push isn't popped in normal control flow.
3240 PopOverrideSearchPath(void)
3242 OverrideStackEntry *entry;
3244 /* Sanity checks. */
3245 if (overrideStack == NIL)
3246 elog(ERROR, "bogus PopOverrideSearchPath call");
3247 entry = (OverrideStackEntry *) linitial(overrideStack);
3248 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3249 elog(ERROR, "bogus PopOverrideSearchPath call");
3251 /* Pop the stack and free storage. */
3252 overrideStack = list_delete_first(overrideStack);
3253 list_free(entry->searchPath);
3256 /* Activate the next level down. */
3259 entry = (OverrideStackEntry *) linitial(overrideStack);
3260 activeSearchPath = entry->searchPath;
3261 activeCreationNamespace = entry->creationNamespace;
3262 activeTempCreationPending = false; /* XXX is this OK? */
3266 /* If not baseSearchPathValid, this is useless but harmless */
3267 activeSearchPath = baseSearchPath;
3268 activeCreationNamespace = baseCreationNamespace;
3269 activeTempCreationPending = baseTempCreationPending;
3275 * get_collation_oid - find a collation by possibly qualified name
3278 get_collation_oid(List *name, bool missing_ok)
3281 char *collation_name;
3282 int32 dbencoding = GetDatabaseEncoding();
3287 /* deconstruct the name list */
3288 DeconstructQualifiedName(name, &schemaname, &collation_name);
3292 /* use exact schema given */
3293 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3294 if (missing_ok && !OidIsValid(namespaceId))
3297 /* first try for encoding-specific entry, then any-encoding */
3298 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3299 PointerGetDatum(collation_name),
3300 Int32GetDatum(dbencoding),
3301 ObjectIdGetDatum(namespaceId));
3302 if (OidIsValid(colloid))
3304 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3305 PointerGetDatum(collation_name),
3307 ObjectIdGetDatum(namespaceId));
3308 if (OidIsValid(colloid))
3313 /* search for it in search path */
3314 recomputeNamespacePath();
3316 foreach(l, activeSearchPath)
3318 namespaceId = lfirst_oid(l);
3320 if (namespaceId == myTempNamespace)
3321 continue; /* do not look in temp namespace */
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 /* Not found in path */
3341 (errcode(ERRCODE_UNDEFINED_OBJECT),
3342 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3343 NameListToString(name), GetDatabaseEncodingName())));
3348 * get_conversion_oid - find a conversion by possibly qualified name
3351 get_conversion_oid(List *name, bool missing_ok)
3354 char *conversion_name;
3356 Oid conoid = InvalidOid;
3359 /* deconstruct the name list */
3360 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3364 /* use exact schema given */
3365 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3366 if (missing_ok && !OidIsValid(namespaceId))
3367 conoid = InvalidOid;
3369 conoid = GetSysCacheOid2(CONNAMENSP,
3370 PointerGetDatum(conversion_name),
3371 ObjectIdGetDatum(namespaceId));
3375 /* search for it in search path */
3376 recomputeNamespacePath();
3378 foreach(l, activeSearchPath)
3380 namespaceId = lfirst_oid(l);
3382 if (namespaceId == myTempNamespace)
3383 continue; /* do not look in temp namespace */
3385 conoid = GetSysCacheOid2(CONNAMENSP,
3386 PointerGetDatum(conversion_name),
3387 ObjectIdGetDatum(namespaceId));
3388 if (OidIsValid(conoid))
3393 /* Not found in path */
3394 if (!OidIsValid(conoid) && !missing_ok)
3396 (errcode(ERRCODE_UNDEFINED_OBJECT),
3397 errmsg("conversion \"%s\" does not exist",
3398 NameListToString(name))));
3403 * FindDefaultConversionProc - find default encoding conversion proc
3406 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3411 recomputeNamespacePath();
3413 foreach(l, activeSearchPath)
3415 Oid namespaceId = lfirst_oid(l);
3417 if (namespaceId == myTempNamespace)
3418 continue; /* do not look in temp namespace */
3420 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3421 if (OidIsValid(proc))
3425 /* Not found in path */
3430 * recomputeNamespacePath - recompute path derived variables if needed.
3433 recomputeNamespacePath(void)
3435 Oid roleid = GetUserId();
3443 MemoryContext oldcxt;
3445 /* Do nothing if an override search spec is active. */
3449 /* Do nothing if path is already valid. */
3450 if (baseSearchPathValid && namespaceUser == roleid)
3453 /* Need a modifiable copy of namespace_search_path string */
3454 rawname = pstrdup(namespace_search_path);
3456 /* Parse string into list of identifiers */
3457 if (!SplitIdentifierString(rawname, ',', &namelist))
3459 /* syntax error in name list */
3460 /* this should not happen if GUC checked check_search_path */
3461 elog(ERROR, "invalid list syntax");
3465 * Convert the list of names to a list of OIDs. If any names are not
3466 * recognizable or we don't have read access, just leave them out of the
3467 * list. (We can't raise an error, since the search_path setting has
3468 * already been accepted.) Don't make duplicate entries, either.
3471 temp_missing = false;
3472 foreach(l, namelist)
3474 char *curname = (char *) lfirst(l);
3477 if (strcmp(curname, "$user") == 0)
3479 /* $user --- substitute namespace matching user name, if any */
3482 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3483 if (HeapTupleIsValid(tuple))
3487 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3488 namespaceId = get_namespace_oid(rname, true);
3489 ReleaseSysCache(tuple);
3490 if (OidIsValid(namespaceId) &&
3491 !list_member_oid(oidlist, namespaceId) &&
3492 pg_namespace_aclcheck(namespaceId, roleid,
3493 ACL_USAGE) == ACLCHECK_OK &&
3494 InvokeNamespaceSearchHook(namespaceId, false))
3495 oidlist = lappend_oid(oidlist, namespaceId);
3498 else if (strcmp(curname, "pg_temp") == 0)
3500 /* pg_temp --- substitute temp namespace, if any */
3501 if (OidIsValid(myTempNamespace))
3503 if (!list_member_oid(oidlist, myTempNamespace) &&
3504 InvokeNamespaceSearchHook(myTempNamespace, false))
3505 oidlist = lappend_oid(oidlist, myTempNamespace);
3509 /* If it ought to be the creation namespace, set flag */
3511 temp_missing = true;
3516 /* normal namespace reference */
3517 namespaceId = get_namespace_oid(curname, true);
3518 if (OidIsValid(namespaceId) &&
3519 !list_member_oid(oidlist, namespaceId) &&
3520 pg_namespace_aclcheck(namespaceId, roleid,
3521 ACL_USAGE) == ACLCHECK_OK &&
3522 InvokeNamespaceSearchHook(namespaceId, false))
3523 oidlist = lappend_oid(oidlist, namespaceId);
3528 * Remember the first member of the explicit list. (Note: this is
3529 * nominally wrong if temp_missing, but we need it anyway to distinguish
3530 * explicit from implicit mention of pg_catalog.)
3533 firstNS = InvalidOid;
3535 firstNS = linitial_oid(oidlist);
3538 * Add any implicitly-searched namespaces to the list. Note these go on
3539 * the front, not the back; also notice that we do not check USAGE
3540 * permissions for these.
3542 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3543 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3545 if (OidIsValid(myTempNamespace) &&
3546 !list_member_oid(oidlist, myTempNamespace))
3547 oidlist = lcons_oid(myTempNamespace, oidlist);
3550 * Now that we've successfully built the new list of namespace OIDs, save
3551 * it in permanent storage.
3553 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3554 newpath = list_copy(oidlist);
3555 MemoryContextSwitchTo(oldcxt);
3557 /* Now safe to assign to state variables. */
3558 list_free(baseSearchPath);
3559 baseSearchPath = newpath;
3560 baseCreationNamespace = firstNS;
3561 baseTempCreationPending = temp_missing;
3563 /* Mark the path valid. */
3564 baseSearchPathValid = true;
3565 namespaceUser = roleid;
3567 /* And make it active. */
3568 activeSearchPath = baseSearchPath;
3569 activeCreationNamespace = baseCreationNamespace;
3570 activeTempCreationPending = baseTempCreationPending;
3574 list_free(namelist);
3579 * InitTempTableNamespace
3580 * Initialize temp table namespace on first use in a particular backend
3583 InitTempTableNamespace(void)
3585 char namespaceName[NAMEDATALEN];
3589 Assert(!OidIsValid(myTempNamespace));
3592 * First, do permission check to see if we are authorized to make temp
3593 * tables. We use a nonstandard error message here since "databasename:
3594 * permission denied" might be a tad cryptic.
3596 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3597 * that's necessary since current user ID could change during the session.
3598 * But there's no need to make the namespace in the first place until a
3599 * temp table creation request is made by someone with appropriate rights.
3601 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3602 ACL_CREATE_TEMP) != ACLCHECK_OK)
3604 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3605 errmsg("permission denied to create temporary tables in database \"%s\"",
3606 get_database_name(MyDatabaseId))));
3609 * Do not allow a Hot Standby slave session to make temp tables. Aside
3610 * from problems with modifying the system catalogs, there is a naming
3611 * conflict: pg_temp_N belongs to the session with BackendId N on the
3612 * master, not to a slave session with the same BackendId. We should not
3613 * be able to get here anyway due to XactReadOnly checks, but let's just
3614 * make real sure. Note that this also backstops various operations that
3615 * allow XactReadOnly transactions to modify temp tables; they'd need
3616 * RecoveryInProgress checks if not for this.
3618 if (RecoveryInProgress())
3620 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3621 errmsg("cannot create temporary tables during recovery")));
3623 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3625 namespaceId = get_namespace_oid(namespaceName, true);
3626 if (!OidIsValid(namespaceId))
3629 * First use of this temp namespace in this database; create it. The
3630 * temp namespaces are always owned by the superuser. We leave their
3631 * permissions at default --- i.e., no access except to superuser ---
3632 * to ensure that unprivileged users can't peek at other backends'
3633 * temp tables. This works because the places that access the temp
3634 * namespace for my own backend skip permissions checks on it.
3636 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3638 /* Advance command counter to make namespace visible */
3639 CommandCounterIncrement();
3644 * If the namespace already exists, clean it out (in case the former
3645 * owner crashed without doing so).
3647 RemoveTempRelations(namespaceId);
3651 * If the corresponding toast-table namespace doesn't exist yet, create
3652 * it. (We assume there is no need to clean it out if it does exist, since
3653 * dropping a parent table should make its toast table go away.)
3655 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3658 toastspaceId = get_namespace_oid(namespaceName, true);
3659 if (!OidIsValid(toastspaceId))
3661 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3663 /* Advance command counter to make namespace visible */
3664 CommandCounterIncrement();
3668 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3669 * so all our work could be undone by transaction rollback. Set flag for
3670 * AtEOXact_Namespace to know what to do.
3672 myTempNamespace = namespaceId;
3673 myTempToastNamespace = toastspaceId;
3675 /* It should not be done already. */
3676 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3677 myTempNamespaceSubID = GetCurrentSubTransactionId();
3679 baseSearchPathValid = false; /* need to rebuild list */
3683 * End-of-transaction cleanup for namespaces.
3686 AtEOXact_Namespace(bool isCommit)
3689 * If we abort the transaction in which a temp namespace was selected,
3690 * we'll have to do any creation or cleanout work over again. So, just
3691 * forget the namespace entirely until next time. On the other hand, if
3692 * we commit then register an exit callback to clean out the temp tables
3693 * at backend shutdown. (We only want to register the callback once per
3694 * session, so this is a good place to do it.)
3696 if (myTempNamespaceSubID != InvalidSubTransactionId)
3699 before_shmem_exit(RemoveTempRelationsCallback, 0);
3702 myTempNamespace = InvalidOid;
3703 myTempToastNamespace = InvalidOid;
3704 baseSearchPathValid = false; /* need to rebuild list */
3706 myTempNamespaceSubID = InvalidSubTransactionId;
3710 * Clean up if someone failed to do PopOverrideSearchPath
3715 elog(WARNING, "leaked override search path");
3716 while (overrideStack)
3718 OverrideStackEntry *entry;
3720 entry = (OverrideStackEntry *) linitial(overrideStack);
3721 overrideStack = list_delete_first(overrideStack);
3722 list_free(entry->searchPath);
3725 /* If not baseSearchPathValid, this is useless but harmless */
3726 activeSearchPath = baseSearchPath;
3727 activeCreationNamespace = baseCreationNamespace;
3728 activeTempCreationPending = baseTempCreationPending;
3733 * AtEOSubXact_Namespace
3735 * At subtransaction commit, propagate the temp-namespace-creation
3736 * flag to the parent subtransaction.
3738 * At subtransaction abort, forget the flag if we set it up.
3741 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3742 SubTransactionId parentSubid)
3744 OverrideStackEntry *entry;
3746 if (myTempNamespaceSubID == mySubid)
3749 myTempNamespaceSubID = parentSubid;
3752 myTempNamespaceSubID = InvalidSubTransactionId;
3753 /* TEMP namespace creation failed, so reset state */
3754 myTempNamespace = InvalidOid;
3755 myTempToastNamespace = InvalidOid;
3756 baseSearchPathValid = false; /* need to rebuild list */
3761 * Clean up if someone failed to do PopOverrideSearchPath
3763 while (overrideStack)
3765 entry = (OverrideStackEntry *) linitial(overrideStack);
3766 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3769 elog(WARNING, "leaked override search path");
3770 overrideStack = list_delete_first(overrideStack);
3771 list_free(entry->searchPath);
3775 /* Activate the next level down. */
3778 entry = (OverrideStackEntry *) linitial(overrideStack);
3779 activeSearchPath = entry->searchPath;
3780 activeCreationNamespace = entry->creationNamespace;
3781 activeTempCreationPending = false; /* XXX is this OK? */
3785 /* If not baseSearchPathValid, this is useless but harmless */
3786 activeSearchPath = baseSearchPath;
3787 activeCreationNamespace = baseCreationNamespace;
3788 activeTempCreationPending = baseTempCreationPending;
3793 * Remove all relations in the specified temp namespace.
3795 * This is called at backend shutdown (if we made any temp relations).
3796 * It is also called when we begin using a pre-existing temp namespace,
3797 * in order to clean out any relations that might have been created by
3798 * a crashed backend.
3801 RemoveTempRelations(Oid tempNamespaceId)
3803 ObjectAddress object;
3806 * We want to get rid of everything in the target namespace, but not the
3807 * namespace itself (deleting it only to recreate it later would be a
3808 * waste of cycles). We do this by finding everything that has a
3809 * dependency on the namespace.
3811 object.classId = NamespaceRelationId;
3812 object.objectId = tempNamespaceId;
3813 object.objectSubId = 0;
3815 deleteWhatDependsOn(&object, false);
3819 * Callback to remove temp relations at backend exit.
3822 RemoveTempRelationsCallback(int code, Datum arg)
3824 if (OidIsValid(myTempNamespace)) /* should always be true */
3826 /* Need to ensure we have a usable transaction. */
3827 AbortOutOfAnyTransaction();
3828 StartTransactionCommand();
3830 RemoveTempRelations(myTempNamespace);
3832 CommitTransactionCommand();
3837 * Remove all temp tables from the temporary namespace.
3840 ResetTempTableNamespace(void)
3842 if (OidIsValid(myTempNamespace))
3843 RemoveTempRelations(myTempNamespace);
3848 * Routines for handling the GUC variable 'search_path'.
3851 /* check_hook: validate new search_path value */
3853 check_search_path(char **newval, void **extra, GucSource source)
3858 /* Need a modifiable copy of string */
3859 rawname = pstrdup(*newval);
3861 /* Parse string into list of identifiers */
3862 if (!SplitIdentifierString(rawname, ',', &namelist))
3864 /* syntax error in name list */
3865 GUC_check_errdetail("List syntax is invalid.");
3867 list_free(namelist);
3872 * We used to try to check that the named schemas exist, but there are
3873 * many valid use-cases for having search_path settings that include
3874 * schemas that don't exist; and often, we are not inside a transaction
3875 * here and so can't consult the system catalogs anyway. So now, the only
3876 * requirement is syntactic validity of the identifier list.
3880 list_free(namelist);
3885 /* assign_hook: do extra actions as needed */
3887 assign_search_path(const char *newval, void *extra)
3890 * We mark the path as needing recomputation, but don't do anything until
3891 * it's needed. This avoids trying to do database access during GUC
3892 * initialization, or outside a transaction.
3894 baseSearchPathValid = false;
3898 * InitializeSearchPath: initialize module during InitPostgres.
3900 * This is called after we are up enough to be able to do catalog lookups.
3903 InitializeSearchPath(void)
3905 if (IsBootstrapProcessingMode())
3908 * In bootstrap mode, the search path must be 'pg_catalog' so that
3909 * tables are created in the proper namespace; ignore the GUC setting.
3911 MemoryContext oldcxt;
3913 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3914 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3915 MemoryContextSwitchTo(oldcxt);
3916 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3917 baseTempCreationPending = false;
3918 baseSearchPathValid = true;
3919 namespaceUser = GetUserId();
3920 activeSearchPath = baseSearchPath;
3921 activeCreationNamespace = baseCreationNamespace;
3922 activeTempCreationPending = baseTempCreationPending;
3927 * In normal mode, arrange for a callback on any syscache invalidation
3928 * of pg_namespace rows.
3930 CacheRegisterSyscacheCallback(NAMESPACEOID,
3933 /* Force search path to be recomputed on next use */
3934 baseSearchPathValid = false;
3940 * Syscache inval callback function
3943 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3945 /* Force search path to be recomputed on next use */
3946 baseSearchPathValid = false;
3950 * Fetch the active search path. The return value is a palloc'ed list
3951 * of OIDs; the caller is responsible for freeing this storage as
3954 * The returned list includes the implicitly-prepended namespaces only if
3955 * includeImplicit is true.
3957 * Note: calling this may result in a CommandCounterIncrement operation,
3958 * if we have to create or clean out the temp namespace.
3961 fetch_search_path(bool includeImplicit)
3965 recomputeNamespacePath();
3968 * If the temp namespace should be first, force it to exist. This is so
3969 * that callers can trust the result to reflect the actual default
3970 * creation namespace. It's a bit bogus to do this here, since
3971 * current_schema() is supposedly a stable function without side-effects,
3972 * but the alternatives seem worse.
3974 if (activeTempCreationPending)
3976 InitTempTableNamespace();
3977 recomputeNamespacePath();
3980 result = list_copy(activeSearchPath);
3981 if (!includeImplicit)
3983 while (result && linitial_oid(result) != activeCreationNamespace)
3984 result = list_delete_first(result);
3991 * Fetch the active search path into a caller-allocated array of OIDs.
3992 * Returns the number of path entries. (If this is more than sarray_len,
3993 * then the data didn't fit and is not all stored.)
3995 * The returned list always includes the implicitly-prepended namespaces,
3996 * but never includes the temp namespace. (This is suitable for existing
3997 * users, which would want to ignore the temp namespace anyway.) This
3998 * definition allows us to not worry about initializing the temp namespace.
4001 fetch_search_path_array(Oid *sarray, int sarray_len)
4006 recomputeNamespacePath();
4008 foreach(l, activeSearchPath)
4010 Oid namespaceId = lfirst_oid(l);
4012 if (namespaceId == myTempNamespace)
4013 continue; /* do not include temp namespace */
4015 if (count < sarray_len)
4016 sarray[count] = namespaceId;
4025 * Export the FooIsVisible functions as SQL-callable functions.
4027 * Note: as of Postgres 8.4, these will silently return NULL if called on
4028 * a nonexistent object OID, rather than failing. This is to avoid race
4029 * condition errors when a query that's scanning a catalog using an MVCC
4030 * snapshot uses one of these functions. The underlying IsVisible functions
4031 * always use an up-to-date snapshot and so might see the object as already
4032 * gone when it's still visible to the transaction snapshot. (There is no race
4033 * condition in the current coding because we don't accept sinval messages
4034 * between the SearchSysCacheExists test and the subsequent lookup.)
4038 pg_table_is_visible(PG_FUNCTION_ARGS)
4040 Oid oid = PG_GETARG_OID(0);
4042 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
4045 PG_RETURN_BOOL(RelationIsVisible(oid));
4049 pg_type_is_visible(PG_FUNCTION_ARGS)
4051 Oid oid = PG_GETARG_OID(0);
4053 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
4056 PG_RETURN_BOOL(TypeIsVisible(oid));
4060 pg_function_is_visible(PG_FUNCTION_ARGS)
4062 Oid oid = PG_GETARG_OID(0);
4064 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
4067 PG_RETURN_BOOL(FunctionIsVisible(oid));
4071 pg_operator_is_visible(PG_FUNCTION_ARGS)
4073 Oid oid = PG_GETARG_OID(0);
4075 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4078 PG_RETURN_BOOL(OperatorIsVisible(oid));
4082 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4084 Oid oid = PG_GETARG_OID(0);
4086 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4089 PG_RETURN_BOOL(OpclassIsVisible(oid));
4093 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4095 Oid oid = PG_GETARG_OID(0);
4097 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4100 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4104 pg_collation_is_visible(PG_FUNCTION_ARGS)
4106 Oid oid = PG_GETARG_OID(0);
4108 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4111 PG_RETURN_BOOL(CollationIsVisible(oid));
4115 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4117 Oid oid = PG_GETARG_OID(0);
4119 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4122 PG_RETURN_BOOL(ConversionIsVisible(oid));
4126 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4128 Oid oid = PG_GETARG_OID(0);
4130 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4133 PG_RETURN_BOOL(TSParserIsVisible(oid));
4137 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4139 Oid oid = PG_GETARG_OID(0);
4141 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4144 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4148 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4150 Oid oid = PG_GETARG_OID(0);
4152 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4155 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4159 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4161 Oid oid = PG_GETARG_OID(0);
4163 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4166 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4170 pg_my_temp_schema(PG_FUNCTION_ARGS)
4172 PG_RETURN_OID(myTempNamespace);
4176 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4178 Oid oid = PG_GETARG_OID(0);
4180 PG_RETURN_BOOL(isOtherTempNamespace(oid));