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-2011, 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/xact.h"
23 #include "catalog/dependency.h"
24 #include "catalog/pg_authid.h"
25 #include "catalog/pg_collation.h"
26 #include "catalog/pg_conversion.h"
27 #include "catalog/pg_conversion_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "catalog/pg_opclass.h"
30 #include "catalog/pg_operator.h"
31 #include "catalog/pg_opfamily.h"
32 #include "catalog/pg_proc.h"
33 #include "catalog/pg_ts_config.h"
34 #include "catalog/pg_ts_dict.h"
35 #include "catalog/pg_ts_parser.h"
36 #include "catalog/pg_ts_template.h"
37 #include "catalog/pg_type.h"
38 #include "commands/dbcommands.h"
40 #include "mb/pg_wchar.h"
41 #include "miscadmin.h"
42 #include "nodes/makefuncs.h"
43 #include "parser/parse_func.h"
44 #include "storage/ipc.h"
45 #include "storage/lmgr.h"
46 #include "storage/sinval.h"
47 #include "utils/acl.h"
48 #include "utils/builtins.h"
49 #include "utils/guc.h"
50 #include "utils/inval.h"
51 #include "utils/lsyscache.h"
52 #include "utils/memutils.h"
53 #include "utils/syscache.h"
57 * The namespace search path is a possibly-empty list of namespace OIDs.
58 * In addition to the explicit list, implicitly-searched namespaces
61 * 1. If a TEMP table namespace has been initialized in this session, it
62 * is implicitly searched first. (The only time this doesn't happen is
63 * when we are obeying an override search path spec that says not to use the
64 * temp namespace, or the temp namespace is included in the explicit list.)
66 * 2. The system catalog namespace is always searched. If the system
67 * namespace is present in the explicit path then it will be searched in
68 * the specified order; otherwise it will be searched after TEMP tables and
69 * *before* the explicit list. (It might seem that the system namespace
70 * should be implicitly last, but this behavior appears to be required by
71 * SQL99. Also, this provides a way to search the system namespace first
72 * without thereby making it the default creation target namespace.)
74 * For security reasons, searches using the search path will ignore the temp
75 * namespace when searching for any object type other than relations and
76 * types. (We must allow types since temp tables have rowtypes.)
78 * The default creation target namespace is always the first element of the
79 * explicit list. If the explicit list is empty, there is no default target.
81 * The textual specification of search_path can include "$user" to refer to
82 * the namespace named the same as the current user, if any. (This is just
83 * ignored if there is no such namespace.) Also, it can include "pg_temp"
84 * to refer to the current backend's temp namespace. This is usually also
85 * ignorable if the temp namespace hasn't been set up, but there's a special
86 * case: if "pg_temp" appears first then it should be the default creation
87 * target. We kluge this case a little bit so that the temp namespace isn't
88 * set up until the first attempt to create something in it. (The reason for
89 * klugery is that we can't create the temp namespace outside a transaction,
90 * but initial GUC processing of search_path happens outside a transaction.)
91 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
92 * but is not reflected in activeCreationNamespace because the namespace isn't
95 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
96 * the system namespace is the only one searched or inserted into.
97 * initdb is also careful to set search_path to "pg_catalog" for its
98 * post-bootstrap standalone backend runs. Otherwise the default search
99 * path is determined by GUC. The factory default path contains the PUBLIC
100 * namespace (if it exists), preceded by the user's personal namespace
103 * We support a stack of "override" search path settings for use within
104 * specific sections of backend code. namespace_search_path is ignored
105 * whenever the override stack is nonempty. activeSearchPath is always
106 * the actually active path; it points either to the search list of the
107 * topmost stack entry, or to baseSearchPath which is the list derived
108 * from namespace_search_path.
110 * If baseSearchPathValid is false, then baseSearchPath (and other
111 * derived variables) need to be recomputed from namespace_search_path.
112 * We mark it invalid upon an assignment to namespace_search_path or receipt
113 * of a syscache invalidation event for pg_namespace. The recomputation
114 * is done during the next non-overridden lookup attempt. Note that an
115 * override spec is never subject to recomputation.
117 * Any namespaces mentioned in namespace_search_path that are not readable
118 * by the current user ID are simply left out of baseSearchPath; so
119 * we have to be willing to recompute the path when current userid changes.
120 * namespaceUser is the userid the path has been computed for.
122 * Note: all data pointed to by these List variables is in TopMemoryContext.
125 /* These variables define the actually active state: */
127 static List *activeSearchPath = NIL;
129 /* default place to create stuff; if InvalidOid, no default */
130 static Oid activeCreationNamespace = InvalidOid;
132 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
133 static bool activeTempCreationPending = false;
135 /* These variables are the values last derived from namespace_search_path: */
137 static List *baseSearchPath = NIL;
139 static Oid baseCreationNamespace = InvalidOid;
141 static bool baseTempCreationPending = false;
143 static Oid namespaceUser = InvalidOid;
145 /* The above four values are valid only if baseSearchPathValid */
146 static bool baseSearchPathValid = true;
148 /* Override requests are remembered in a stack of OverrideStackEntry structs */
152 List *searchPath; /* the desired search path */
153 Oid creationNamespace; /* the desired creation namespace */
154 int nestLevel; /* subtransaction nesting level */
155 } OverrideStackEntry;
157 static List *overrideStack = NIL;
160 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
161 * in a particular backend session (this happens when a CREATE TEMP TABLE
162 * command is first executed). Thereafter it's the OID of the temp namespace.
164 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
165 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
167 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
168 * current subtransaction. The flag propagates up the subtransaction tree,
169 * so the main transaction will correctly recognize the flag if all
170 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
171 * we either haven't made the TEMP namespace yet, or have successfully
172 * committed its creation, depending on whether myTempNamespace is valid.
174 static Oid myTempNamespace = InvalidOid;
176 static Oid myTempToastNamespace = InvalidOid;
178 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
181 * This is the user's textual search path specification --- it's the value
182 * of the GUC variable 'search_path'.
184 char *namespace_search_path = NULL;
187 /* Local functions */
188 static void recomputeNamespacePath(void);
189 static void InitTempTableNamespace(void);
190 static void RemoveTempRelations(Oid tempNamespaceId);
191 static void RemoveTempRelationsCallback(int code, Datum arg);
192 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
193 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
196 /* These don't really need to appear in any header file */
197 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
198 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
199 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
200 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_collation_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
207 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
208 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
209 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
210 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
215 * Given a RangeVar describing an existing relation,
216 * select the proper namespace and look up the relation OID.
218 * If the relation is not found, return InvalidOid if missing_ok = true,
219 * otherwise raise an error.
221 * If nowait = true, throw an error if we'd have to wait for a lock.
223 * Callback allows caller to check permissions or acquire additional locks
224 * prior to grabbing the relation lock.
227 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
228 bool missing_ok, bool nowait,
229 RangeVarGetRelidCallback callback, void *callback_arg)
233 Oid oldRelId = InvalidOid;
237 * We check the catalog name and then ignore it.
239 if (relation->catalogname)
241 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
243 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
244 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
245 relation->catalogname, relation->schemaname,
246 relation->relname)));
250 * DDL operations can change the results of a name lookup. Since all
251 * such operations will generate invalidation messages, we keep track
252 * of whether any such messages show up while we're performing the
253 * operation, and retry until either (1) no more invalidation messages
254 * show up or (2) the answer doesn't change.
256 * But if lockmode = NoLock, then we assume that either the caller is OK
257 * with the answer changing under them, or that they already hold some
258 * appropriate lock, and therefore return the first answer we get without
259 * checking for invalidation messages. Also, if the requested lock is
260 * already held, no LockRelationOid will not AcceptInvalidationMessages,
261 * so we may fail to notice a change. We could protect against that case
262 * by calling AcceptInvalidationMessages() before beginning this loop,
263 * but that would add a significant amount overhead, so for now we don't.
268 * Remember this value, so that, after looking up the relation name
269 * and locking its OID, we can check whether any invalidation messages
270 * have been processed that might require a do-over.
272 inval_count = SharedInvalidMessageCounter;
275 * Some non-default relpersistence value may have been specified. The
276 * parser never generates such a RangeVar in simple DML, but it can
277 * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
278 * KEY)". Such a command will generate an added CREATE INDEX
279 * operation, which must be careful to find the temp table, even when
280 * pg_temp is not first in the search path.
282 if (relation->relpersistence == RELPERSISTENCE_TEMP)
284 if (!OidIsValid(myTempNamespace))
285 relId = InvalidOid; /* this probably can't happen? */
288 if (relation->schemaname)
291 namespaceId = LookupExplicitNamespace(relation->schemaname);
292 if (namespaceId != myTempNamespace)
294 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
295 errmsg("temporary tables cannot specify a schema name")));
298 relId = get_relname_relid(relation->relname, myTempNamespace);
301 else if (relation->schemaname)
305 /* use exact schema given */
306 namespaceId = LookupExplicitNamespace(relation->schemaname);
307 relId = get_relname_relid(relation->relname, namespaceId);
311 /* search the namespace path */
312 relId = RelnameGetRelid(relation->relname);
316 * Invoke caller-supplied callback, if any.
318 * This callback is a good place to check permissions: we haven't taken
319 * the table lock yet (and it's really best to check permissions before
320 * locking anything!), but we've gotten far enough to know what OID we
321 * think we should lock. Of course, concurrent DDL might change things
322 * while we're waiting for the lock, but in that case the callback will
323 * be invoked again for the new OID.
326 callback(relation, relId, oldRelId, callback_arg);
329 * If no lock requested, we assume the caller knows what they're
330 * doing. They should have already acquired a heavyweight lock on
331 * this relation earlier in the processing of this same statement,
332 * so it wouldn't be appropriate to AcceptInvalidationMessages()
333 * here, as that might pull the rug out from under them.
335 if (lockmode == NoLock)
339 * If, upon retry, we get back the same OID we did last time, then
340 * the invalidation messages we processed did not change the final
341 * answer. So we're done.
343 * If we got a different OID, we've locked the relation that used to
344 * have this name rather than the one that does now. So release
349 if (relId == oldRelId)
351 if (OidIsValid(oldRelId))
352 UnlockRelationOid(oldRelId, lockmode);
356 * Lock relation. This will also accept any pending invalidation
357 * messages. If we got back InvalidOid, indicating not found, then
358 * there's nothing to lock, but we accept invalidation messages
359 * anyway, to flush any negative catcache entries that may be
362 if (!OidIsValid(relId))
363 AcceptInvalidationMessages();
365 LockRelationOid(relId, lockmode);
366 else if (!ConditionalLockRelationOid(relId, lockmode))
368 if (relation->schemaname)
370 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
371 errmsg("could not obtain lock on relation \"%s.%s\"",
372 relation->schemaname, relation->relname)));
375 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
376 errmsg("could not obtain lock on relation \"%s\"",
377 relation->relname)));
381 * If no invalidation message were processed, we're done!
383 if (inval_count == SharedInvalidMessageCounter)
387 * Something may have changed. Let's repeat the name lookup, to
388 * make sure this name still references the same relation it did
395 if (!OidIsValid(relId) && !missing_ok)
397 if (relation->schemaname)
399 (errcode(ERRCODE_UNDEFINED_TABLE),
400 errmsg("relation \"%s.%s\" does not exist",
401 relation->schemaname, relation->relname)));
404 (errcode(ERRCODE_UNDEFINED_TABLE),
405 errmsg("relation \"%s\" does not exist",
406 relation->relname)));
412 * RangeVarGetCreationNamespace
413 * Given a RangeVar describing a to-be-created relation,
414 * choose which namespace to create it in.
416 * Note: calling this may result in a CommandCounterIncrement operation.
417 * That will happen on the first request for a temp table in any particular
418 * backend run; we will need to either create or clean out the temp schema.
421 RangeVarGetCreationNamespace(const RangeVar *newRelation)
426 * We check the catalog name and then ignore it.
428 if (newRelation->catalogname)
430 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
432 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
433 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
434 newRelation->catalogname, newRelation->schemaname,
435 newRelation->relname)));
438 if (newRelation->schemaname)
440 /* check for pg_temp alias */
441 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
443 /* Initialize temp namespace if first time through */
444 if (!OidIsValid(myTempNamespace))
445 InitTempTableNamespace();
446 return myTempNamespace;
448 /* use exact schema given */
449 namespaceId = get_namespace_oid(newRelation->schemaname, false);
450 /* we do not check for USAGE rights here! */
452 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
454 /* Initialize temp namespace if first time through */
455 if (!OidIsValid(myTempNamespace))
456 InitTempTableNamespace();
457 return myTempNamespace;
461 /* use the default creation namespace */
462 recomputeNamespacePath();
463 if (activeTempCreationPending)
465 /* Need to initialize temp namespace */
466 InitTempTableNamespace();
467 return myTempNamespace;
469 namespaceId = activeCreationNamespace;
470 if (!OidIsValid(namespaceId))
472 (errcode(ERRCODE_UNDEFINED_SCHEMA),
473 errmsg("no schema has been selected to create in")));
476 /* Note: callers will check for CREATE rights when appropriate */
482 * RangeVarGetAndCheckCreationNamespace
483 * As RangeVarGetCreationNamespace, but with a permissions check.
486 RangeVarGetAndCheckCreationNamespace(const RangeVar *newRelation)
490 namespaceId = RangeVarGetCreationNamespace(newRelation);
493 * Check we have permission to create there. Skip check if bootstrapping,
494 * since permissions machinery may not be working yet.
496 if (!IsBootstrapProcessingMode())
500 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
502 if (aclresult != ACLCHECK_OK)
503 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
504 get_namespace_name(namespaceId));
511 * Adjust the relpersistence for an about-to-be-created relation based on the
512 * creation namespace, and throw an error for invalid combinations.
515 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
517 switch (newRelation->relpersistence)
519 case RELPERSISTENCE_TEMP:
520 if (!isTempOrToastNamespace(nspid))
522 if (isAnyTempNamespace(nspid))
524 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
525 errmsg("cannot create relations in temporary schemas of other sessions")));
528 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
529 errmsg("cannot create temporary relation in non-temporary schema")));
532 case RELPERSISTENCE_PERMANENT:
533 if (isTempOrToastNamespace(nspid))
534 newRelation->relpersistence = RELPERSISTENCE_TEMP;
535 else if (isAnyTempNamespace(nspid))
537 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
538 errmsg("cannot create relations in temporary schemas of other sessions")));
541 if (isAnyTempNamespace(nspid))
543 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
544 errmsg("only temporary relations may be created in temporary schemas")));
550 * Try to resolve an unqualified relation name.
551 * Returns OID if relation found in search path, else InvalidOid.
554 RelnameGetRelid(const char *relname)
559 recomputeNamespacePath();
561 foreach(l, activeSearchPath)
563 Oid namespaceId = lfirst_oid(l);
565 relid = get_relname_relid(relname, namespaceId);
566 if (OidIsValid(relid))
570 /* Not found in path */
577 * Determine whether a relation (identified by OID) is visible in the
578 * current search path. Visible means "would be found by searching
579 * for the unqualified relation name".
582 RelationIsVisible(Oid relid)
585 Form_pg_class relform;
589 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
590 if (!HeapTupleIsValid(reltup))
591 elog(ERROR, "cache lookup failed for relation %u", relid);
592 relform = (Form_pg_class) GETSTRUCT(reltup);
594 recomputeNamespacePath();
597 * Quick check: if it ain't in the path at all, it ain't visible. Items in
598 * the system namespace are surely in the path and so we needn't even do
599 * list_member_oid() for them.
601 relnamespace = relform->relnamespace;
602 if (relnamespace != PG_CATALOG_NAMESPACE &&
603 !list_member_oid(activeSearchPath, relnamespace))
608 * If it is in the path, it might still not be visible; it could be
609 * hidden by another relation of the same name earlier in the path. So
610 * we must do a slow check for conflicting relations.
612 char *relname = NameStr(relform->relname);
616 foreach(l, activeSearchPath)
618 Oid namespaceId = lfirst_oid(l);
620 if (namespaceId == relnamespace)
622 /* Found it first in path */
626 if (OidIsValid(get_relname_relid(relname, namespaceId)))
628 /* Found something else first in path */
634 ReleaseSysCache(reltup);
642 * Try to resolve an unqualified datatype name.
643 * Returns OID if type found in search path, else InvalidOid.
645 * This is essentially the same as RelnameGetRelid.
648 TypenameGetTypid(const char *typname)
653 recomputeNamespacePath();
655 foreach(l, activeSearchPath)
657 Oid namespaceId = lfirst_oid(l);
659 typid = GetSysCacheOid2(TYPENAMENSP,
660 PointerGetDatum(typname),
661 ObjectIdGetDatum(namespaceId));
662 if (OidIsValid(typid))
666 /* Not found in path */
672 * Determine whether a type (identified by OID) is visible in the
673 * current search path. Visible means "would be found by searching
674 * for the unqualified type name".
677 TypeIsVisible(Oid typid)
680 Form_pg_type typform;
684 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
685 if (!HeapTupleIsValid(typtup))
686 elog(ERROR, "cache lookup failed for type %u", typid);
687 typform = (Form_pg_type) GETSTRUCT(typtup);
689 recomputeNamespacePath();
692 * Quick check: if it ain't in the path at all, it ain't visible. Items in
693 * the system namespace are surely in the path and so we needn't even do
694 * list_member_oid() for them.
696 typnamespace = typform->typnamespace;
697 if (typnamespace != PG_CATALOG_NAMESPACE &&
698 !list_member_oid(activeSearchPath, typnamespace))
703 * If it is in the path, it might still not be visible; it could be
704 * hidden by another type of the same name earlier in the path. So we
705 * must do a slow check for conflicting types.
707 char *typname = NameStr(typform->typname);
711 foreach(l, activeSearchPath)
713 Oid namespaceId = lfirst_oid(l);
715 if (namespaceId == typnamespace)
717 /* Found it first in path */
721 if (SearchSysCacheExists2(TYPENAMENSP,
722 PointerGetDatum(typname),
723 ObjectIdGetDatum(namespaceId)))
725 /* Found something else first in path */
731 ReleaseSysCache(typtup);
738 * FuncnameGetCandidates
739 * Given a possibly-qualified function name and argument count,
740 * retrieve a list of the possible matches.
742 * If nargs is -1, we return all functions matching the given name,
743 * regardless of argument count. (argnames must be NIL, and expand_variadic
744 * and expand_defaults must be false, in this case.)
746 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
747 * and only functions having all the listed argument names will be returned.
748 * (We assume that length(argnames) <= nargs and all the passed-in names are
749 * distinct.) The returned structs will include an argnumbers array showing
750 * the actual argument index for each logical argument position.
752 * If expand_variadic is true, then variadic functions having the same number
753 * or fewer arguments will be retrieved, with the variadic argument and any
754 * additional argument positions filled with the variadic element type.
755 * nvargs in the returned struct is set to the number of such arguments.
756 * If expand_variadic is false, variadic arguments are not treated specially,
757 * and the returned nvargs will always be zero.
759 * If expand_defaults is true, functions that could match after insertion of
760 * default argument values will also be retrieved. In this case the returned
761 * structs could have nargs > passed-in nargs, and ndargs is set to the number
762 * of additional args (which can be retrieved from the function's
763 * proargdefaults entry).
765 * It is not possible for nvargs and ndargs to both be nonzero in the same
766 * list entry, since default insertion allows matches to functions with more
767 * than nargs arguments while the variadic transformation requires the same
770 * When argnames isn't NIL, the returned args[] type arrays are not ordered
771 * according to the functions' declarations, but rather according to the call:
772 * first any positional arguments, then the named arguments, then defaulted
773 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
774 * array can be used to map this back to the catalog information.
775 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
777 * We search a single namespace if the function name is qualified, else
778 * all namespaces in the search path. In the multiple-namespace case,
779 * we arrange for entries in earlier namespaces to mask identical entries in
782 * When expanding variadics, we arrange for non-variadic functions to mask
783 * variadic ones if the expanded argument list is the same. It is still
784 * possible for there to be conflicts between different variadic functions,
787 * It is guaranteed that the return list will never contain multiple entries
788 * with identical argument lists. When expand_defaults is true, the entries
789 * could have more than nargs positions, but we still guarantee that they are
790 * distinct in the first nargs positions. However, if argnames isn't NIL or
791 * either expand_variadic or expand_defaults is true, there might be multiple
792 * candidate functions that expand to identical argument lists. Rather than
793 * throw error here, we report such situations by returning a single entry
794 * with oid = 0 that represents a set of such conflicting candidates.
795 * The caller might end up discarding such an entry anyway, but if it selects
796 * such an entry it should react as though the call were ambiguous.
799 FuncnameGetCandidates(List *names, int nargs, List *argnames,
800 bool expand_variadic, bool expand_defaults)
802 FuncCandidateList resultList = NULL;
803 bool any_special = false;
810 /* check for caller error */
811 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
813 /* deconstruct the name list */
814 DeconstructQualifiedName(names, &schemaname, &funcname);
818 /* use exact schema given */
819 namespaceId = LookupExplicitNamespace(schemaname);
823 /* flag to indicate we need namespace search */
824 namespaceId = InvalidOid;
825 recomputeNamespacePath();
828 /* Search syscache by name only */
829 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
831 for (i = 0; i < catlist->n_members; i++)
833 HeapTuple proctup = &catlist->members[i]->tuple;
834 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
835 int pronargs = procform->pronargs;
841 int *argnumbers = NULL;
842 FuncCandidateList newResult;
844 if (OidIsValid(namespaceId))
846 /* Consider only procs in specified namespace */
847 if (procform->pronamespace != namespaceId)
853 * Consider only procs that are in the search path and are not in
854 * the temp namespace.
858 foreach(nsp, activeSearchPath)
860 if (procform->pronamespace == lfirst_oid(nsp) &&
861 procform->pronamespace != myTempNamespace)
866 continue; /* proc is not in search path */
872 * Call uses named or mixed notation
874 * Named or mixed notation can match a variadic function only if
875 * expand_variadic is off; otherwise there is no way to match the
876 * presumed-nameless parameters expanded from the variadic array.
878 if (OidIsValid(procform->provariadic) && expand_variadic)
880 va_elem_type = InvalidOid;
884 * Check argument count.
886 Assert(nargs >= 0); /* -1 not supported with argnames */
888 if (pronargs > nargs && expand_defaults)
890 /* Ignore if not enough default expressions */
891 if (nargs + procform->pronargdefaults < pronargs)
896 use_defaults = false;
898 /* Ignore if it doesn't match requested argument count */
899 if (pronargs != nargs && !use_defaults)
902 /* Check for argument name match, generate positional mapping */
903 if (!MatchNamedCall(proctup, nargs, argnames,
907 /* Named argument matching is always "special" */
913 * Call uses positional notation
915 * Check if function is variadic, and get variadic element type if
916 * so. If expand_variadic is false, we should just ignore
919 if (pronargs <= nargs && expand_variadic)
921 va_elem_type = procform->provariadic;
922 variadic = OidIsValid(va_elem_type);
923 any_special |= variadic;
927 va_elem_type = InvalidOid;
932 * Check if function can match by using parameter defaults.
934 if (pronargs > nargs && expand_defaults)
936 /* Ignore if not enough default expressions */
937 if (nargs + procform->pronargdefaults < pronargs)
943 use_defaults = false;
945 /* Ignore if it doesn't match requested argument count */
946 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
951 * We must compute the effective argument list so that we can easily
952 * compare it to earlier results. We waste a palloc cycle if it gets
953 * masked by an earlier result, but really that's a pretty infrequent
954 * case so it's not worth worrying about.
956 effective_nargs = Max(pronargs, nargs);
957 newResult = (FuncCandidateList)
958 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
959 + effective_nargs * sizeof(Oid));
960 newResult->pathpos = pathpos;
961 newResult->oid = HeapTupleGetOid(proctup);
962 newResult->nargs = effective_nargs;
963 newResult->argnumbers = argnumbers;
966 /* Re-order the argument types into call's logical order */
967 Oid *proargtypes = procform->proargtypes.values;
970 for (i = 0; i < pronargs; i++)
971 newResult->args[i] = proargtypes[argnumbers[i]];
975 /* Simple positional case, just copy proargtypes as-is */
976 memcpy(newResult->args, procform->proargtypes.values,
977 pronargs * sizeof(Oid));
983 newResult->nvargs = effective_nargs - pronargs + 1;
984 /* Expand variadic argument into N copies of element type */
985 for (i = pronargs - 1; i < effective_nargs; i++)
986 newResult->args[i] = va_elem_type;
989 newResult->nvargs = 0;
990 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
993 * Does it have the same arguments as something we already accepted?
994 * If so, decide what to do to avoid returning duplicate argument
995 * lists. We can skip this check for the single-namespace case if no
996 * special (named, variadic or defaults) match has been made, since
997 * then the unique index on pg_proc guarantees all the matches have
998 * different argument lists.
1000 if (resultList != NULL &&
1001 (any_special || !OidIsValid(namespaceId)))
1004 * If we have an ordered list from SearchSysCacheList (the normal
1005 * case), then any conflicting proc must immediately adjoin this
1006 * one in the list, so we only need to look at the newest result
1007 * item. If we have an unordered list, we have to scan the whole
1008 * result list. Also, if either the current candidate or any
1009 * previous candidate is a special match, we can't assume that
1010 * conflicts are adjacent.
1012 * We ignore defaulted arguments in deciding what is a match.
1014 FuncCandidateList prevResult;
1016 if (catlist->ordered && !any_special)
1018 /* ndargs must be 0 if !any_special */
1019 if (effective_nargs == resultList->nargs &&
1020 memcmp(newResult->args,
1022 effective_nargs * sizeof(Oid)) == 0)
1023 prevResult = resultList;
1029 int cmp_nargs = newResult->nargs - newResult->ndargs;
1031 for (prevResult = resultList;
1033 prevResult = prevResult->next)
1035 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1036 memcmp(newResult->args,
1038 cmp_nargs * sizeof(Oid)) == 0)
1046 * We have a match with a previous result. Decide which one
1047 * to keep, or mark it ambiguous if we can't decide. The
1048 * logic here is preference > 0 means prefer the old result,
1049 * preference < 0 means prefer the new, preference = 0 means
1054 if (pathpos != prevResult->pathpos)
1057 * Prefer the one that's earlier in the search path.
1059 preference = pathpos - prevResult->pathpos;
1061 else if (variadic && prevResult->nvargs == 0)
1064 * With variadic functions we could have, for example,
1065 * both foo(numeric) and foo(variadic numeric[]) in the
1066 * same namespace; if so we prefer the non-variadic match
1067 * on efficiency grounds.
1071 else if (!variadic && prevResult->nvargs > 0)
1078 * We can't decide. This can happen with, for example,
1079 * both foo(numeric, variadic numeric[]) and
1080 * foo(variadic numeric[]) in the same namespace, or
1081 * both foo(int) and foo (int, int default something)
1082 * in the same namespace, or both foo(a int, b text)
1083 * and foo(b text, a int) in the same namespace.
1091 /* keep previous result */
1095 else if (preference < 0)
1097 /* remove previous result from the list */
1098 if (prevResult == resultList)
1099 resultList = prevResult->next;
1102 FuncCandidateList prevPrevResult;
1104 for (prevPrevResult = resultList;
1106 prevPrevResult = prevPrevResult->next)
1108 if (prevResult == prevPrevResult->next)
1110 prevPrevResult->next = prevResult->next;
1114 Assert(prevPrevResult); /* assert we found it */
1117 /* fall through to add newResult to list */
1121 /* mark old result as ambiguous, discard new */
1122 prevResult->oid = InvalidOid;
1130 * Okay to add it to result list
1132 newResult->next = resultList;
1133 resultList = newResult;
1136 ReleaseSysCacheList(catlist);
1143 * Given a pg_proc heap tuple and a call's list of argument names,
1144 * check whether the function could match the call.
1146 * The call could match if all supplied argument names are accepted by
1147 * the function, in positions after the last positional argument, and there
1148 * are defaults for all unsupplied arguments.
1150 * The number of positional arguments is nargs - list_length(argnames).
1151 * Note caller has already done basic checks on argument count.
1153 * On match, return true and fill *argnumbers with a palloc'd array showing
1154 * the mapping from call argument positions to actual function argument
1155 * numbers. Defaulted arguments are included in this map, at positions
1156 * after the last supplied argument.
1159 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1162 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1163 int pronargs = procform->pronargs;
1164 int numposargs = nargs - list_length(argnames);
1169 bool arggiven[FUNC_MAX_ARGS];
1171 int ap; /* call args position */
1172 int pp; /* proargs position */
1175 Assert(argnames != NIL);
1176 Assert(numposargs >= 0);
1177 Assert(nargs <= pronargs);
1179 /* Ignore this function if its proargnames is null */
1180 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1185 /* OK, let's extract the argument names and types */
1186 pronallargs = get_func_arg_info(proctup,
1187 &p_argtypes, &p_argnames, &p_argmodes);
1188 Assert(p_argnames != NULL);
1190 /* initialize state for matching */
1191 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1192 memset(arggiven, false, pronargs * sizeof(bool));
1194 /* there are numposargs positional args before the named args */
1195 for (ap = 0; ap < numposargs; ap++)
1197 (*argnumbers)[ap] = ap;
1198 arggiven[ap] = true;
1201 /* now examine the named args */
1202 foreach(lc, argnames)
1204 char *argname = (char *) lfirst(lc);
1210 for (i = 0; i < pronallargs; i++)
1212 /* consider only input parameters */
1214 (p_argmodes[i] != FUNC_PARAM_IN &&
1215 p_argmodes[i] != FUNC_PARAM_INOUT &&
1216 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1218 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1220 /* fail if argname matches a positional argument */
1223 arggiven[pp] = true;
1224 (*argnumbers)[ap] = pp;
1228 /* increase pp only for input parameters */
1231 /* if name isn't in proargnames, fail */
1237 Assert(ap == nargs); /* processed all actual parameters */
1239 /* Check for default arguments */
1240 if (nargs < pronargs)
1242 int first_arg_with_default = pronargs - procform->pronargdefaults;
1244 for (pp = numposargs; pp < pronargs; pp++)
1248 /* fail if arg not given and no default available */
1249 if (pp < first_arg_with_default)
1251 (*argnumbers)[ap++] = pp;
1255 Assert(ap == pronargs); /* processed all function parameters */
1262 * Determine whether a function (identified by OID) is visible in the
1263 * current search path. Visible means "would be found by searching
1264 * for the unqualified function name with exact argument matches".
1267 FunctionIsVisible(Oid funcid)
1270 Form_pg_proc procform;
1274 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1275 if (!HeapTupleIsValid(proctup))
1276 elog(ERROR, "cache lookup failed for function %u", funcid);
1277 procform = (Form_pg_proc) GETSTRUCT(proctup);
1279 recomputeNamespacePath();
1282 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1283 * the system namespace are surely in the path and so we needn't even do
1284 * list_member_oid() for them.
1286 pronamespace = procform->pronamespace;
1287 if (pronamespace != PG_CATALOG_NAMESPACE &&
1288 !list_member_oid(activeSearchPath, pronamespace))
1293 * If it is in the path, it might still not be visible; it could be
1294 * hidden by another proc of the same name and arguments earlier in
1295 * the path. So we must do a slow check to see if this is the same
1296 * proc that would be found by FuncnameGetCandidates.
1298 char *proname = NameStr(procform->proname);
1299 int nargs = procform->pronargs;
1300 FuncCandidateList clist;
1304 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1305 nargs, NIL, false, false);
1307 for (; clist; clist = clist->next)
1309 if (memcmp(clist->args, procform->proargtypes.values,
1310 nargs * sizeof(Oid)) == 0)
1312 /* Found the expected entry; is it the right proc? */
1313 visible = (clist->oid == funcid);
1319 ReleaseSysCache(proctup);
1327 * Given a possibly-qualified operator name and exact input datatypes,
1328 * look up the operator. Returns InvalidOid if not found.
1330 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1333 * If the operator name is not schema-qualified, it is sought in the current
1334 * namespace search path.
1337 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1344 /* deconstruct the name list */
1345 DeconstructQualifiedName(names, &schemaname, &opername);
1349 /* search only in exact schema given */
1353 namespaceId = LookupExplicitNamespace(schemaname);
1354 opertup = SearchSysCache4(OPERNAMENSP,
1355 CStringGetDatum(opername),
1356 ObjectIdGetDatum(oprleft),
1357 ObjectIdGetDatum(oprright),
1358 ObjectIdGetDatum(namespaceId));
1359 if (HeapTupleIsValid(opertup))
1361 Oid result = HeapTupleGetOid(opertup);
1363 ReleaseSysCache(opertup);
1369 /* Search syscache by name and argument types */
1370 catlist = SearchSysCacheList3(OPERNAMENSP,
1371 CStringGetDatum(opername),
1372 ObjectIdGetDatum(oprleft),
1373 ObjectIdGetDatum(oprright));
1375 if (catlist->n_members == 0)
1377 /* no hope, fall out early */
1378 ReleaseSysCacheList(catlist);
1383 * We have to find the list member that is first in the search path, if
1384 * there's more than one. This doubly-nested loop looks ugly, but in
1385 * practice there should usually be few catlist members.
1387 recomputeNamespacePath();
1389 foreach(l, activeSearchPath)
1391 Oid namespaceId = lfirst_oid(l);
1394 if (namespaceId == myTempNamespace)
1395 continue; /* do not look in temp namespace */
1397 for (i = 0; i < catlist->n_members; i++)
1399 HeapTuple opertup = &catlist->members[i]->tuple;
1400 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1402 if (operform->oprnamespace == namespaceId)
1404 Oid result = HeapTupleGetOid(opertup);
1406 ReleaseSysCacheList(catlist);
1412 ReleaseSysCacheList(catlist);
1417 * OpernameGetCandidates
1418 * Given a possibly-qualified operator name and operator kind,
1419 * retrieve a list of the possible matches.
1421 * If oprkind is '\0', we return all operators matching the given name,
1422 * regardless of arguments.
1424 * We search a single namespace if the operator name is qualified, else
1425 * all namespaces in the search path. The return list will never contain
1426 * multiple entries with identical argument lists --- in the multiple-
1427 * namespace case, we arrange for entries in earlier namespaces to mask
1428 * identical entries in later namespaces.
1430 * The returned items always have two args[] entries --- one or the other
1431 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1434 OpernameGetCandidates(List *names, char oprkind)
1436 FuncCandidateList resultList = NULL;
1437 char *resultSpace = NULL;
1445 /* deconstruct the name list */
1446 DeconstructQualifiedName(names, &schemaname, &opername);
1450 /* use exact schema given */
1451 namespaceId = LookupExplicitNamespace(schemaname);
1455 /* flag to indicate we need namespace search */
1456 namespaceId = InvalidOid;
1457 recomputeNamespacePath();
1460 /* Search syscache by name only */
1461 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1464 * In typical scenarios, most if not all of the operators found by the
1465 * catcache search will end up getting returned; and there can be quite a
1466 * few, for common operator names such as '=' or '+'. To reduce the time
1467 * spent in palloc, we allocate the result space as an array large enough
1468 * to hold all the operators. The original coding of this routine did a
1469 * separate palloc for each operator, but profiling revealed that the
1470 * pallocs used an unreasonably large fraction of parsing time.
1472 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1474 if (catlist->n_members > 0)
1475 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1477 for (i = 0; i < catlist->n_members; i++)
1479 HeapTuple opertup = &catlist->members[i]->tuple;
1480 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1482 FuncCandidateList newResult;
1484 /* Ignore operators of wrong kind, if specific kind requested */
1485 if (oprkind && operform->oprkind != oprkind)
1488 if (OidIsValid(namespaceId))
1490 /* Consider only opers in specified namespace */
1491 if (operform->oprnamespace != namespaceId)
1493 /* No need to check args, they must all be different */
1498 * Consider only opers that are in the search path and are not in
1499 * the temp namespace.
1503 foreach(nsp, activeSearchPath)
1505 if (operform->oprnamespace == lfirst_oid(nsp) &&
1506 operform->oprnamespace != myTempNamespace)
1511 continue; /* oper is not in search path */
1514 * Okay, it's in the search path, but does it have the same
1515 * arguments as something we already accepted? If so, keep only
1516 * the one that appears earlier in the search path.
1518 * If we have an ordered list from SearchSysCacheList (the normal
1519 * case), then any conflicting oper must immediately adjoin this
1520 * one in the list, so we only need to look at the newest result
1521 * item. If we have an unordered list, we have to scan the whole
1526 FuncCandidateList prevResult;
1528 if (catlist->ordered)
1530 if (operform->oprleft == resultList->args[0] &&
1531 operform->oprright == resultList->args[1])
1532 prevResult = resultList;
1538 for (prevResult = resultList;
1540 prevResult = prevResult->next)
1542 if (operform->oprleft == prevResult->args[0] &&
1543 operform->oprright == prevResult->args[1])
1549 /* We have a match with a previous result */
1550 Assert(pathpos != prevResult->pathpos);
1551 if (pathpos > prevResult->pathpos)
1552 continue; /* keep previous result */
1553 /* replace previous result */
1554 prevResult->pathpos = pathpos;
1555 prevResult->oid = HeapTupleGetOid(opertup);
1556 continue; /* args are same, of course */
1562 * Okay to add it to result list
1564 newResult = (FuncCandidateList) (resultSpace + nextResult);
1565 nextResult += SPACE_PER_OP;
1567 newResult->pathpos = pathpos;
1568 newResult->oid = HeapTupleGetOid(opertup);
1569 newResult->nargs = 2;
1570 newResult->nvargs = 0;
1571 newResult->ndargs = 0;
1572 newResult->argnumbers = NULL;
1573 newResult->args[0] = operform->oprleft;
1574 newResult->args[1] = operform->oprright;
1575 newResult->next = resultList;
1576 resultList = newResult;
1579 ReleaseSysCacheList(catlist);
1586 * Determine whether an operator (identified by OID) is visible in the
1587 * current search path. Visible means "would be found by searching
1588 * for the unqualified operator name with exact argument matches".
1591 OperatorIsVisible(Oid oprid)
1594 Form_pg_operator oprform;
1598 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1599 if (!HeapTupleIsValid(oprtup))
1600 elog(ERROR, "cache lookup failed for operator %u", oprid);
1601 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1603 recomputeNamespacePath();
1606 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1607 * the system namespace are surely in the path and so we needn't even do
1608 * list_member_oid() for them.
1610 oprnamespace = oprform->oprnamespace;
1611 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1612 !list_member_oid(activeSearchPath, oprnamespace))
1617 * If it is in the path, it might still not be visible; it could be
1618 * hidden by another operator of the same name and arguments earlier
1619 * in the path. So we must do a slow check to see if this is the same
1620 * operator that would be found by OpernameGetOprId.
1622 char *oprname = NameStr(oprform->oprname);
1624 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1625 oprform->oprleft, oprform->oprright)
1629 ReleaseSysCache(oprtup);
1636 * OpclassnameGetOpcid
1637 * Try to resolve an unqualified index opclass name.
1638 * Returns OID if opclass found in search path, else InvalidOid.
1640 * This is essentially the same as TypenameGetTypid, but we have to have
1641 * an extra argument for the index AM OID.
1644 OpclassnameGetOpcid(Oid amid, const char *opcname)
1649 recomputeNamespacePath();
1651 foreach(l, activeSearchPath)
1653 Oid namespaceId = lfirst_oid(l);
1655 if (namespaceId == myTempNamespace)
1656 continue; /* do not look in temp namespace */
1658 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1659 ObjectIdGetDatum(amid),
1660 PointerGetDatum(opcname),
1661 ObjectIdGetDatum(namespaceId));
1662 if (OidIsValid(opcid))
1666 /* Not found in path */
1672 * Determine whether an opclass (identified by OID) is visible in the
1673 * current search path. Visible means "would be found by searching
1674 * for the unqualified opclass name".
1677 OpclassIsVisible(Oid opcid)
1680 Form_pg_opclass opcform;
1684 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1685 if (!HeapTupleIsValid(opctup))
1686 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1687 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1689 recomputeNamespacePath();
1692 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1693 * the system namespace are surely in the path and so we needn't even do
1694 * list_member_oid() for them.
1696 opcnamespace = opcform->opcnamespace;
1697 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1698 !list_member_oid(activeSearchPath, opcnamespace))
1703 * If it is in the path, it might still not be visible; it could be
1704 * hidden by another opclass of the same name earlier in the path. So
1705 * we must do a slow check to see if this opclass would be found by
1706 * OpclassnameGetOpcid.
1708 char *opcname = NameStr(opcform->opcname);
1710 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1713 ReleaseSysCache(opctup);
1719 * OpfamilynameGetOpfid
1720 * Try to resolve an unqualified index opfamily name.
1721 * Returns OID if opfamily found in search path, else InvalidOid.
1723 * This is essentially the same as TypenameGetTypid, but we have to have
1724 * an extra argument for the index AM OID.
1727 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1732 recomputeNamespacePath();
1734 foreach(l, activeSearchPath)
1736 Oid namespaceId = lfirst_oid(l);
1738 if (namespaceId == myTempNamespace)
1739 continue; /* do not look in temp namespace */
1741 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1742 ObjectIdGetDatum(amid),
1743 PointerGetDatum(opfname),
1744 ObjectIdGetDatum(namespaceId));
1745 if (OidIsValid(opfid))
1749 /* Not found in path */
1755 * Determine whether an opfamily (identified by OID) is visible in the
1756 * current search path. Visible means "would be found by searching
1757 * for the unqualified opfamily name".
1760 OpfamilyIsVisible(Oid opfid)
1763 Form_pg_opfamily opfform;
1767 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1768 if (!HeapTupleIsValid(opftup))
1769 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1770 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1772 recomputeNamespacePath();
1775 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1776 * the system namespace are surely in the path and so we needn't even do
1777 * list_member_oid() for them.
1779 opfnamespace = opfform->opfnamespace;
1780 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1781 !list_member_oid(activeSearchPath, opfnamespace))
1786 * If it is in the path, it might still not be visible; it could be
1787 * hidden by another opfamily of the same name earlier in the path. So
1788 * we must do a slow check to see if this opfamily would be found by
1789 * OpfamilynameGetOpfid.
1791 char *opfname = NameStr(opfform->opfname);
1793 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1796 ReleaseSysCache(opftup);
1802 * CollationGetCollid
1803 * Try to resolve an unqualified collation name.
1804 * Returns OID if collation found in search path, else InvalidOid.
1807 CollationGetCollid(const char *collname)
1809 int32 dbencoding = GetDatabaseEncoding();
1812 recomputeNamespacePath();
1814 foreach(l, activeSearchPath)
1816 Oid namespaceId = lfirst_oid(l);
1819 if (namespaceId == myTempNamespace)
1820 continue; /* do not look in temp namespace */
1822 /* Check for database-encoding-specific entry */
1823 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1824 PointerGetDatum(collname),
1825 Int32GetDatum(dbencoding),
1826 ObjectIdGetDatum(namespaceId));
1827 if (OidIsValid(collid))
1830 /* Check for any-encoding entry */
1831 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1832 PointerGetDatum(collname),
1834 ObjectIdGetDatum(namespaceId));
1835 if (OidIsValid(collid))
1839 /* Not found in path */
1844 * CollationIsVisible
1845 * Determine whether a collation (identified by OID) is visible in the
1846 * current search path. Visible means "would be found by searching
1847 * for the unqualified collation name".
1850 CollationIsVisible(Oid collid)
1853 Form_pg_collation collform;
1857 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1858 if (!HeapTupleIsValid(colltup))
1859 elog(ERROR, "cache lookup failed for collation %u", collid);
1860 collform = (Form_pg_collation) GETSTRUCT(colltup);
1862 recomputeNamespacePath();
1865 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1866 * the system namespace are surely in the path and so we needn't even do
1867 * list_member_oid() for them.
1869 collnamespace = collform->collnamespace;
1870 if (collnamespace != PG_CATALOG_NAMESPACE &&
1871 !list_member_oid(activeSearchPath, collnamespace))
1876 * If it is in the path, it might still not be visible; it could be
1877 * hidden by another conversion of the same name earlier in the path.
1878 * So we must do a slow check to see if this conversion would be found
1879 * by CollationGetCollid.
1881 char *collname = NameStr(collform->collname);
1883 visible = (CollationGetCollid(collname) == collid);
1886 ReleaseSysCache(colltup);
1893 * ConversionGetConid
1894 * Try to resolve an unqualified conversion name.
1895 * Returns OID if conversion found in search path, else InvalidOid.
1897 * This is essentially the same as RelnameGetRelid.
1900 ConversionGetConid(const char *conname)
1905 recomputeNamespacePath();
1907 foreach(l, activeSearchPath)
1909 Oid namespaceId = lfirst_oid(l);
1911 if (namespaceId == myTempNamespace)
1912 continue; /* do not look in temp namespace */
1914 conid = GetSysCacheOid2(CONNAMENSP,
1915 PointerGetDatum(conname),
1916 ObjectIdGetDatum(namespaceId));
1917 if (OidIsValid(conid))
1921 /* Not found in path */
1926 * ConversionIsVisible
1927 * Determine whether a conversion (identified by OID) is visible in the
1928 * current search path. Visible means "would be found by searching
1929 * for the unqualified conversion name".
1932 ConversionIsVisible(Oid conid)
1935 Form_pg_conversion conform;
1939 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1940 if (!HeapTupleIsValid(contup))
1941 elog(ERROR, "cache lookup failed for conversion %u", conid);
1942 conform = (Form_pg_conversion) GETSTRUCT(contup);
1944 recomputeNamespacePath();
1947 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1948 * the system namespace are surely in the path and so we needn't even do
1949 * list_member_oid() for them.
1951 connamespace = conform->connamespace;
1952 if (connamespace != PG_CATALOG_NAMESPACE &&
1953 !list_member_oid(activeSearchPath, connamespace))
1958 * If it is in the path, it might still not be visible; it could be
1959 * hidden by another conversion of the same name earlier in the path.
1960 * So we must do a slow check to see if this conversion would be found
1961 * by ConversionGetConid.
1963 char *conname = NameStr(conform->conname);
1965 visible = (ConversionGetConid(conname) == conid);
1968 ReleaseSysCache(contup);
1974 * get_ts_parser_oid - find a TS parser by possibly qualified name
1976 * If not found, returns InvalidOid if missing_ok, else throws error
1979 get_ts_parser_oid(List *names, bool missing_ok)
1984 Oid prsoid = InvalidOid;
1987 /* deconstruct the name list */
1988 DeconstructQualifiedName(names, &schemaname, &parser_name);
1992 /* use exact schema given */
1993 namespaceId = LookupExplicitNamespace(schemaname);
1994 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1995 PointerGetDatum(parser_name),
1996 ObjectIdGetDatum(namespaceId));
2000 /* search for it in search path */
2001 recomputeNamespacePath();
2003 foreach(l, activeSearchPath)
2005 namespaceId = lfirst_oid(l);
2007 if (namespaceId == myTempNamespace)
2008 continue; /* do not look in temp namespace */
2010 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
2011 PointerGetDatum(parser_name),
2012 ObjectIdGetDatum(namespaceId));
2013 if (OidIsValid(prsoid))
2018 if (!OidIsValid(prsoid) && !missing_ok)
2020 (errcode(ERRCODE_UNDEFINED_OBJECT),
2021 errmsg("text search parser \"%s\" does not exist",
2022 NameListToString(names))));
2029 * Determine whether a parser (identified by OID) is visible in the
2030 * current search path. Visible means "would be found by searching
2031 * for the unqualified parser name".
2034 TSParserIsVisible(Oid prsId)
2037 Form_pg_ts_parser form;
2041 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
2042 if (!HeapTupleIsValid(tup))
2043 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2044 form = (Form_pg_ts_parser) GETSTRUCT(tup);
2046 recomputeNamespacePath();
2049 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2050 * the system namespace are surely in the path and so we needn't even do
2051 * list_member_oid() for them.
2053 namespace = form->prsnamespace;
2054 if (namespace != PG_CATALOG_NAMESPACE &&
2055 !list_member_oid(activeSearchPath, namespace))
2060 * If it is in the path, it might still not be visible; it could be
2061 * hidden by another parser of the same name earlier in the path. So
2062 * we must do a slow check for conflicting parsers.
2064 char *name = NameStr(form->prsname);
2068 foreach(l, activeSearchPath)
2070 Oid namespaceId = lfirst_oid(l);
2072 if (namespaceId == myTempNamespace)
2073 continue; /* do not look in temp namespace */
2075 if (namespaceId == namespace)
2077 /* Found it first in path */
2081 if (SearchSysCacheExists2(TSPARSERNAMENSP,
2082 PointerGetDatum(name),
2083 ObjectIdGetDatum(namespaceId)))
2085 /* Found something else first in path */
2091 ReleaseSysCache(tup);
2097 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2099 * If not found, returns InvalidOid if failOK, else throws error
2102 get_ts_dict_oid(List *names, bool missing_ok)
2107 Oid dictoid = InvalidOid;
2110 /* deconstruct the name list */
2111 DeconstructQualifiedName(names, &schemaname, &dict_name);
2115 /* use exact schema given */
2116 namespaceId = LookupExplicitNamespace(schemaname);
2117 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2118 PointerGetDatum(dict_name),
2119 ObjectIdGetDatum(namespaceId));
2123 /* search for it in search path */
2124 recomputeNamespacePath();
2126 foreach(l, activeSearchPath)
2128 namespaceId = lfirst_oid(l);
2130 if (namespaceId == myTempNamespace)
2131 continue; /* do not look in temp namespace */
2133 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2134 PointerGetDatum(dict_name),
2135 ObjectIdGetDatum(namespaceId));
2136 if (OidIsValid(dictoid))
2141 if (!OidIsValid(dictoid) && !missing_ok)
2143 (errcode(ERRCODE_UNDEFINED_OBJECT),
2144 errmsg("text search dictionary \"%s\" does not exist",
2145 NameListToString(names))));
2151 * TSDictionaryIsVisible
2152 * Determine whether a dictionary (identified by OID) is visible in the
2153 * current search path. Visible means "would be found by searching
2154 * for the unqualified dictionary name".
2157 TSDictionaryIsVisible(Oid dictId)
2160 Form_pg_ts_dict form;
2164 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2165 if (!HeapTupleIsValid(tup))
2166 elog(ERROR, "cache lookup failed for text search dictionary %u",
2168 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2170 recomputeNamespacePath();
2173 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2174 * the system namespace are surely in the path and so we needn't even do
2175 * list_member_oid() for them.
2177 namespace = form->dictnamespace;
2178 if (namespace != PG_CATALOG_NAMESPACE &&
2179 !list_member_oid(activeSearchPath, namespace))
2184 * If it is in the path, it might still not be visible; it could be
2185 * hidden by another dictionary of the same name earlier in the path.
2186 * So we must do a slow check for conflicting dictionaries.
2188 char *name = NameStr(form->dictname);
2192 foreach(l, activeSearchPath)
2194 Oid namespaceId = lfirst_oid(l);
2196 if (namespaceId == myTempNamespace)
2197 continue; /* do not look in temp namespace */
2199 if (namespaceId == namespace)
2201 /* Found it first in path */
2205 if (SearchSysCacheExists2(TSDICTNAMENSP,
2206 PointerGetDatum(name),
2207 ObjectIdGetDatum(namespaceId)))
2209 /* Found something else first in path */
2215 ReleaseSysCache(tup);
2221 * get_ts_template_oid - find a TS template by possibly qualified name
2223 * If not found, returns InvalidOid if missing_ok, else throws error
2226 get_ts_template_oid(List *names, bool missing_ok)
2229 char *template_name;
2231 Oid tmploid = InvalidOid;
2234 /* deconstruct the name list */
2235 DeconstructQualifiedName(names, &schemaname, &template_name);
2239 /* use exact schema given */
2240 namespaceId = LookupExplicitNamespace(schemaname);
2241 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2242 PointerGetDatum(template_name),
2243 ObjectIdGetDatum(namespaceId));
2247 /* search for it in search path */
2248 recomputeNamespacePath();
2250 foreach(l, activeSearchPath)
2252 namespaceId = lfirst_oid(l);
2254 if (namespaceId == myTempNamespace)
2255 continue; /* do not look in temp namespace */
2257 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2258 PointerGetDatum(template_name),
2259 ObjectIdGetDatum(namespaceId));
2260 if (OidIsValid(tmploid))
2265 if (!OidIsValid(tmploid) && !missing_ok)
2267 (errcode(ERRCODE_UNDEFINED_OBJECT),
2268 errmsg("text search template \"%s\" does not exist",
2269 NameListToString(names))));
2275 * TSTemplateIsVisible
2276 * Determine whether a template (identified by OID) is visible in the
2277 * current search path. Visible means "would be found by searching
2278 * for the unqualified template name".
2281 TSTemplateIsVisible(Oid tmplId)
2284 Form_pg_ts_template form;
2288 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2289 if (!HeapTupleIsValid(tup))
2290 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2291 form = (Form_pg_ts_template) GETSTRUCT(tup);
2293 recomputeNamespacePath();
2296 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2297 * the system namespace are surely in the path and so we needn't even do
2298 * list_member_oid() for them.
2300 namespace = form->tmplnamespace;
2301 if (namespace != PG_CATALOG_NAMESPACE &&
2302 !list_member_oid(activeSearchPath, namespace))
2307 * If it is in the path, it might still not be visible; it could be
2308 * hidden by another template of the same name earlier in the path. So
2309 * we must do a slow check for conflicting templates.
2311 char *name = NameStr(form->tmplname);
2315 foreach(l, activeSearchPath)
2317 Oid namespaceId = lfirst_oid(l);
2319 if (namespaceId == myTempNamespace)
2320 continue; /* do not look in temp namespace */
2322 if (namespaceId == namespace)
2324 /* Found it first in path */
2328 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2329 PointerGetDatum(name),
2330 ObjectIdGetDatum(namespaceId)))
2332 /* Found something else first in path */
2338 ReleaseSysCache(tup);
2344 * get_ts_config_oid - find a TS config by possibly qualified name
2346 * If not found, returns InvalidOid if missing_ok, else throws error
2349 get_ts_config_oid(List *names, bool missing_ok)
2354 Oid cfgoid = InvalidOid;
2357 /* deconstruct the name list */
2358 DeconstructQualifiedName(names, &schemaname, &config_name);
2362 /* use exact schema given */
2363 namespaceId = LookupExplicitNamespace(schemaname);
2364 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2365 PointerGetDatum(config_name),
2366 ObjectIdGetDatum(namespaceId));
2370 /* search for it in search path */
2371 recomputeNamespacePath();
2373 foreach(l, activeSearchPath)
2375 namespaceId = lfirst_oid(l);
2377 if (namespaceId == myTempNamespace)
2378 continue; /* do not look in temp namespace */
2380 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2381 PointerGetDatum(config_name),
2382 ObjectIdGetDatum(namespaceId));
2383 if (OidIsValid(cfgoid))
2388 if (!OidIsValid(cfgoid) && !missing_ok)
2390 (errcode(ERRCODE_UNDEFINED_OBJECT),
2391 errmsg("text search configuration \"%s\" does not exist",
2392 NameListToString(names))));
2399 * Determine whether a text search configuration (identified by OID)
2400 * is visible in the current search path. Visible means "would be found
2401 * by searching for the unqualified text search configuration name".
2404 TSConfigIsVisible(Oid cfgid)
2407 Form_pg_ts_config form;
2411 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2412 if (!HeapTupleIsValid(tup))
2413 elog(ERROR, "cache lookup failed for text search configuration %u",
2415 form = (Form_pg_ts_config) GETSTRUCT(tup);
2417 recomputeNamespacePath();
2420 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2421 * the system namespace are surely in the path and so we needn't even do
2422 * list_member_oid() for them.
2424 namespace = form->cfgnamespace;
2425 if (namespace != PG_CATALOG_NAMESPACE &&
2426 !list_member_oid(activeSearchPath, namespace))
2431 * If it is in the path, it might still not be visible; it could be
2432 * hidden by another configuration of the same name earlier in the
2433 * path. So we must do a slow check for conflicting configurations.
2435 char *name = NameStr(form->cfgname);
2439 foreach(l, activeSearchPath)
2441 Oid namespaceId = lfirst_oid(l);
2443 if (namespaceId == myTempNamespace)
2444 continue; /* do not look in temp namespace */
2446 if (namespaceId == namespace)
2448 /* Found it first in path */
2452 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2453 PointerGetDatum(name),
2454 ObjectIdGetDatum(namespaceId)))
2456 /* Found something else first in path */
2462 ReleaseSysCache(tup);
2469 * DeconstructQualifiedName
2470 * Given a possibly-qualified name expressed as a list of String nodes,
2471 * extract the schema name and object name.
2473 * *nspname_p is set to NULL if there is no explicit schema name.
2476 DeconstructQualifiedName(List *names,
2481 char *schemaname = NULL;
2482 char *objname = NULL;
2484 switch (list_length(names))
2487 objname = strVal(linitial(names));
2490 schemaname = strVal(linitial(names));
2491 objname = strVal(lsecond(names));
2494 catalogname = strVal(linitial(names));
2495 schemaname = strVal(lsecond(names));
2496 objname = strVal(lthird(names));
2499 * We check the catalog name and then ignore it.
2501 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2503 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2504 errmsg("cross-database references are not implemented: %s",
2505 NameListToString(names))));
2509 (errcode(ERRCODE_SYNTAX_ERROR),
2510 errmsg("improper qualified name (too many dotted names): %s",
2511 NameListToString(names))));
2515 *nspname_p = schemaname;
2516 *objname_p = objname;
2520 * LookupNamespaceNoError
2521 * Look up a schema name.
2523 * Returns the namespace OID, or InvalidOid if not found.
2525 * Note this does NOT perform any permissions check --- callers are
2526 * responsible for being sure that an appropriate check is made.
2527 * In the majority of cases LookupExplicitNamespace is preferable.
2530 LookupNamespaceNoError(const char *nspname)
2532 /* check for pg_temp alias */
2533 if (strcmp(nspname, "pg_temp") == 0)
2535 if (OidIsValid(myTempNamespace))
2536 return myTempNamespace;
2539 * Since this is used only for looking up existing objects, there is
2540 * no point in trying to initialize the temp namespace here; and doing
2541 * so might create problems for some callers. Just report "not found".
2546 return get_namespace_oid(nspname, true);
2550 * LookupExplicitNamespace
2551 * Process an explicitly-specified schema name: look up the schema
2552 * and verify we have USAGE (lookup) rights in it.
2554 * Returns the namespace OID. Raises ereport if any problem.
2557 LookupExplicitNamespace(const char *nspname)
2560 AclResult aclresult;
2562 /* check for pg_temp alias */
2563 if (strcmp(nspname, "pg_temp") == 0)
2565 if (OidIsValid(myTempNamespace))
2566 return myTempNamespace;
2569 * Since this is used only for looking up existing objects, there is
2570 * no point in trying to initialize the temp namespace here; and doing
2571 * so might create problems for some callers. Just fall through and
2572 * give the "does not exist" error.
2576 namespaceId = get_namespace_oid(nspname, false);
2578 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2579 if (aclresult != ACLCHECK_OK)
2580 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2587 * LookupCreationNamespace
2588 * Look up the schema and verify we have CREATE rights on it.
2590 * This is just like LookupExplicitNamespace except for the different
2591 * permission check, and that we are willing to create pg_temp if needed.
2593 * Note: calling this may result in a CommandCounterIncrement operation,
2594 * if we have to create or clean out the temp namespace.
2597 LookupCreationNamespace(const char *nspname)
2600 AclResult aclresult;
2602 /* check for pg_temp alias */
2603 if (strcmp(nspname, "pg_temp") == 0)
2605 /* Initialize temp namespace if first time through */
2606 if (!OidIsValid(myTempNamespace))
2607 InitTempTableNamespace();
2608 return myTempNamespace;
2611 namespaceId = get_namespace_oid(nspname, false);
2613 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2614 if (aclresult != ACLCHECK_OK)
2615 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2622 * Common checks on switching namespaces.
2624 * We complain if (1) the old and new namespaces are the same, (2) either the
2625 * old or new namespaces is a temporary schema (or temporary toast schema), or
2626 * (3) either the old or new namespaces is the TOAST schema.
2629 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2631 if (oldNspOid == nspOid)
2633 (classid == RelationRelationId ?
2634 errcode(ERRCODE_DUPLICATE_TABLE) :
2635 classid == ProcedureRelationId ?
2636 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2637 errcode(ERRCODE_DUPLICATE_OBJECT),
2638 errmsg("%s is already in schema \"%s\"",
2639 getObjectDescriptionOids(classid, objid),
2640 get_namespace_name(nspOid))));
2642 /* disallow renaming into or out of temp schemas */
2643 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2645 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2646 errmsg("cannot move objects into or out of temporary schemas")));
2648 /* same for TOAST schema */
2649 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2651 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2652 errmsg("cannot move objects into or out of TOAST schema")));
2656 * QualifiedNameGetCreationNamespace
2657 * Given a possibly-qualified name for an object (in List-of-Values
2658 * format), determine what namespace the object should be created in.
2659 * Also extract and return the object name (last component of list).
2661 * Note: this does not apply any permissions check. Callers must check
2662 * for CREATE rights on the selected namespace when appropriate.
2664 * Note: calling this may result in a CommandCounterIncrement operation,
2665 * if we have to create or clean out the temp namespace.
2668 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2673 /* deconstruct the name list */
2674 DeconstructQualifiedName(names, &schemaname, objname_p);
2678 /* check for pg_temp alias */
2679 if (strcmp(schemaname, "pg_temp") == 0)
2681 /* Initialize temp namespace if first time through */
2682 if (!OidIsValid(myTempNamespace))
2683 InitTempTableNamespace();
2684 return myTempNamespace;
2686 /* use exact schema given */
2687 namespaceId = get_namespace_oid(schemaname, false);
2688 /* we do not check for USAGE rights here! */
2692 /* use the default creation namespace */
2693 recomputeNamespacePath();
2694 if (activeTempCreationPending)
2696 /* Need to initialize temp namespace */
2697 InitTempTableNamespace();
2698 return myTempNamespace;
2700 namespaceId = activeCreationNamespace;
2701 if (!OidIsValid(namespaceId))
2703 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2704 errmsg("no schema has been selected to create in")));
2711 * get_namespace_oid - given a namespace name, look up the OID
2713 * If missing_ok is false, throw an error if namespace name not found. If
2714 * true, just return InvalidOid.
2717 get_namespace_oid(const char *nspname, bool missing_ok)
2721 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2722 if (!OidIsValid(oid) && !missing_ok)
2724 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2725 errmsg("schema \"%s\" does not exist", nspname)));
2731 * makeRangeVarFromNameList
2732 * Utility routine to convert a qualified-name list into RangeVar form.
2735 makeRangeVarFromNameList(List *names)
2737 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2739 switch (list_length(names))
2742 rel->relname = strVal(linitial(names));
2745 rel->schemaname = strVal(linitial(names));
2746 rel->relname = strVal(lsecond(names));
2749 rel->catalogname = strVal(linitial(names));
2750 rel->schemaname = strVal(lsecond(names));
2751 rel->relname = strVal(lthird(names));
2755 (errcode(ERRCODE_SYNTAX_ERROR),
2756 errmsg("improper relation name (too many dotted names): %s",
2757 NameListToString(names))));
2766 * Utility routine to convert a qualified-name list into a string.
2768 * This is used primarily to form error messages, and so we do not quote
2769 * the list elements, for the sake of legibility.
2771 * In most scenarios the list elements should always be Value strings,
2772 * but we also allow A_Star for the convenience of ColumnRef processing.
2775 NameListToString(List *names)
2777 StringInfoData string;
2780 initStringInfo(&string);
2784 Node *name = (Node *) lfirst(l);
2786 if (l != list_head(names))
2787 appendStringInfoChar(&string, '.');
2789 if (IsA(name, String))
2790 appendStringInfoString(&string, strVal(name));
2791 else if (IsA(name, A_Star))
2792 appendStringInfoString(&string, "*");
2794 elog(ERROR, "unexpected node type in name list: %d",
2795 (int) nodeTag(name));
2802 * NameListToQuotedString
2803 * Utility routine to convert a qualified-name list into a string.
2805 * Same as above except that names will be double-quoted where necessary,
2806 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2809 NameListToQuotedString(List *names)
2811 StringInfoData string;
2814 initStringInfo(&string);
2818 if (l != list_head(names))
2819 appendStringInfoChar(&string, '.');
2820 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2827 * isTempNamespace - is the given namespace my temporary-table namespace?
2830 isTempNamespace(Oid namespaceId)
2832 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2838 * isTempToastNamespace - is the given namespace my temporary-toast-table
2842 isTempToastNamespace(Oid namespaceId)
2844 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2850 * isTempOrToastNamespace - is the given namespace my temporary-table
2851 * namespace or my temporary-toast-table namespace?
2854 isTempOrToastNamespace(Oid namespaceId)
2856 if (OidIsValid(myTempNamespace) &&
2857 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2863 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2864 * (either my own, or another backend's)? Temporary-toast-table namespaces
2865 * are included, too.
2868 isAnyTempNamespace(Oid namespaceId)
2873 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2874 nspname = get_namespace_name(namespaceId);
2876 return false; /* no such namespace? */
2877 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2878 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2884 * isOtherTempNamespace - is the given namespace some other backend's
2885 * temporary-table namespace (including temporary-toast-table namespaces)?
2887 * Note: for most purposes in the C code, this function is obsolete. Use
2888 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2891 isOtherTempNamespace(Oid namespaceId)
2893 /* If it's my own temp namespace, say "false" */
2894 if (isTempOrToastNamespace(namespaceId))
2896 /* Else, if it's any temp namespace, say "true" */
2897 return isAnyTempNamespace(namespaceId);
2901 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
2902 * namespace (either my own, or another backend's), return the BackendId
2903 * that owns it. Temporary-toast-table namespaces are included, too.
2904 * If it isn't a temp namespace, return InvalidBackendId.
2907 GetTempNamespaceBackendId(Oid namespaceId)
2912 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2913 nspname = get_namespace_name(namespaceId);
2915 return InvalidBackendId; /* no such namespace? */
2916 if (strncmp(nspname, "pg_temp_", 8) == 0)
2917 result = atoi(nspname + 8);
2918 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
2919 result = atoi(nspname + 14);
2921 result = InvalidBackendId;
2927 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
2928 * which must already be assigned. (This is only used when creating a toast
2929 * table for a temp table, so we must have already done InitTempTableNamespace)
2932 GetTempToastNamespace(void)
2934 Assert(OidIsValid(myTempToastNamespace));
2935 return myTempToastNamespace;
2940 * GetOverrideSearchPath - fetch current search path definition in form
2941 * used by PushOverrideSearchPath.
2943 * The result structure is allocated in the specified memory context
2944 * (which might or might not be equal to CurrentMemoryContext); but any
2945 * junk created by revalidation calculations will be in CurrentMemoryContext.
2947 OverrideSearchPath *
2948 GetOverrideSearchPath(MemoryContext context)
2950 OverrideSearchPath *result;
2952 MemoryContext oldcxt;
2954 recomputeNamespacePath();
2956 oldcxt = MemoryContextSwitchTo(context);
2958 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
2959 schemas = list_copy(activeSearchPath);
2960 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
2962 if (linitial_oid(schemas) == myTempNamespace)
2963 result->addTemp = true;
2966 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
2967 result->addCatalog = true;
2969 schemas = list_delete_first(schemas);
2971 result->schemas = schemas;
2973 MemoryContextSwitchTo(oldcxt);
2979 * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
2981 * The result structure is allocated in CurrentMemoryContext.
2983 OverrideSearchPath *
2984 CopyOverrideSearchPath(OverrideSearchPath *path)
2986 OverrideSearchPath *result;
2988 result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
2989 result->schemas = list_copy(path->schemas);
2990 result->addCatalog = path->addCatalog;
2991 result->addTemp = path->addTemp;
2997 * PushOverrideSearchPath - temporarily override the search path
2999 * We allow nested overrides, hence the push/pop terminology. The GUC
3000 * search_path variable is ignored while an override is active.
3002 * It's possible that newpath->useTemp is set but there is no longer any
3003 * active temp namespace, if the path was saved during a transaction that
3004 * created a temp namespace and was later rolled back. In that case we just
3005 * ignore useTemp. A plausible alternative would be to create a new temp
3006 * namespace, but for existing callers that's not necessary because an empty
3007 * temp namespace wouldn't affect their results anyway.
3009 * It's also worth noting that other schemas listed in newpath might not
3010 * exist anymore either. We don't worry about this because OIDs that match
3011 * no existing namespace will simply not produce any hits during searches.
3014 PushOverrideSearchPath(OverrideSearchPath *newpath)
3016 OverrideStackEntry *entry;
3019 MemoryContext oldcxt;
3022 * Copy the list for safekeeping, and insert implicitly-searched
3023 * namespaces as needed. This code should track recomputeNamespacePath.
3025 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3027 oidlist = list_copy(newpath->schemas);
3030 * Remember the first member of the explicit list.
3033 firstNS = InvalidOid;
3035 firstNS = linitial_oid(oidlist);
3038 * Add any implicitly-searched namespaces to the list. Note these go on
3039 * the front, not the back; also notice that we do not check USAGE
3040 * permissions for these.
3042 if (newpath->addCatalog)
3043 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3045 if (newpath->addTemp && OidIsValid(myTempNamespace))
3046 oidlist = lcons_oid(myTempNamespace, oidlist);
3049 * Build the new stack entry, then insert it at the head of the list.
3051 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3052 entry->searchPath = oidlist;
3053 entry->creationNamespace = firstNS;
3054 entry->nestLevel = GetCurrentTransactionNestLevel();
3056 overrideStack = lcons(entry, overrideStack);
3058 /* And make it active. */
3059 activeSearchPath = entry->searchPath;
3060 activeCreationNamespace = entry->creationNamespace;
3061 activeTempCreationPending = false; /* XXX is this OK? */
3063 MemoryContextSwitchTo(oldcxt);
3067 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3069 * Any push during a (sub)transaction will be popped automatically at abort.
3070 * But it's caller error if a push isn't popped in normal control flow.
3073 PopOverrideSearchPath(void)
3075 OverrideStackEntry *entry;
3077 /* Sanity checks. */
3078 if (overrideStack == NIL)
3079 elog(ERROR, "bogus PopOverrideSearchPath call");
3080 entry = (OverrideStackEntry *) linitial(overrideStack);
3081 if (entry->nestLevel != GetCurrentTransactionNestLevel())
3082 elog(ERROR, "bogus PopOverrideSearchPath call");
3084 /* Pop the stack and free storage. */
3085 overrideStack = list_delete_first(overrideStack);
3086 list_free(entry->searchPath);
3089 /* Activate the next level down. */
3092 entry = (OverrideStackEntry *) linitial(overrideStack);
3093 activeSearchPath = entry->searchPath;
3094 activeCreationNamespace = entry->creationNamespace;
3095 activeTempCreationPending = false; /* XXX is this OK? */
3099 /* If not baseSearchPathValid, this is useless but harmless */
3100 activeSearchPath = baseSearchPath;
3101 activeCreationNamespace = baseCreationNamespace;
3102 activeTempCreationPending = baseTempCreationPending;
3108 * get_collation_oid - find a collation by possibly qualified name
3111 get_collation_oid(List *name, bool missing_ok)
3114 char *collation_name;
3115 int32 dbencoding = GetDatabaseEncoding();
3120 /* deconstruct the name list */
3121 DeconstructQualifiedName(name, &schemaname, &collation_name);
3125 /* use exact schema given */
3126 namespaceId = LookupExplicitNamespace(schemaname);
3128 /* first try for encoding-specific entry, then any-encoding */
3129 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3130 PointerGetDatum(collation_name),
3131 Int32GetDatum(dbencoding),
3132 ObjectIdGetDatum(namespaceId));
3133 if (OidIsValid(colloid))
3135 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3136 PointerGetDatum(collation_name),
3138 ObjectIdGetDatum(namespaceId));
3139 if (OidIsValid(colloid))
3144 /* search for it in search path */
3145 recomputeNamespacePath();
3147 foreach(l, activeSearchPath)
3149 namespaceId = lfirst_oid(l);
3151 if (namespaceId == myTempNamespace)
3152 continue; /* do not look in temp namespace */
3154 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3155 PointerGetDatum(collation_name),
3156 Int32GetDatum(dbencoding),
3157 ObjectIdGetDatum(namespaceId));
3158 if (OidIsValid(colloid))
3160 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3161 PointerGetDatum(collation_name),
3163 ObjectIdGetDatum(namespaceId));
3164 if (OidIsValid(colloid))
3169 /* Not found in path */
3172 (errcode(ERRCODE_UNDEFINED_OBJECT),
3173 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3174 NameListToString(name), GetDatabaseEncodingName())));
3179 * get_conversion_oid - find a conversion by possibly qualified name
3182 get_conversion_oid(List *name, bool missing_ok)
3185 char *conversion_name;
3187 Oid conoid = InvalidOid;
3190 /* deconstruct the name list */
3191 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3195 /* use exact schema given */
3196 namespaceId = LookupExplicitNamespace(schemaname);
3197 conoid = GetSysCacheOid2(CONNAMENSP,
3198 PointerGetDatum(conversion_name),
3199 ObjectIdGetDatum(namespaceId));
3203 /* search for it in search path */
3204 recomputeNamespacePath();
3206 foreach(l, activeSearchPath)
3208 namespaceId = lfirst_oid(l);
3210 if (namespaceId == myTempNamespace)
3211 continue; /* do not look in temp namespace */
3213 conoid = GetSysCacheOid2(CONNAMENSP,
3214 PointerGetDatum(conversion_name),
3215 ObjectIdGetDatum(namespaceId));
3216 if (OidIsValid(conoid))
3221 /* Not found in path */
3222 if (!OidIsValid(conoid) && !missing_ok)
3224 (errcode(ERRCODE_UNDEFINED_OBJECT),
3225 errmsg("conversion \"%s\" does not exist",
3226 NameListToString(name))));
3231 * FindDefaultConversionProc - find default encoding conversion proc
3234 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
3239 recomputeNamespacePath();
3241 foreach(l, activeSearchPath)
3243 Oid namespaceId = lfirst_oid(l);
3245 if (namespaceId == myTempNamespace)
3246 continue; /* do not look in temp namespace */
3248 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3249 if (OidIsValid(proc))
3253 /* Not found in path */
3258 * recomputeNamespacePath - recompute path derived variables if needed.
3261 recomputeNamespacePath(void)
3263 Oid roleid = GetUserId();
3271 MemoryContext oldcxt;
3273 /* Do nothing if an override search spec is active. */
3277 /* Do nothing if path is already valid. */
3278 if (baseSearchPathValid && namespaceUser == roleid)
3281 /* Need a modifiable copy of namespace_search_path string */
3282 rawname = pstrdup(namespace_search_path);
3284 /* Parse string into list of identifiers */
3285 if (!SplitIdentifierString(rawname, ',', &namelist))
3287 /* syntax error in name list */
3288 /* this should not happen if GUC checked check_search_path */
3289 elog(ERROR, "invalid list syntax");
3293 * Convert the list of names to a list of OIDs. If any names are not
3294 * recognizable or we don't have read access, just leave them out of the
3295 * list. (We can't raise an error, since the search_path setting has
3296 * already been accepted.) Don't make duplicate entries, either.
3299 temp_missing = false;
3300 foreach(l, namelist)
3302 char *curname = (char *) lfirst(l);
3305 if (strcmp(curname, "$user") == 0)
3307 /* $user --- substitute namespace matching user name, if any */
3310 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3311 if (HeapTupleIsValid(tuple))
3315 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3316 namespaceId = get_namespace_oid(rname, true);
3317 ReleaseSysCache(tuple);
3318 if (OidIsValid(namespaceId) &&
3319 !list_member_oid(oidlist, namespaceId) &&
3320 pg_namespace_aclcheck(namespaceId, roleid,
3321 ACL_USAGE) == ACLCHECK_OK)
3322 oidlist = lappend_oid(oidlist, namespaceId);
3325 else if (strcmp(curname, "pg_temp") == 0)
3327 /* pg_temp --- substitute temp namespace, if any */
3328 if (OidIsValid(myTempNamespace))
3330 if (!list_member_oid(oidlist, myTempNamespace))
3331 oidlist = lappend_oid(oidlist, myTempNamespace);
3335 /* If it ought to be the creation namespace, set flag */
3337 temp_missing = true;
3342 /* normal namespace reference */
3343 namespaceId = get_namespace_oid(curname, true);
3344 if (OidIsValid(namespaceId) &&
3345 !list_member_oid(oidlist, namespaceId) &&
3346 pg_namespace_aclcheck(namespaceId, roleid,
3347 ACL_USAGE) == ACLCHECK_OK)
3348 oidlist = lappend_oid(oidlist, namespaceId);
3353 * Remember the first member of the explicit list. (Note: this is
3354 * nominally wrong if temp_missing, but we need it anyway to distinguish
3355 * explicit from implicit mention of pg_catalog.)
3358 firstNS = InvalidOid;
3360 firstNS = linitial_oid(oidlist);
3363 * Add any implicitly-searched namespaces to the list. Note these go on
3364 * the front, not the back; also notice that we do not check USAGE
3365 * permissions for these.
3367 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3368 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3370 if (OidIsValid(myTempNamespace) &&
3371 !list_member_oid(oidlist, myTempNamespace))
3372 oidlist = lcons_oid(myTempNamespace, oidlist);
3375 * Now that we've successfully built the new list of namespace OIDs, save
3376 * it in permanent storage.
3378 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3379 newpath = list_copy(oidlist);
3380 MemoryContextSwitchTo(oldcxt);
3382 /* Now safe to assign to state variables. */
3383 list_free(baseSearchPath);
3384 baseSearchPath = newpath;
3385 baseCreationNamespace = firstNS;
3386 baseTempCreationPending = temp_missing;
3388 /* Mark the path valid. */
3389 baseSearchPathValid = true;
3390 namespaceUser = roleid;
3392 /* And make it active. */
3393 activeSearchPath = baseSearchPath;
3394 activeCreationNamespace = baseCreationNamespace;
3395 activeTempCreationPending = baseTempCreationPending;
3399 list_free(namelist);
3404 * InitTempTableNamespace
3405 * Initialize temp table namespace on first use in a particular backend
3408 InitTempTableNamespace(void)
3410 char namespaceName[NAMEDATALEN];
3414 Assert(!OidIsValid(myTempNamespace));
3417 * First, do permission check to see if we are authorized to make temp
3418 * tables. We use a nonstandard error message here since "databasename:
3419 * permission denied" might be a tad cryptic.
3421 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3422 * that's necessary since current user ID could change during the session.
3423 * But there's no need to make the namespace in the first place until a
3424 * temp table creation request is made by someone with appropriate rights.
3426 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3427 ACL_CREATE_TEMP) != ACLCHECK_OK)
3429 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3430 errmsg("permission denied to create temporary tables in database \"%s\"",
3431 get_database_name(MyDatabaseId))));
3434 * Do not allow a Hot Standby slave session to make temp tables. Aside
3435 * from problems with modifying the system catalogs, there is a naming
3436 * conflict: pg_temp_N belongs to the session with BackendId N on the
3437 * master, not to a slave session with the same BackendId. We should not
3438 * be able to get here anyway due to XactReadOnly checks, but let's just
3439 * make real sure. Note that this also backstops various operations that
3440 * allow XactReadOnly transactions to modify temp tables; they'd need
3441 * RecoveryInProgress checks if not for this.
3443 if (RecoveryInProgress())
3445 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3446 errmsg("cannot create temporary tables during recovery")));
3448 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3450 namespaceId = get_namespace_oid(namespaceName, true);
3451 if (!OidIsValid(namespaceId))
3454 * First use of this temp namespace in this database; create it. The
3455 * temp namespaces are always owned by the superuser. We leave their
3456 * permissions at default --- i.e., no access except to superuser ---
3457 * to ensure that unprivileged users can't peek at other backends'
3458 * temp tables. This works because the places that access the temp
3459 * namespace for my own backend skip permissions checks on it.
3461 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3462 /* Advance command counter to make namespace visible */
3463 CommandCounterIncrement();
3468 * If the namespace already exists, clean it out (in case the former
3469 * owner crashed without doing so).
3471 RemoveTempRelations(namespaceId);
3475 * If the corresponding toast-table namespace doesn't exist yet, create
3476 * it. (We assume there is no need to clean it out if it does exist, since
3477 * dropping a parent table should make its toast table go away.)
3479 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3482 toastspaceId = get_namespace_oid(namespaceName, true);
3483 if (!OidIsValid(toastspaceId))
3485 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3486 /* Advance command counter to make namespace visible */
3487 CommandCounterIncrement();
3491 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3492 * so all our work could be undone by transaction rollback. Set flag for
3493 * AtEOXact_Namespace to know what to do.
3495 myTempNamespace = namespaceId;
3496 myTempToastNamespace = toastspaceId;
3498 /* It should not be done already. */
3499 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3500 myTempNamespaceSubID = GetCurrentSubTransactionId();
3502 baseSearchPathValid = false; /* need to rebuild list */
3506 * End-of-transaction cleanup for namespaces.
3509 AtEOXact_Namespace(bool isCommit)
3512 * If we abort the transaction in which a temp namespace was selected,
3513 * we'll have to do any creation or cleanout work over again. So, just
3514 * forget the namespace entirely until next time. On the other hand, if
3515 * we commit then register an exit callback to clean out the temp tables
3516 * at backend shutdown. (We only want to register the callback once per
3517 * session, so this is a good place to do it.)
3519 if (myTempNamespaceSubID != InvalidSubTransactionId)
3522 on_shmem_exit(RemoveTempRelationsCallback, 0);
3525 myTempNamespace = InvalidOid;
3526 myTempToastNamespace = InvalidOid;
3527 baseSearchPathValid = false; /* need to rebuild list */
3529 myTempNamespaceSubID = InvalidSubTransactionId;
3533 * Clean up if someone failed to do PopOverrideSearchPath
3538 elog(WARNING, "leaked override search path");
3539 while (overrideStack)
3541 OverrideStackEntry *entry;
3543 entry = (OverrideStackEntry *) linitial(overrideStack);
3544 overrideStack = list_delete_first(overrideStack);
3545 list_free(entry->searchPath);
3548 /* If not baseSearchPathValid, this is useless but harmless */
3549 activeSearchPath = baseSearchPath;
3550 activeCreationNamespace = baseCreationNamespace;
3551 activeTempCreationPending = baseTempCreationPending;
3556 * AtEOSubXact_Namespace
3558 * At subtransaction commit, propagate the temp-namespace-creation
3559 * flag to the parent subtransaction.
3561 * At subtransaction abort, forget the flag if we set it up.
3564 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3565 SubTransactionId parentSubid)
3567 OverrideStackEntry *entry;
3569 if (myTempNamespaceSubID == mySubid)
3572 myTempNamespaceSubID = parentSubid;
3575 myTempNamespaceSubID = InvalidSubTransactionId;
3576 /* TEMP namespace creation failed, so reset state */
3577 myTempNamespace = InvalidOid;
3578 myTempToastNamespace = InvalidOid;
3579 baseSearchPathValid = false; /* need to rebuild list */
3584 * Clean up if someone failed to do PopOverrideSearchPath
3586 while (overrideStack)
3588 entry = (OverrideStackEntry *) linitial(overrideStack);
3589 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3592 elog(WARNING, "leaked override search path");
3593 overrideStack = list_delete_first(overrideStack);
3594 list_free(entry->searchPath);
3598 /* Activate the next level down. */
3601 entry = (OverrideStackEntry *) linitial(overrideStack);
3602 activeSearchPath = entry->searchPath;
3603 activeCreationNamespace = entry->creationNamespace;
3604 activeTempCreationPending = false; /* XXX is this OK? */
3608 /* If not baseSearchPathValid, this is useless but harmless */
3609 activeSearchPath = baseSearchPath;
3610 activeCreationNamespace = baseCreationNamespace;
3611 activeTempCreationPending = baseTempCreationPending;
3616 * Remove all relations in the specified temp namespace.
3618 * This is called at backend shutdown (if we made any temp relations).
3619 * It is also called when we begin using a pre-existing temp namespace,
3620 * in order to clean out any relations that might have been created by
3621 * a crashed backend.
3624 RemoveTempRelations(Oid tempNamespaceId)
3626 ObjectAddress object;
3629 * We want to get rid of everything in the target namespace, but not the
3630 * namespace itself (deleting it only to recreate it later would be a
3631 * waste of cycles). We do this by finding everything that has a
3632 * dependency on the namespace.
3634 object.classId = NamespaceRelationId;
3635 object.objectId = tempNamespaceId;
3636 object.objectSubId = 0;
3638 deleteWhatDependsOn(&object, false);
3642 * Callback to remove temp relations at backend exit.
3645 RemoveTempRelationsCallback(int code, Datum arg)
3647 if (OidIsValid(myTempNamespace)) /* should always be true */
3649 /* Need to ensure we have a usable transaction. */
3650 AbortOutOfAnyTransaction();
3651 StartTransactionCommand();
3653 RemoveTempRelations(myTempNamespace);
3655 CommitTransactionCommand();
3660 * Remove all temp tables from the temporary namespace.
3663 ResetTempTableNamespace(void)
3665 if (OidIsValid(myTempNamespace))
3666 RemoveTempRelations(myTempNamespace);
3671 * Routines for handling the GUC variable 'search_path'.
3674 /* check_hook: validate new search_path, if possible */
3676 check_search_path(char **newval, void **extra, GucSource source)
3683 /* Need a modifiable copy of string */
3684 rawname = pstrdup(*newval);
3686 /* Parse string into list of identifiers */
3687 if (!SplitIdentifierString(rawname, ',', &namelist))
3689 /* syntax error in name list */
3690 GUC_check_errdetail("List syntax is invalid.");
3692 list_free(namelist);
3697 * If we aren't inside a transaction, we cannot do database access so
3698 * cannot verify the individual names. Must accept the list on faith.
3700 if (IsTransactionState())
3703 * Verify that all the names are either valid namespace names or
3704 * "$user" or "pg_temp". We do not require $user to correspond to a
3705 * valid namespace, and pg_temp might not exist yet. We do not check
3706 * for USAGE rights, either; should we?
3708 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3709 * DATABASE SET or ALTER USER SET command. It could be that the
3710 * intended use of the search path is for some other database, so we
3711 * should not error out if it mentions schemas not present in the
3712 * current database. We issue a NOTICE instead.
3714 foreach(l, namelist)
3716 char *curname = (char *) lfirst(l);
3718 if (strcmp(curname, "$user") == 0)
3720 if (strcmp(curname, "pg_temp") == 0)
3722 if (!SearchSysCacheExists1(NAMESPACENAME,
3723 CStringGetDatum(curname)))
3725 if (source == PGC_S_TEST)
3727 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3728 errmsg("schema \"%s\" does not exist", curname)));
3731 GUC_check_errdetail("schema \"%s\" does not exist", curname);
3740 list_free(namelist);
3745 /* assign_hook: do extra actions as needed */
3747 assign_search_path(const char *newval, void *extra)
3750 * We mark the path as needing recomputation, but don't do anything until
3751 * it's needed. This avoids trying to do database access during GUC
3752 * initialization, or outside a transaction.
3754 baseSearchPathValid = false;
3758 * InitializeSearchPath: initialize module during InitPostgres.
3760 * This is called after we are up enough to be able to do catalog lookups.
3763 InitializeSearchPath(void)
3765 if (IsBootstrapProcessingMode())
3768 * In bootstrap mode, the search path must be 'pg_catalog' so that
3769 * tables are created in the proper namespace; ignore the GUC setting.
3771 MemoryContext oldcxt;
3773 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3774 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3775 MemoryContextSwitchTo(oldcxt);
3776 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3777 baseTempCreationPending = false;
3778 baseSearchPathValid = true;
3779 namespaceUser = GetUserId();
3780 activeSearchPath = baseSearchPath;
3781 activeCreationNamespace = baseCreationNamespace;
3782 activeTempCreationPending = baseTempCreationPending;
3787 * In normal mode, arrange for a callback on any syscache invalidation
3788 * of pg_namespace rows.
3790 CacheRegisterSyscacheCallback(NAMESPACEOID,
3793 /* Force search path to be recomputed on next use */
3794 baseSearchPathValid = false;
3800 * Syscache inval callback function
3803 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3805 /* Force search path to be recomputed on next use */
3806 baseSearchPathValid = false;
3810 * Fetch the active search path. The return value is a palloc'ed list
3811 * of OIDs; the caller is responsible for freeing this storage as
3814 * The returned list includes the implicitly-prepended namespaces only if
3815 * includeImplicit is true.
3817 * Note: calling this may result in a CommandCounterIncrement operation,
3818 * if we have to create or clean out the temp namespace.
3821 fetch_search_path(bool includeImplicit)
3825 recomputeNamespacePath();
3828 * If the temp namespace should be first, force it to exist. This is so
3829 * that callers can trust the result to reflect the actual default
3830 * creation namespace. It's a bit bogus to do this here, since
3831 * current_schema() is supposedly a stable function without side-effects,
3832 * but the alternatives seem worse.
3834 if (activeTempCreationPending)
3836 InitTempTableNamespace();
3837 recomputeNamespacePath();
3840 result = list_copy(activeSearchPath);
3841 if (!includeImplicit)
3843 while (result && linitial_oid(result) != activeCreationNamespace)
3844 result = list_delete_first(result);
3851 * Fetch the active search path into a caller-allocated array of OIDs.
3852 * Returns the number of path entries. (If this is more than sarray_len,
3853 * then the data didn't fit and is not all stored.)
3855 * The returned list always includes the implicitly-prepended namespaces,
3856 * but never includes the temp namespace. (This is suitable for existing
3857 * users, which would want to ignore the temp namespace anyway.) This
3858 * definition allows us to not worry about initializing the temp namespace.
3861 fetch_search_path_array(Oid *sarray, int sarray_len)
3866 recomputeNamespacePath();
3868 foreach(l, activeSearchPath)
3870 Oid namespaceId = lfirst_oid(l);
3872 if (namespaceId == myTempNamespace)
3873 continue; /* do not include temp namespace */
3875 if (count < sarray_len)
3876 sarray[count] = namespaceId;
3885 * Export the FooIsVisible functions as SQL-callable functions.
3887 * Note: as of Postgres 8.4, these will silently return NULL if called on
3888 * a nonexistent object OID, rather than failing. This is to avoid race
3889 * condition errors when a query that's scanning a catalog using an MVCC
3890 * snapshot uses one of these functions. The underlying IsVisible functions
3891 * operate on SnapshotNow semantics and so might see the object as already
3892 * gone when it's still visible to the MVCC snapshot. (There is no race
3893 * condition in the current coding because we don't accept sinval messages
3894 * between the SearchSysCacheExists test and the subsequent lookup.)
3898 pg_table_is_visible(PG_FUNCTION_ARGS)
3900 Oid oid = PG_GETARG_OID(0);
3902 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3905 PG_RETURN_BOOL(RelationIsVisible(oid));
3909 pg_type_is_visible(PG_FUNCTION_ARGS)
3911 Oid oid = PG_GETARG_OID(0);
3913 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3916 PG_RETURN_BOOL(TypeIsVisible(oid));
3920 pg_function_is_visible(PG_FUNCTION_ARGS)
3922 Oid oid = PG_GETARG_OID(0);
3924 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3927 PG_RETURN_BOOL(FunctionIsVisible(oid));
3931 pg_operator_is_visible(PG_FUNCTION_ARGS)
3933 Oid oid = PG_GETARG_OID(0);
3935 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3938 PG_RETURN_BOOL(OperatorIsVisible(oid));
3942 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3944 Oid oid = PG_GETARG_OID(0);
3946 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3949 PG_RETURN_BOOL(OpclassIsVisible(oid));
3953 pg_opfamily_is_visible(PG_FUNCTION_ARGS)
3955 Oid oid = PG_GETARG_OID(0);
3957 if (!SearchSysCacheExists1(OPFAMILYOID, ObjectIdGetDatum(oid)))
3960 PG_RETURN_BOOL(OpfamilyIsVisible(oid));
3964 pg_collation_is_visible(PG_FUNCTION_ARGS)
3966 Oid oid = PG_GETARG_OID(0);
3968 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
3971 PG_RETURN_BOOL(CollationIsVisible(oid));
3975 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3977 Oid oid = PG_GETARG_OID(0);
3979 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3982 PG_RETURN_BOOL(ConversionIsVisible(oid));
3986 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3988 Oid oid = PG_GETARG_OID(0);
3990 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3993 PG_RETURN_BOOL(TSParserIsVisible(oid));
3997 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3999 Oid oid = PG_GETARG_OID(0);
4001 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
4004 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
4008 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
4010 Oid oid = PG_GETARG_OID(0);
4012 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
4015 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
4019 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
4021 Oid oid = PG_GETARG_OID(0);
4023 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
4026 PG_RETURN_BOOL(TSConfigIsVisible(oid));
4030 pg_my_temp_schema(PG_FUNCTION_ARGS)
4032 PG_RETURN_OID(myTempNamespace);
4036 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
4038 Oid oid = PG_GETARG_OID(0);
4040 PG_RETURN_BOOL(isOtherTempNamespace(oid));