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)
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, false);
1580 /* flag to indicate we need namespace search */
1581 namespaceId = InvalidOid;
1582 recomputeNamespacePath();
1585 /* Search syscache by name only */
1586 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1589 * In typical scenarios, most if not all of the operators found by the
1590 * catcache search will end up getting returned; and there can be quite a
1591 * few, for common operator names such as '=' or '+'. To reduce the time
1592 * spent in palloc, we allocate the result space as an array large enough
1593 * to hold all the operators. The original coding of this routine did a
1594 * separate palloc for each operator, but profiling revealed that the
1595 * pallocs used an unreasonably large fraction of parsing time.
1597 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1599 if (catlist->n_members > 0)
1600 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1602 for (i = 0; i < catlist->n_members; i++)
1604 HeapTuple opertup = &catlist->members[i]->tuple;
1605 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1607 FuncCandidateList newResult;
1609 /* Ignore operators of wrong kind, if specific kind requested */
1610 if (oprkind && operform->oprkind != oprkind)
1613 if (OidIsValid(namespaceId))
1615 /* Consider only opers in specified namespace */
1616 if (operform->oprnamespace != namespaceId)
1618 /* No need to check args, they must all be different */
1623 * Consider only opers that are in the search path and are not in
1624 * the temp namespace.
1628 foreach(nsp, activeSearchPath)
1630 if (operform->oprnamespace == lfirst_oid(nsp) &&
1631 operform->oprnamespace != myTempNamespace)
1636 continue; /* oper is not in search path */
1639 * Okay, it's in the search path, but does it have the same
1640 * arguments as something we already accepted? If so, keep only
1641 * the one that appears earlier in the search path.
1643 * If we have an ordered list from SearchSysCacheList (the normal
1644 * case), then any conflicting oper must immediately adjoin this
1645 * one in the list, so we only need to look at the newest result
1646 * item. If we have an unordered list, we have to scan the whole
1651 FuncCandidateList prevResult;
1653 if (catlist->ordered)
1655 if (operform->oprleft == resultList->args[0] &&
1656 operform->oprright == resultList->args[1])
1657 prevResult = resultList;
1663 for (prevResult = resultList;
1665 prevResult = prevResult->next)
1667 if (operform->oprleft == prevResult->args[0] &&
1668 operform->oprright == prevResult->args[1])
1674 /* We have a match with a previous result */
1675 Assert(pathpos != prevResult->pathpos);
1676 if (pathpos > prevResult->pathpos)
1677 continue; /* keep previous result */
1678 /* replace previous result */
1679 prevResult->pathpos = pathpos;
1680 prevResult->oid = HeapTupleGetOid(opertup);
1681 continue; /* args are same, of course */
1687 * Okay to add it to result list
1689 newResult = (FuncCandidateList) (resultSpace + nextResult);
1690 nextResult += SPACE_PER_OP;
1692 newResult->pathpos = pathpos;
1693 newResult->oid = HeapTupleGetOid(opertup);
1694 newResult->nargs = 2;
1695 newResult->nvargs = 0;
1696 newResult->ndargs = 0;
1697 newResult->argnumbers = NULL;
1698 newResult->args[0] = operform->oprleft;
1699 newResult->args[1] = operform->oprright;
1700 newResult->next = resultList;
1701 resultList = newResult;
1704 ReleaseSysCacheList(catlist);
1711 * Determine whether an operator (identified by OID) is visible in the
1712 * current search path. Visible means "would be found by searching
1713 * for the unqualified operator name with exact argument matches".
1716 OperatorIsVisible(Oid oprid)
1719 Form_pg_operator oprform;
1723 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1724 if (!HeapTupleIsValid(oprtup))
1725 elog(ERROR, "cache lookup failed for operator %u", oprid);
1726 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1728 recomputeNamespacePath();
1731 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1732 * the system namespace are surely in the path and so we needn't even do
1733 * list_member_oid() for them.
1735 oprnamespace = oprform->oprnamespace;
1736 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1737 !list_member_oid(activeSearchPath, oprnamespace))
1742 * If it is in the path, it might still not be visible; it could be
1743 * hidden by another operator of the same name and arguments earlier
1744 * in the path. So we must do a slow check to see if this is the same
1745 * operator that would be found by OpernameGetOprid.
1747 char *oprname = NameStr(oprform->oprname);
1749 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1750 oprform->oprleft, oprform->oprright)
1754 ReleaseSysCache(oprtup);
1761 * OpclassnameGetOpcid
1762 * Try to resolve an unqualified index opclass name.
1763 * Returns OID if opclass found in search path, else InvalidOid.
1765 * This is essentially the same as TypenameGetTypid, but we have to have
1766 * an extra argument for the index AM OID.
1769 OpclassnameGetOpcid(Oid amid, const char *opcname)
1774 recomputeNamespacePath();
1776 foreach(l, activeSearchPath)
1778 Oid namespaceId = lfirst_oid(l);
1780 if (namespaceId == myTempNamespace)
1781 continue; /* do not look in temp namespace */
1783 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1784 ObjectIdGetDatum(amid),
1785 PointerGetDatum(opcname),
1786 ObjectIdGetDatum(namespaceId));
1787 if (OidIsValid(opcid))
1791 /* Not found in path */
1797 * Determine whether an opclass (identified by OID) is visible in the
1798 * current search path. Visible means "would be found by searching
1799 * for the unqualified opclass name".
1802 OpclassIsVisible(Oid opcid)
1805 Form_pg_opclass opcform;
1809 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1810 if (!HeapTupleIsValid(opctup))
1811 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1812 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1814 recomputeNamespacePath();
1817 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1818 * the system namespace are surely in the path and so we needn't even do
1819 * list_member_oid() for them.
1821 opcnamespace = opcform->opcnamespace;
1822 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1823 !list_member_oid(activeSearchPath, opcnamespace))
1828 * If it is in the path, it might still not be visible; it could be
1829 * hidden by another opclass of the same name earlier in the path. So
1830 * we must do a slow check to see if this opclass would be found by
1831 * OpclassnameGetOpcid.
1833 char *opcname = NameStr(opcform->opcname);
1835 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1838 ReleaseSysCache(opctup);
1844 * OpfamilynameGetOpfid
1845 * Try to resolve an unqualified index opfamily name.
1846 * Returns OID if opfamily found in search path, else InvalidOid.
1848 * This is essentially the same as TypenameGetTypid, but we have to have
1849 * an extra argument for the index AM OID.
1852 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1857 recomputeNamespacePath();
1859 foreach(l, activeSearchPath)
1861 Oid namespaceId = lfirst_oid(l);
1863 if (namespaceId == myTempNamespace)
1864 continue; /* do not look in temp namespace */
1866 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1867 ObjectIdGetDatum(amid),
1868 PointerGetDatum(opfname),
1869 ObjectIdGetDatum(namespaceId));
1870 if (OidIsValid(opfid))
1874 /* Not found in path */
1880 * Determine whether an opfamily (identified by OID) is visible in the
1881 * current search path. Visible means "would be found by searching
1882 * for the unqualified opfamily name".
1885 OpfamilyIsVisible(Oid opfid)
1888 Form_pg_opfamily opfform;
1892 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1893 if (!HeapTupleIsValid(opftup))
1894 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1895 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1897 recomputeNamespacePath();
1900 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1901 * the system namespace are surely in the path and so we needn't even do
1902 * list_member_oid() for them.
1904 opfnamespace = opfform->opfnamespace;
1905 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1906 !list_member_oid(activeSearchPath, opfnamespace))
1911 * If it is in the path, it might still not be visible; it could be
1912 * hidden by another opfamily of the same name earlier in the path. So
1913 * we must do a slow check to see if this opfamily would be found by
1914 * OpfamilynameGetOpfid.
1916 char *opfname = NameStr(opfform->opfname);
1918 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1921 ReleaseSysCache(opftup);
1927 * CollationGetCollid
1928 * Try to resolve an unqualified collation name.
1929 * Returns OID if collation found in search path, else InvalidOid.
1932 CollationGetCollid(const char *collname)
1934 int32 dbencoding = GetDatabaseEncoding();
1937 recomputeNamespacePath();
1939 foreach(l, activeSearchPath)
1941 Oid namespaceId = lfirst_oid(l);
1944 if (namespaceId == myTempNamespace)
1945 continue; /* do not look in temp namespace */
1947 /* Check for database-encoding-specific entry */
1948 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1949 PointerGetDatum(collname),
1950 Int32GetDatum(dbencoding),
1951 ObjectIdGetDatum(namespaceId));
1952 if (OidIsValid(collid))
1955 /* Check for any-encoding entry */
1956 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1957 PointerGetDatum(collname),
1959 ObjectIdGetDatum(namespaceId));
1960 if (OidIsValid(collid))
1964 /* Not found in path */
1969 * CollationIsVisible
1970 * Determine whether a collation (identified by OID) is visible in the
1971 * current search path. Visible means "would be found by searching
1972 * for the unqualified collation name".
1975 CollationIsVisible(Oid collid)
1978 Form_pg_collation collform;
1982 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1983 if (!HeapTupleIsValid(colltup))
1984 elog(ERROR, "cache lookup failed for collation %u", collid);
1985 collform = (Form_pg_collation) GETSTRUCT(colltup);
1987 recomputeNamespacePath();
1990 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1991 * the system namespace are surely in the path and so we needn't even do
1992 * list_member_oid() for them.
1994 collnamespace = collform->collnamespace;
1995 if (collnamespace != PG_CATALOG_NAMESPACE &&
1996 !list_member_oid(activeSearchPath, collnamespace))
2001 * If it is in the path, it might still not be visible; it could be
2002 * hidden by another conversion of the same name earlier in the path.
2003 * So we must do a slow check to see if this conversion would be found
2004 * by CollationGetCollid.
2006 char *collname = NameStr(collform->collname);
2008 visible = (CollationGetCollid(collname) == collid);
2011 ReleaseSysCache(colltup);
2018 * ConversionGetConid
2019 * Try to resolve an unqualified conversion name.
2020 * Returns OID if conversion found in search path, else InvalidOid.
2022 * This is essentially the same as RelnameGetRelid.
2025 ConversionGetConid(const char *conname)
2030 recomputeNamespacePath();
2032 foreach(l, activeSearchPath)
2034 Oid namespaceId = lfirst_oid(l);
2036 if (namespaceId == myTempNamespace)
2037 continue; /* do not look in temp namespace */
2039 conid = GetSysCacheOid2(CONNAMENSP,
2040 PointerGetDatum(conname),
2041 ObjectIdGetDatum(namespaceId));
2042 if (OidIsValid(conid))
2046 /* Not found in path */
2051 * ConversionIsVisible
2052 * Determine whether a conversion (identified by OID) is visible in the
2053 * current search path. Visible means "would be found by searching
2054 * for the unqualified conversion name".
2057 ConversionIsVisible(Oid conid)
2060 Form_pg_conversion conform;
2064 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2065 if (!HeapTupleIsValid(contup))
2066 elog(ERROR, "cache lookup failed for conversion %u", conid);
2067 conform = (Form_pg_conversion) GETSTRUCT(contup);
2069 recomputeNamespacePath();
2072 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2073 * the system namespace are surely in the path and so we needn't even do
2074 * list_member_oid() for them.
2076 connamespace = conform->connamespace;
2077 if (connamespace != PG_CATALOG_NAMESPACE &&
2078 !list_member_oid(activeSearchPath, connamespace))
2083 * If it is in the path, it might still not be visible; it could be
2084 * hidden by another conversion of the same name earlier in the path.
2085 * So we must do a slow check to see if this conversion would be found
2086 * by ConversionGetConid.
2088 char *conname = NameStr(conform->conname);
2090 visible = (ConversionGetConid(conname) == conid);
2093 ReleaseSysCache(contup);
2099 * get_ts_parser_oid - find a TS parser by possibly qualified name
2101 * If not found, returns InvalidOid if missing_ok, else throws error
2104 get_ts_parser_oid(List *names, bool missing_ok)
2109 Oid prsoid = InvalidOid;
2112 /* deconstruct the name list */
2113 DeconstructQualifiedName(names, &schemaname, &parser_name);
2117 /* use exact schema given */
2118 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2119 if (missing_ok && !OidIsValid(namespaceId))
2120 prsoid = InvalidOid;
2122 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2123 PointerGetDatum(parser_name),
2124 ObjectIdGetDatum(namespaceId));
2128 /* search for it in search path */
2129 recomputeNamespacePath();
2131 foreach(l, activeSearchPath)
2133 namespaceId = lfirst_oid(l);
2135 if (namespaceId == myTempNamespace)
2136 continue; /* do not look in temp namespace */
2138 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2139 PointerGetDatum(parser_name),
2140 ObjectIdGetDatum(namespaceId));
2141 if (OidIsValid(prsoid))
2146 if (!OidIsValid(prsoid) && !missing_ok)
2148 (errcode(ERRCODE_UNDEFINED_OBJECT),
2149 errmsg("text search parser \"%s\" does not exist",
2150 NameListToString(names))));
2157 * Determine whether a parser (identified by OID) is visible in the
2158 * current search path. Visible means "would be found by searching
2159 * for the unqualified parser name".
2162 TSParserIsVisible(Oid prsId)
2165 Form_pg_ts_parser form;
2169 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2170 if (!HeapTupleIsValid(tup))
2171 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2172 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2174 recomputeNamespacePath();
2177 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2178 * the system namespace are surely in the path and so we needn't even do
2179 * list_member_oid() for them.
2181 namespace = form->prsnamespace;
2182 if (namespace != PG_CATALOG_NAMESPACE &&
2183 !list_member_oid(activeSearchPath, namespace))
2188 * If it is in the path, it might still not be visible; it could be
2189 * hidden by another parser of the same name earlier in the path. So
2190 * we must do a slow check for conflicting parsers.
2192 char *name = NameStr(form->prsname);
2196 foreach(l, activeSearchPath)
2198 Oid namespaceId = lfirst_oid(l);
2200 if (namespaceId == myTempNamespace)
2201 continue; /* do not look in temp namespace */
2203 if (namespaceId == namespace)
2205 /* Found it first in path */
2209 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2210 PointerGetDatum(name),
2211 ObjectIdGetDatum(namespaceId)))
2213 /* Found something else first in path */
2219 ReleaseSysCache(tup);
2225 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2227 * If not found, returns InvalidOid if failOK, else throws error
2230 get_ts_dict_oid(List *names, bool missing_ok)
2235 Oid dictoid = InvalidOid;
2238 /* deconstruct the name list */
2239 DeconstructQualifiedName(names, &schemaname, &dict_name);
2243 /* use exact schema given */
2244 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2245 if (missing_ok && !OidIsValid(namespaceId))
2246 dictoid = InvalidOid;
2248 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2249 PointerGetDatum(dict_name),
2250 ObjectIdGetDatum(namespaceId));
2254 /* search for it in search path */
2255 recomputeNamespacePath();
2257 foreach(l, activeSearchPath)
2259 namespaceId = lfirst_oid(l);
2261 if (namespaceId == myTempNamespace)
2262 continue; /* do not look in temp namespace */
2264 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2265 PointerGetDatum(dict_name),
2266 ObjectIdGetDatum(namespaceId));
2267 if (OidIsValid(dictoid))
2272 if (!OidIsValid(dictoid) && !missing_ok)
2274 (errcode(ERRCODE_UNDEFINED_OBJECT),
2275 errmsg("text search dictionary \"%s\" does not exist",
2276 NameListToString(names))));
2282 * TSDictionaryIsVisible
2283 * Determine whether a dictionary (identified by OID) is visible in the
2284 * current search path. Visible means "would be found by searching
2285 * for the unqualified dictionary name".
2288 TSDictionaryIsVisible(Oid dictId)
2291 Form_pg_ts_dict form;
2295 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2296 if (!HeapTupleIsValid(tup))
2297 elog(ERROR, "cache lookup failed for text search dictionary %u",
2299 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2301 recomputeNamespacePath();
2304 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2305 * the system namespace are surely in the path and so we needn't even do
2306 * list_member_oid() for them.
2308 namespace = form->dictnamespace;
2309 if (namespace != PG_CATALOG_NAMESPACE &&
2310 !list_member_oid(activeSearchPath, namespace))
2315 * If it is in the path, it might still not be visible; it could be
2316 * hidden by another dictionary of the same name earlier in the path.
2317 * So we must do a slow check for conflicting dictionaries.
2319 char *name = NameStr(form->dictname);
2323 foreach(l, activeSearchPath)
2325 Oid namespaceId = lfirst_oid(l);
2327 if (namespaceId == myTempNamespace)
2328 continue; /* do not look in temp namespace */
2330 if (namespaceId == namespace)
2332 /* Found it first in path */
2336 if (SearchSysCacheExists2(TSDICTNAMENSP,
2337 PointerGetDatum(name),
2338 ObjectIdGetDatum(namespaceId)))
2340 /* Found something else first in path */
2346 ReleaseSysCache(tup);
2352 * get_ts_template_oid - find a TS template by possibly qualified name
2354 * If not found, returns InvalidOid if missing_ok, else throws error
2357 get_ts_template_oid(List *names, bool missing_ok)
2360 char *template_name;
2362 Oid tmploid = InvalidOid;
2365 /* deconstruct the name list */
2366 DeconstructQualifiedName(names, &schemaname, &template_name);
2370 /* use exact schema given */
2371 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2372 if (missing_ok && !OidIsValid(namespaceId))
2373 tmploid = InvalidOid;
2375 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2376 PointerGetDatum(template_name),
2377 ObjectIdGetDatum(namespaceId));
2381 /* search for it in search path */
2382 recomputeNamespacePath();
2384 foreach(l, activeSearchPath)
2386 namespaceId = lfirst_oid(l);
2388 if (namespaceId == myTempNamespace)
2389 continue; /* do not look in temp namespace */
2391 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2392 PointerGetDatum(template_name),
2393 ObjectIdGetDatum(namespaceId));
2394 if (OidIsValid(tmploid))
2399 if (!OidIsValid(tmploid) && !missing_ok)
2401 (errcode(ERRCODE_UNDEFINED_OBJECT),
2402 errmsg("text search template \"%s\" does not exist",
2403 NameListToString(names))));
2409 * TSTemplateIsVisible
2410 * Determine whether a template (identified by OID) is visible in the
2411 * current search path. Visible means "would be found by searching
2412 * for the unqualified template name".
2415 TSTemplateIsVisible(Oid tmplId)
2418 Form_pg_ts_template form;
2422 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2423 if (!HeapTupleIsValid(tup))
2424 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2425 form = (Form_pg_ts_template) GETSTRUCT(tup);
2427 recomputeNamespacePath();
2430 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2431 * the system namespace are surely in the path and so we needn't even do
2432 * list_member_oid() for them.
2434 namespace = form->tmplnamespace;
2435 if (namespace != PG_CATALOG_NAMESPACE &&
2436 !list_member_oid(activeSearchPath, namespace))
2441 * If it is in the path, it might still not be visible; it could be
2442 * hidden by another template of the same name earlier in the path. So
2443 * we must do a slow check for conflicting templates.
2445 char *name = NameStr(form->tmplname);
2449 foreach(l, activeSearchPath)
2451 Oid namespaceId = lfirst_oid(l);
2453 if (namespaceId == myTempNamespace)
2454 continue; /* do not look in temp namespace */
2456 if (namespaceId == namespace)
2458 /* Found it first in path */
2462 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2463 PointerGetDatum(name),
2464 ObjectIdGetDatum(namespaceId)))
2466 /* Found something else first in path */
2472 ReleaseSysCache(tup);
2478 * get_ts_config_oid - find a TS config by possibly qualified name
2480 * If not found, returns InvalidOid if missing_ok, else throws error
2483 get_ts_config_oid(List *names, bool missing_ok)
2488 Oid cfgoid = InvalidOid;
2491 /* deconstruct the name list */
2492 DeconstructQualifiedName(names, &schemaname, &config_name);
2496 /* use exact schema given */
2497 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2498 if (missing_ok && !OidIsValid(namespaceId))
2499 cfgoid = InvalidOid;
2501 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2502 PointerGetDatum(config_name),
2503 ObjectIdGetDatum(namespaceId));
2507 /* search for it in search path */
2508 recomputeNamespacePath();
2510 foreach(l, activeSearchPath)
2512 namespaceId = lfirst_oid(l);
2514 if (namespaceId == myTempNamespace)
2515 continue; /* do not look in temp namespace */
2517 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2518 PointerGetDatum(config_name),
2519 ObjectIdGetDatum(namespaceId));
2520 if (OidIsValid(cfgoid))
2525 if (!OidIsValid(cfgoid) && !missing_ok)
2527 (errcode(ERRCODE_UNDEFINED_OBJECT),
2528 errmsg("text search configuration \"%s\" does not exist",
2529 NameListToString(names))));
2536 * Determine whether a text search configuration (identified by OID)
2537 * is visible in the current search path. Visible means "would be found
2538 * by searching for the unqualified text search configuration name".
2541 TSConfigIsVisible(Oid cfgid)
2544 Form_pg_ts_config form;
2548 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2549 if (!HeapTupleIsValid(tup))
2550 elog(ERROR, "cache lookup failed for text search configuration %u",
2552 form = (Form_pg_ts_config) GETSTRUCT(tup);
2554 recomputeNamespacePath();
2557 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2558 * the system namespace are surely in the path and so we needn't even do
2559 * list_member_oid() for them.
2561 namespace = form->cfgnamespace;
2562 if (namespace != PG_CATALOG_NAMESPACE &&
2563 !list_member_oid(activeSearchPath, namespace))
2568 * If it is in the path, it might still not be visible; it could be
2569 * hidden by another configuration of the same name earlier in the
2570 * path. So we must do a slow check for conflicting configurations.
2572 char *name = NameStr(form->cfgname);
2576 foreach(l, activeSearchPath)
2578 Oid namespaceId = lfirst_oid(l);
2580 if (namespaceId == myTempNamespace)
2581 continue; /* do not look in temp namespace */
2583 if (namespaceId == namespace)
2585 /* Found it first in path */
2589 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2590 PointerGetDatum(name),
2591 ObjectIdGetDatum(namespaceId)))
2593 /* Found something else first in path */
2599 ReleaseSysCache(tup);
2606 * DeconstructQualifiedName
2607 * Given a possibly-qualified name expressed as a list of String nodes,
2608 * extract the schema name and object name.
2610 * *nspname_p is set to NULL if there is no explicit schema name.
2613 DeconstructQualifiedName(List *names,
2618 char *schemaname = NULL;
2619 char *objname = NULL;
2621 switch (list_length(names))
2624 objname = strVal(linitial(names));
2627 schemaname = strVal(linitial(names));
2628 objname = strVal(lsecond(names));
2631 catalogname = strVal(linitial(names));
2632 schemaname = strVal(lsecond(names));
2633 objname = strVal(lthird(names));
2636 * We check the catalog name and then ignore it.
2638 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2640 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2641 errmsg("cross-database references are not implemented: %s",
2642 NameListToString(names))));
2646 (errcode(ERRCODE_SYNTAX_ERROR),
2647 errmsg("improper qualified name (too many dotted names): %s",
2648 NameListToString(names))));
2652 *nspname_p = schemaname;
2653 *objname_p = objname;
2657 * LookupNamespaceNoError
2658 * Look up a schema name.
2660 * Returns the namespace OID, or InvalidOid if not found.
2662 * Note this does NOT perform any permissions check --- callers are
2663 * responsible for being sure that an appropriate check is made.
2664 * In the majority of cases LookupExplicitNamespace is preferable.
2667 LookupNamespaceNoError(const char *nspname)
2669 /* check for pg_temp alias */
2670 if (strcmp(nspname, "pg_temp") == 0)
2672 if (OidIsValid(myTempNamespace))
2674 InvokeNamespaceSearchHook(myTempNamespace, true);
2675 return myTempNamespace;
2679 * Since this is used only for looking up existing objects, there is
2680 * no point in trying to initialize the temp namespace here; and doing
2681 * so might create problems for some callers. Just report "not found".
2686 return get_namespace_oid(nspname, true);
2690 * LookupExplicitNamespace
2691 * Process an explicitly-specified schema name: look up the schema
2692 * and verify we have USAGE (lookup) rights in it.
2694 * Returns the namespace OID
2697 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2700 AclResult aclresult;
2702 /* check for pg_temp alias */
2703 if (strcmp(nspname, "pg_temp") == 0)
2705 if (OidIsValid(myTempNamespace))
2706 return myTempNamespace;
2709 * Since this is used only for looking up existing objects, there is
2710 * no point in trying to initialize the temp namespace here; and doing
2711 * so might create problems for some callers --- just fall through.
2715 namespaceId = get_namespace_oid(nspname, missing_ok);
2716 if (missing_ok && !OidIsValid(namespaceId))
2719 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2720 if (aclresult != ACLCHECK_OK)
2721 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2723 /* Schema search hook for this lookup */
2724 InvokeNamespaceSearchHook(namespaceId, true);
2730 * LookupCreationNamespace
2731 * Look up the schema and verify we have CREATE rights on it.
2733 * This is just like LookupExplicitNamespace except for the different
2734 * permission check, and that we are willing to create pg_temp if needed.
2736 * Note: calling this may result in a CommandCounterIncrement operation,
2737 * if we have to create or clean out the temp namespace.
2740 LookupCreationNamespace(const char *nspname)
2743 AclResult aclresult;
2745 /* check for pg_temp alias */
2746 if (strcmp(nspname, "pg_temp") == 0)
2748 /* Initialize temp namespace if first time through */
2749 if (!OidIsValid(myTempNamespace))
2750 InitTempTableNamespace();
2751 return myTempNamespace;
2754 namespaceId = get_namespace_oid(nspname, false);
2756 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2757 if (aclresult != ACLCHECK_OK)
2758 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2765 * Common checks on switching namespaces.
2767 * We complain if (1) the old and new namespaces are the same, (2) either the
2768 * old or new namespaces is a temporary schema (or temporary toast schema), or
2769 * (3) either the old or new namespaces is the TOAST schema.
2772 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2774 if (oldNspOid == nspOid)
2776 (classid == RelationRelationId ?
2777 errcode(ERRCODE_DUPLICATE_TABLE) :
2778 classid == ProcedureRelationId ?
2779 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2780 errcode(ERRCODE_DUPLICATE_OBJECT),
2781 errmsg("%s is already in schema \"%s\"",
2782 getObjectDescriptionOids(classid, objid),
2783 get_namespace_name(nspOid))));
2785 /* disallow renaming into or out of temp schemas */
2786 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2788 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2789 errmsg("cannot move objects into or out of temporary schemas")));
2791 /* same for TOAST schema */
2792 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2794 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2795 errmsg("cannot move objects into or out of TOAST schema")));
2799 * QualifiedNameGetCreationNamespace
2800 * Given a possibly-qualified name for an object (in List-of-Values
2801 * format), determine what namespace the object should be created in.
2802 * Also extract and return the object name (last component of list).
2804 * Note: this does not apply any permissions check. Callers must check
2805 * for CREATE rights on the selected namespace when appropriate.
2807 * Note: calling this may result in a CommandCounterIncrement operation,
2808 * if we have to create or clean out the temp namespace.
2811 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2816 /* deconstruct the name list */
2817 DeconstructQualifiedName(names, &schemaname, objname_p);
2821 /* check for pg_temp alias */
2822 if (strcmp(schemaname, "pg_temp") == 0)
2824 /* Initialize temp namespace if first time through */
2825 if (!OidIsValid(myTempNamespace))
2826 InitTempTableNamespace();
2827 return myTempNamespace;
2829 /* use exact schema given */
2830 namespaceId = get_namespace_oid(schemaname, false);
2831 /* we do not check for USAGE rights here! */
2835 /* use the default creation namespace */
2836 recomputeNamespacePath();
2837 if (activeTempCreationPending)
2839 /* Need to initialize temp namespace */
2840 InitTempTableNamespace();
2841 return myTempNamespace;
2843 namespaceId = activeCreationNamespace;
2844 if (!OidIsValid(namespaceId))
2846 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2847 errmsg("no schema has been selected to create in")));
2854 * get_namespace_oid - given a namespace name, look up the OID
2856 * If missing_ok is false, throw an error if namespace name not found. If
2857 * true, just return InvalidOid.
2860 get_namespace_oid(const char *nspname, bool missing_ok)
2864 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2865 if (!OidIsValid(oid) && !missing_ok)
2867 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2868 errmsg("schema \"%s\" does not exist", nspname)));
2874 * makeRangeVarFromNameList
2875 * Utility routine to convert a qualified-name list into RangeVar form.
2878 makeRangeVarFromNameList(List *names)
2880 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2882 switch (list_length(names))
2885 rel->relname = strVal(linitial(names));
2888 rel->schemaname = strVal(linitial(names));
2889 rel->relname = strVal(lsecond(names));
2892 rel->catalogname = strVal(linitial(names));
2893 rel->schemaname = strVal(lsecond(names));
2894 rel->relname = strVal(lthird(names));
2898 (errcode(ERRCODE_SYNTAX_ERROR),
2899 errmsg("improper relation name (too many dotted names): %s",
2900 NameListToString(names))));
2909 * Utility routine to convert a qualified-name list into a string.
2911 * This is used primarily to form error messages, and so we do not quote
2912 * the list elements, for the sake of legibility.
2914 * In most scenarios the list elements should always be Value strings,
2915 * but we also allow A_Star for the convenience of ColumnRef processing.
2918 NameListToString(List *names)
2920 StringInfoData string;
2923 initStringInfo(&string);
2927 Node *name = (Node *) lfirst(l);
2929 if (l != list_head(names))
2930 appendStringInfoChar(&string, '.');
2932 if (IsA(name, String))
2933 appendStringInfoString(&string, strVal(name));
2934 else if (IsA(name, A_Star))
2935 appendStringInfoString(&string, "*");
2937 elog(ERROR, "unexpected node type in name list: %d",
2938 (int) nodeTag(name));
2945 * NameListToQuotedString
2946 * Utility routine to convert a qualified-name list into a string.
2948 * Same as above except that names will be double-quoted where necessary,
2949 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2952 NameListToQuotedString(List *names)
2954 StringInfoData string;
2957 initStringInfo(&string);
2961 if (l != list_head(names))
2962 appendStringInfoChar(&string, '.');
2963 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2970 * isTempNamespace - is the given namespace my temporary-table namespace?
2973 isTempNamespace(Oid namespaceId)
2975 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2981 * isTempToastNamespace - is the given namespace my temporary-toast-table
2985 isTempToastNamespace(Oid namespaceId)
2987 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2993 * isTempOrToastNamespace - is the given namespace my temporary-table
2994 * namespace or my temporary-toast-table namespace?
2997 isTempOrToastNamespace(Oid namespaceId)
2999 if (OidIsValid(myTempNamespace) &&
3000 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
3006 * isAnyTempNamespace - is the given namespace a temporary-table namespace
3007 * (either my own, or another backend's)? Temporary-toast-table namespaces
3008 * are included, too.
3011 isAnyTempNamespace(Oid namespaceId)
3016 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3017 nspname = get_namespace_name(namespaceId);
3019 return false; /* no such namespace? */
3020 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3021 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3027 * isOtherTempNamespace - is the given namespace some other backend's
3028 * temporary-table namespace (including temporary-toast-table namespaces)?
3030 * Note: for most purposes in the C code, this function is obsolete. Use
3031 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3034 isOtherTempNamespace(Oid namespaceId)
3036 /* If it's my own temp namespace, say "false" */
3037 if (isTempOrToastNamespace(namespaceId))
3039 /* Else, if it's any temp namespace, say "true" */
3040 return isAnyTempNamespace(namespaceId);
3044 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3045 * namespace (either my own, or another backend's), return the BackendId
3046 * that owns it. Temporary-toast-table namespaces are included, too.
3047 * If it isn't a temp namespace, return InvalidBackendId.
3050 GetTempNamespaceBackendId(Oid namespaceId)
3055 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3056 nspname = get_namespace_name(namespaceId);
3058 return InvalidBackendId; /* no such namespace? */
3059 if (strncmp(nspname, "pg_temp_", 8) == 0)
3060 result = atoi(nspname + 8);
3061 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3062 result = atoi(nspname + 14);
3064 result = InvalidBackendId;
3070 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3071 * which must already be assigned. (This is only used when creating a toast
3072 * table for a temp table, so we must have already done InitTempTableNamespace)
3075 GetTempToastNamespace(void)
3077 Assert(OidIsValid(myTempToastNamespace));
3078 return myTempToastNamespace;
3083 * GetOverrideSearchPath - fetch current search path definition in form
3084 * used by PushOverrideSearchPath.
3086 * The result structure is allocated in the specified memory context
3087 * (which might or might not be equal to CurrentMemoryContext); but any
3088 * junk created by revalidation calculations will be in CurrentMemoryContext.
3090 OverrideSearchPath *
3091 GetOverrideSearchPath(MemoryContext context)
3093 OverrideSearchPath *result;
3095 MemoryContext oldcxt;
3097 recomputeNamespacePath();
3099 oldcxt = MemoryContextSwitchTo(context);
3101 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3102 schemas = list_copy(activeSearchPath);
3103 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3105 if (linitial_oid(schemas) == myTempNamespace)
3106 result->addTemp = true;
3109 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
3110 result->addCatalog = true;
3112 schemas = list_delete_first(schemas);
3114 result->schemas = schemas;
3116 MemoryContextSwitchTo(oldcxt);
3122 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3124 * The result structure is allocated in CurrentMemoryContext.
3126 OverrideSearchPath *
3127 CopyOverrideSearchPath(OverrideSearchPath *path)
3129 OverrideSearchPath *result;
3131 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3132 result->schemas = list_copy(path->schemas);
3133 result->addCatalog = path->addCatalog;
3134 result->addTemp = path->addTemp;
3140 * OverrideSearchPathMatchesCurrent - does path match current setting?
3143 OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
3145 /* Easiest way to do this is GetOverrideSearchPath() and compare */
3147 OverrideSearchPath *cur;
3149 cur = GetOverrideSearchPath(CurrentMemoryContext);
3150 if (path->addCatalog == cur->addCatalog &&
3151 path->addTemp == cur->addTemp &&
3152 equal(path->schemas, cur->schemas))
3156 list_free(cur->schemas);
3162 * PushOverrideSearchPath - temporarily override the search path
3164 * We allow nested overrides, hence the push/pop terminology. The GUC
3165 * search_path variable is ignored while an override is active.
3167 * It's possible that newpath->useTemp is set but there is no longer any
3168 * active temp namespace, if the path was saved during a transaction that
3169 * created a temp namespace and was later rolled back. In that case we just
3170 * ignore useTemp. A plausible alternative would be to create a new temp
3171 * namespace, but for existing callers that's not necessary because an empty
3172 * temp namespace wouldn't affect their results anyway.
3174 * It's also worth noting that other schemas listed in newpath might not
3175 * exist anymore either. We don't worry about this because OIDs that match
3176 * no existing namespace will simply not produce any hits during searches.
3179 PushOverrideSearchPath(OverrideSearchPath *newpath)
3181 OverrideStackEntry *entry;
3184 MemoryContext oldcxt;
3187 * Copy the list for safekeeping, and insert implicitly-searched
3188 * namespaces as needed. This code should track recomputeNamespacePath.
3190 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3192 oidlist = list_copy(newpath->schemas);
3195 * Remember the first member of the explicit list.
3198 firstNS = InvalidOid;
3200 firstNS = linitial_oid(oidlist);
3203 * Add any implicitly-searched namespaces to the list. Note these go on
3204 * the front, not the back; also notice that we do not check USAGE
3205 * permissions for these.
3207 if (newpath->addCatalog)
3208 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3210 if (newpath->addTemp && OidIsValid(myTempNamespace))
3211 oidlist = lcons_oid(myTempNamespace, oidlist);
3214 * Build the new stack entry, then insert it at the head of the list.
3216 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3217 entry->searchPath = oidlist;
3218 entry->creationNamespace = firstNS;
3219 entry->nestLevel = GetCurrentTransactionNestLevel();
3221 overrideStack = lcons(entry, overrideStack);
3223 /* And make it active. */
3224 activeSearchPath = entry->searchPath;
3225 activeCreationNamespace = entry->creationNamespace;
3226 activeTempCreationPending = false; /* XXX is this OK? */
3228 MemoryContextSwitchTo(oldcxt);
3232 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3234 * Any push during a (sub)transaction will be popped automatically at abort.
3235 * But it's caller error if a push isn't popped in normal control flow.
3238 PopOverrideSearchPath(void)
3240 OverrideStackEntry *entry;
3242 /* Sanity checks. */
3243 if (overrideStack == NIL)
3244 elog(ERROR, "bogus PopOverrideSearchPath call");
3245 entry = (OverrideStackEntry *) linitial(overrideStack);
3246 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3247 elog(ERROR, "bogus PopOverrideSearchPath call");
3249 /* Pop the stack and free storage. */
3250 overrideStack = list_delete_first(overrideStack);
3251 list_free(entry->searchPath);
3254 /* Activate the next level down. */
3257 entry = (OverrideStackEntry *) linitial(overrideStack);
3258 activeSearchPath = entry->searchPath;
3259 activeCreationNamespace = entry->creationNamespace;
3260 activeTempCreationPending = false; /* XXX is this OK? */
3264 /* If not baseSearchPathValid, this is useless but harmless */
3265 activeSearchPath = baseSearchPath;
3266 activeCreationNamespace = baseCreationNamespace;
3267 activeTempCreationPending = baseTempCreationPending;
3273 * get_collation_oid - find a collation by possibly qualified name
3276 get_collation_oid(List *name, bool missing_ok)
3279 char *collation_name;
3280 int32 dbencoding = GetDatabaseEncoding();
3285 /* deconstruct the name list */
3286 DeconstructQualifiedName(name, &schemaname, &collation_name);
3290 /* use exact schema given */
3291 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3292 if (missing_ok && !OidIsValid(namespaceId))
3295 /* first try for encoding-specific entry, then any-encoding */
3296 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3297 PointerGetDatum(collation_name),
3298 Int32GetDatum(dbencoding),
3299 ObjectIdGetDatum(namespaceId));
3300 if (OidIsValid(colloid))
3302 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3303 PointerGetDatum(collation_name),
3305 ObjectIdGetDatum(namespaceId));
3306 if (OidIsValid(colloid))
3311 /* search for it in search path */
3312 recomputeNamespacePath();
3314 foreach(l, activeSearchPath)
3316 namespaceId = lfirst_oid(l);
3318 if (namespaceId == myTempNamespace)
3319 continue; /* do not look in temp namespace */
3321 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3322 PointerGetDatum(collation_name),
3323 Int32GetDatum(dbencoding),
3324 ObjectIdGetDatum(namespaceId));
3325 if (OidIsValid(colloid))
3327 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3328 PointerGetDatum(collation_name),
3330 ObjectIdGetDatum(namespaceId));
3331 if (OidIsValid(colloid))
3336 /* Not found in path */
3339 (errcode(ERRCODE_UNDEFINED_OBJECT),
3340 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3341 NameListToString(name), GetDatabaseEncodingName())));
3346 * get_conversion_oid - find a conversion by possibly qualified name
3349 get_conversion_oid(List *name, bool missing_ok)
3352 char *conversion_name;
3354 Oid conoid = InvalidOid;
3357 /* deconstruct the name list */
3358 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3362 /* use exact schema given */
3363 namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3364 if (missing_ok && !OidIsValid(namespaceId))
3365 conoid = InvalidOid;
3367 conoid = GetSysCacheOid2(CONNAMENSP,
3368 PointerGetDatum(conversion_name),
3369 ObjectIdGetDatum(namespaceId));
3373 /* search for it in search path */
3374 recomputeNamespacePath();
3376 foreach(l, activeSearchPath)
3378 namespaceId = lfirst_oid(l);
3380 if (namespaceId == myTempNamespace)
3381 continue; /* do not look in temp namespace */
3383 conoid = GetSysCacheOid2(CONNAMENSP,
3384 PointerGetDatum(conversion_name),
3385 ObjectIdGetDatum(namespaceId));
3386 if (OidIsValid(conoid))
3391 /* Not found in path */
3392 if (!OidIsValid(conoid) && !missing_ok)
3394 (errcode(ERRCODE_UNDEFINED_OBJECT),
3395 errmsg("conversion \"%s\" does not exist",
3396 NameListToString(name))));
3401 * FindDefaultConversionProc - find default encoding conversion proc
3404 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3409 recomputeNamespacePath();
3411 foreach(l, activeSearchPath)
3413 Oid namespaceId = lfirst_oid(l);
3415 if (namespaceId == myTempNamespace)
3416 continue; /* do not look in temp namespace */
3418 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3419 if (OidIsValid(proc))
3423 /* Not found in path */
3428 * recomputeNamespacePath - recompute path derived variables if needed.
3431 recomputeNamespacePath(void)
3433 Oid roleid = GetUserId();
3441 MemoryContext oldcxt;
3443 /* Do nothing if an override search spec is active. */
3447 /* Do nothing if path is already valid. */
3448 if (baseSearchPathValid && namespaceUser == roleid)
3451 /* Need a modifiable copy of namespace_search_path string */
3452 rawname = pstrdup(namespace_search_path);
3454 /* Parse string into list of identifiers */
3455 if (!SplitIdentifierString(rawname, ',', &namelist))
3457 /* syntax error in name list */
3458 /* this should not happen if GUC checked check_search_path */
3459 elog(ERROR, "invalid list syntax");
3463 * Convert the list of names to a list of OIDs. If any names are not
3464 * recognizable or we don't have read access, just leave them out of the
3465 * list. (We can't raise an error, since the search_path setting has
3466 * already been accepted.) Don't make duplicate entries, either.
3469 temp_missing = false;
3470 foreach(l, namelist)
3472 char *curname = (char *) lfirst(l);
3475 if (strcmp(curname, "$user") == 0)
3477 /* $user --- substitute namespace matching user name, if any */
3480 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3481 if (HeapTupleIsValid(tuple))
3485 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3486 namespaceId = get_namespace_oid(rname, true);
3487 ReleaseSysCache(tuple);
3488 if (OidIsValid(namespaceId) &&
3489 !list_member_oid(oidlist, namespaceId) &&
3490 pg_namespace_aclcheck(namespaceId, roleid,
3491 ACL_USAGE) == ACLCHECK_OK &&
3492 InvokeNamespaceSearchHook(namespaceId, false))
3493 oidlist = lappend_oid(oidlist, namespaceId);
3496 else if (strcmp(curname, "pg_temp") == 0)
3498 /* pg_temp --- substitute temp namespace, if any */
3499 if (OidIsValid(myTempNamespace))
3501 if (!list_member_oid(oidlist, myTempNamespace) &&
3502 InvokeNamespaceSearchHook(myTempNamespace, false))
3503 oidlist = lappend_oid(oidlist, myTempNamespace);
3507 /* If it ought to be the creation namespace, set flag */
3509 temp_missing = true;
3514 /* normal namespace reference */
3515 namespaceId = get_namespace_oid(curname, true);
3516 if (OidIsValid(namespaceId) &&
3517 !list_member_oid(oidlist, namespaceId) &&
3518 pg_namespace_aclcheck(namespaceId, roleid,
3519 ACL_USAGE) == ACLCHECK_OK &&
3520 InvokeNamespaceSearchHook(namespaceId, false))
3521 oidlist = lappend_oid(oidlist, namespaceId);
3526 * Remember the first member of the explicit list. (Note: this is
3527 * nominally wrong if temp_missing, but we need it anyway to distinguish
3528 * explicit from implicit mention of pg_catalog.)
3531 firstNS = InvalidOid;
3533 firstNS = linitial_oid(oidlist);
3536 * Add any implicitly-searched namespaces to the list. Note these go on
3537 * the front, not the back; also notice that we do not check USAGE
3538 * permissions for these.
3540 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3541 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3543 if (OidIsValid(myTempNamespace) &&
3544 !list_member_oid(oidlist, myTempNamespace))
3545 oidlist = lcons_oid(myTempNamespace, oidlist);
3548 * Now that we've successfully built the new list of namespace OIDs, save
3549 * it in permanent storage.
3551 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3552 newpath = list_copy(oidlist);
3553 MemoryContextSwitchTo(oldcxt);
3555 /* Now safe to assign to state variables. */
3556 list_free(baseSearchPath);
3557 baseSearchPath = newpath;
3558 baseCreationNamespace = firstNS;
3559 baseTempCreationPending = temp_missing;
3561 /* Mark the path valid. */
3562 baseSearchPathValid = true;
3563 namespaceUser = roleid;
3565 /* And make it active. */
3566 activeSearchPath = baseSearchPath;
3567 activeCreationNamespace = baseCreationNamespace;
3568 activeTempCreationPending = baseTempCreationPending;
3572 list_free(namelist);
3577 * InitTempTableNamespace
3578 * Initialize temp table namespace on first use in a particular backend
3581 InitTempTableNamespace(void)
3583 char namespaceName[NAMEDATALEN];
3587 Assert(!OidIsValid(myTempNamespace));
3590 * First, do permission check to see if we are authorized to make temp
3591 * tables. We use a nonstandard error message here since "databasename:
3592 * permission denied" might be a tad cryptic.
3594 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3595 * that's necessary since current user ID could change during the session.
3596 * But there's no need to make the namespace in the first place until a
3597 * temp table creation request is made by someone with appropriate rights.
3599 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3600 ACL_CREATE_TEMP) != ACLCHECK_OK)
3602 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3603 errmsg("permission denied to create temporary tables in database \"%s\"",
3604 get_database_name(MyDatabaseId))));
3607 * Do not allow a Hot Standby slave session to make temp tables. Aside
3608 * from problems with modifying the system catalogs, there is a naming
3609 * conflict: pg_temp_N belongs to the session with BackendId N on the
3610 * master, not to a slave session with the same BackendId. We should not
3611 * be able to get here anyway due to XactReadOnly checks, but let's just
3612 * make real sure. Note that this also backstops various operations that
3613 * allow XactReadOnly transactions to modify temp tables; they'd need
3614 * RecoveryInProgress checks if not for this.
3616 if (RecoveryInProgress())
3618 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3619 errmsg("cannot create temporary tables during recovery")));
3621 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3623 namespaceId = get_namespace_oid(namespaceName, true);
3624 if (!OidIsValid(namespaceId))
3627 * First use of this temp namespace in this database; create it. The
3628 * temp namespaces are always owned by the superuser. We leave their
3629 * permissions at default --- i.e., no access except to superuser ---
3630 * to ensure that unprivileged users can't peek at other backends'
3631 * temp tables. This works because the places that access the temp
3632 * namespace for my own backend skip permissions checks on it.
3634 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3636 /* Advance command counter to make namespace visible */
3637 CommandCounterIncrement();
3642 * If the namespace already exists, clean it out (in case the former
3643 * owner crashed without doing so).
3645 RemoveTempRelations(namespaceId);
3649 * If the corresponding toast-table namespace doesn't exist yet, create
3650 * it. (We assume there is no need to clean it out if it does exist, since
3651 * dropping a parent table should make its toast table go away.)
3653 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3656 toastspaceId = get_namespace_oid(namespaceName, true);
3657 if (!OidIsValid(toastspaceId))
3659 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3661 /* Advance command counter to make namespace visible */
3662 CommandCounterIncrement();
3666 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3667 * so all our work could be undone by transaction rollback. Set flag for
3668 * AtEOXact_Namespace to know what to do.
3670 myTempNamespace = namespaceId;
3671 myTempToastNamespace = toastspaceId;
3673 /* It should not be done already. */
3674 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3675 myTempNamespaceSubID = GetCurrentSubTransactionId();
3677 baseSearchPathValid = false; /* need to rebuild list */
3681 * End-of-transaction cleanup for namespaces.
3684 AtEOXact_Namespace(bool isCommit)
3687 * If we abort the transaction in which a temp namespace was selected,
3688 * we'll have to do any creation or cleanout work over again. So, just
3689 * forget the namespace entirely until next time. On the other hand, if
3690 * we commit then register an exit callback to clean out the temp tables
3691 * at backend shutdown. (We only want to register the callback once per
3692 * session, so this is a good place to do it.)
3694 if (myTempNamespaceSubID != InvalidSubTransactionId)
3697 before_shmem_exit(RemoveTempRelationsCallback, 0);
3700 myTempNamespace = InvalidOid;
3701 myTempToastNamespace = InvalidOid;
3702 baseSearchPathValid = false; /* need to rebuild list */
3704 myTempNamespaceSubID = InvalidSubTransactionId;
3708 * Clean up if someone failed to do PopOverrideSearchPath
3713 elog(WARNING, "leaked override search path");
3714 while (overrideStack)
3716 OverrideStackEntry *entry;
3718 entry = (OverrideStackEntry *) linitial(overrideStack);
3719 overrideStack = list_delete_first(overrideStack);
3720 list_free(entry->searchPath);
3723 /* If not baseSearchPathValid, this is useless but harmless */
3724 activeSearchPath = baseSearchPath;
3725 activeCreationNamespace = baseCreationNamespace;
3726 activeTempCreationPending = baseTempCreationPending;
3731 * AtEOSubXact_Namespace
3733 * At subtransaction commit, propagate the temp-namespace-creation
3734 * flag to the parent subtransaction.
3736 * At subtransaction abort, forget the flag if we set it up.
3739 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3740 SubTransactionId parentSubid)
3742 OverrideStackEntry *entry;
3744 if (myTempNamespaceSubID == mySubid)
3747 myTempNamespaceSubID = parentSubid;
3750 myTempNamespaceSubID = InvalidSubTransactionId;
3751 /* TEMP namespace creation failed, so reset state */
3752 myTempNamespace = InvalidOid;
3753 myTempToastNamespace = InvalidOid;
3754 baseSearchPathValid = false; /* need to rebuild list */
3759 * Clean up if someone failed to do PopOverrideSearchPath
3761 while (overrideStack)
3763 entry = (OverrideStackEntry *) linitial(overrideStack);
3764 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3767 elog(WARNING, "leaked override search path");
3768 overrideStack = list_delete_first(overrideStack);
3769 list_free(entry->searchPath);
3773 /* Activate the next level down. */
3776 entry = (OverrideStackEntry *) linitial(overrideStack);
3777 activeSearchPath = entry->searchPath;
3778 activeCreationNamespace = entry->creationNamespace;
3779 activeTempCreationPending = false; /* XXX is this OK? */
3783 /* If not baseSearchPathValid, this is useless but harmless */
3784 activeSearchPath = baseSearchPath;
3785 activeCreationNamespace = baseCreationNamespace;
3786 activeTempCreationPending = baseTempCreationPending;
3791 * Remove all relations in the specified temp namespace.
3793 * This is called at backend shutdown (if we made any temp relations).
3794 * It is also called when we begin using a pre-existing temp namespace,
3795 * in order to clean out any relations that might have been created by
3796 * a crashed backend.
3799 RemoveTempRelations(Oid tempNamespaceId)
3801 ObjectAddress object;
3804 * We want to get rid of everything in the target namespace, but not the
3805 * namespace itself (deleting it only to recreate it later would be a
3806 * waste of cycles). We do this by finding everything that has a
3807 * dependency on the namespace.
3809 object.classId = NamespaceRelationId;
3810 object.objectId = tempNamespaceId;
3811 object.objectSubId = 0;
3813 deleteWhatDependsOn(&object, false);
3817 * Callback to remove temp relations at backend exit.
3820 RemoveTempRelationsCallback(int code, Datum arg)
3822 if (OidIsValid(myTempNamespace)) /* should always be true */
3824 /* Need to ensure we have a usable transaction. */
3825 AbortOutOfAnyTransaction();
3826 StartTransactionCommand();
3828 RemoveTempRelations(myTempNamespace);
3830 CommitTransactionCommand();
3835 * Remove all temp tables from the temporary namespace.
3838 ResetTempTableNamespace(void)
3840 if (OidIsValid(myTempNamespace))
3841 RemoveTempRelations(myTempNamespace);
3846 * Routines for handling the GUC variable 'search_path'.
3849 /* check_hook: validate new search_path value */
3851 check_search_path(char **newval, void **extra, GucSource source)
3856 /* Need a modifiable copy of string */
3857 rawname = pstrdup(*newval);
3859 /* Parse string into list of identifiers */
3860 if (!SplitIdentifierString(rawname, ',', &namelist))
3862 /* syntax error in name list */
3863 GUC_check_errdetail("List syntax is invalid.");
3865 list_free(namelist);
3870 * We used to try to check that the named schemas exist, but there are
3871 * many valid use-cases for having search_path settings that include
3872 * schemas that don't exist; and often, we are not inside a transaction
3873 * here and so can't consult the system catalogs anyway. So now, the only
3874 * requirement is syntactic validity of the identifier list.
3878 list_free(namelist);
3883 /* assign_hook: do extra actions as needed */
3885 assign_search_path(const char *newval, void *extra)
3888 * We mark the path as needing recomputation, but don't do anything until
3889 * it's needed. This avoids trying to do database access during GUC
3890 * initialization, or outside a transaction.
3892 baseSearchPathValid = false;
3896 * InitializeSearchPath: initialize module during InitPostgres.
3898 * This is called after we are up enough to be able to do catalog lookups.
3901 InitializeSearchPath(void)
3903 if (IsBootstrapProcessingMode())
3906 * In bootstrap mode, the search path must be 'pg_catalog' so that
3907 * tables are created in the proper namespace; ignore the GUC setting.
3909 MemoryContext oldcxt;
3911 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3912 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3913 MemoryContextSwitchTo(oldcxt);
3914 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3915 baseTempCreationPending = false;
3916 baseSearchPathValid = true;
3917 namespaceUser = GetUserId();
3918 activeSearchPath = baseSearchPath;
3919 activeCreationNamespace = baseCreationNamespace;
3920 activeTempCreationPending = baseTempCreationPending;
3925 * In normal mode, arrange for a callback on any syscache invalidation
3926 * of pg_namespace rows.
3928 CacheRegisterSyscacheCallback(NAMESPACEOID,
3931 /* Force search path to be recomputed on next use */
3932 baseSearchPathValid = false;
3938 * Syscache inval callback function
3941 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3943 /* Force search path to be recomputed on next use */
3944 baseSearchPathValid = false;
3948 * Fetch the active search path. The return value is a palloc'ed list
3949 * of OIDs; the caller is responsible for freeing this storage as
3952 * The returned list includes the implicitly-prepended namespaces only if
3953 * includeImplicit is true.
3955 * Note: calling this may result in a CommandCounterIncrement operation,
3956 * if we have to create or clean out the temp namespace.
3959 fetch_search_path(bool includeImplicit)
3963 recomputeNamespacePath();
3966 * If the temp namespace should be first, force it to exist. This is so
3967 * that callers can trust the result to reflect the actual default
3968 * creation namespace. It's a bit bogus to do this here, since
3969 * current_schema() is supposedly a stable function without side-effects,
3970 * but the alternatives seem worse.
3972 if (activeTempCreationPending)
3974 InitTempTableNamespace();
3975 recomputeNamespacePath();
3978 result = list_copy(activeSearchPath);
3979 if (!includeImplicit)
3981 while (result && linitial_oid(result) != activeCreationNamespace)
3982 result = list_delete_first(result);
3989 * Fetch the active search path into a caller-allocated array of OIDs.
3990 * Returns the number of path entries. (If this is more than sarray_len,
3991 * then the data didn't fit and is not all stored.)
3993 * The returned list always includes the implicitly-prepended namespaces,
3994 * but never includes the temp namespace. (This is suitable for existing
3995 * users, which would want to ignore the temp namespace anyway.) This
3996 * definition allows us to not worry about initializing the temp namespace.
3999 fetch_search_path_array(Oid *sarray, int sarray_len)
4004 recomputeNamespacePath();
4006 foreach(l, activeSearchPath)
4008 Oid namespaceId = lfirst_oid(l);
4010 if (namespaceId == myTempNamespace)
4011 continue; /* do not include temp namespace */
4013 if (count < sarray_len)
4014 sarray[count] = namespaceId;
4023 * Export the FooIsVisible functions as SQL-callable functions.
4025 * Note: as of Postgres 8.4, these will silently return NULL if called on
4026 * a nonexistent object OID, rather than failing. This is to avoid race
4027 * condition errors when a query that's scanning a catalog using an MVCC
4028 * snapshot uses one of these functions. The underlying IsVisible functions
4029 * always use an up-to-date snapshot and so might see the object as already
4030 * gone when it's still visible to the transaction snapshot. (There is no race
4031 * condition in the current coding because we don't accept sinval messages
4032 * between the SearchSysCacheExists test and the subsequent lookup.)
4036 pg_table_is_visible(PG_FUNCTION_ARGS)
4038 Oid oid = PG_GETARG_OID(0);
4040 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
4043 PG_RETURN_BOOL(RelationIsVisible(oid));
4047 pg_type_is_visible(PG_FUNCTION_ARGS)
4049 Oid oid = PG_GETARG_OID(0);
4051 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
4054 PG_RETURN_BOOL(TypeIsVisible(oid));
4058 pg_function_is_visible(PG_FUNCTION_ARGS)
4060 Oid oid = PG_GETARG_OID(0);
4062 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
4065 PG_RETURN_BOOL(FunctionIsVisible(oid));
4069 pg_operator_is_visible(PG_FUNCTION_ARGS)
4071 Oid oid = PG_GETARG_OID(0);
4073 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
4076 PG_RETURN_BOOL(OperatorIsVisible(oid));
4080 pg_opclass_is_visible(PG_FUNCTION_ARGS)
4082 Oid oid = PG_GETARG_OID(0);
4084 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
4087 PG_RETURN_BOOL(OpclassIsVisible(oid));
4091 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
4093 Oid oid = PG_GETARG_OID(0);
4095 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
4098 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
4102 pg_collation_is_visible(PG_FUNCTION_ARGS)
4104 Oid oid = PG_GETARG_OID(0);
4106 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
4109 PG_RETURN_BOOL(CollationIsVisible(oid));
4113 pg_conversion_is_visible(PG_FUNCTION_ARGS)
4115 Oid oid = PG_GETARG_OID(0);
4117 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
4120 PG_RETURN_BOOL(ConversionIsVisible(oid));
4124 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
4126 Oid oid = PG_GETARG_OID(0);
4128 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
4131 PG_RETURN_BOOL(TSParserIsVisible(oid));
4135 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
4137 Oid oid = PG_GETARG_OID(0);
4139 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4142 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4146 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4148 Oid oid = PG_GETARG_OID(0);
4150 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4153 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4157 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4159 Oid oid = PG_GETARG_OID(0);
4161 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4164 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4168 pg_my_temp_schema(PG_FUNCTION_ARGS)
4170 PG_RETURN_OID(myTempNamespace);
4174 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4176 Oid oid = PG_GETARG_OID(0);
4178 PG_RETURN_BOOL(isOtherTempNamespace(oid));