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/namespace.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_collation.h"
27 #include "catalog/pg_conversion.h"
28 #include "catalog/pg_conversion_fn.h"
29 #include "catalog/pg_namespace.h"
30 #include "catalog/pg_opclass.h"
31 #include "catalog/pg_operator.h"
32 #include "catalog/pg_opfamily.h"
33 #include "catalog/pg_proc.h"
34 #include "catalog/pg_ts_config.h"
35 #include "catalog/pg_ts_dict.h"
36 #include "catalog/pg_ts_parser.h"
37 #include "catalog/pg_ts_template.h"
38 #include "catalog/pg_type.h"
39 #include "commands/dbcommands.h"
41 #include "mb/pg_wchar.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "parser/parse_func.h"
45 #include "storage/backendid.h"
46 #include "storage/ipc.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/rel.h"
54 #include "utils/syscache.h"
58 * The namespace search path is a possibly-empty list of namespace OIDs.
59 * In addition to the explicit list, implicitly-searched namespaces
62 * 1. If a TEMP table namespace has been initialized in this session, it
63 * is implicitly searched first. (The only time this doesn't happen is
64 * when we are obeying an override search path spec that says not to use the
65 * temp namespace, or the temp namespace is included in the explicit list.)
67 * 2. The system catalog namespace is always searched. If the system
68 * namespace is present in the explicit path then it will be searched in
69 * the specified order; otherwise it will be searched after TEMP tables and
70 * *before* the explicit list. (It might seem that the system namespace
71 * should be implicitly last, but this behavior appears to be required by
72 * SQL99. Also, this provides a way to search the system namespace first
73 * without thereby making it the default creation target namespace.)
75 * For security reasons, searches using the search path will ignore the temp
76 * namespace when searching for any object type other than relations and
77 * types. (We must allow types since temp tables have rowtypes.)
79 * The default creation target namespace is always the first element of the
80 * explicit list. If the explicit list is empty, there is no default target.
82 * The textual specification of search_path can include "$user" to refer to
83 * the namespace named the same as the current user, if any. (This is just
84 * ignored if there is no such namespace.) Also, it can include "pg_temp"
85 * to refer to the current backend's temp namespace. This is usually also
86 * ignorable if the temp namespace hasn't been set up, but there's a special
87 * case: if "pg_temp" appears first then it should be the default creation
88 * target. We kluge this case a little bit so that the temp namespace isn't
89 * set up until the first attempt to create something in it. (The reason for
90 * klugery is that we can't create the temp namespace outside a transaction,
91 * but initial GUC processing of search_path happens outside a transaction.)
92 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
93 * but is not reflected in activeCreationNamespace because the namespace isn't
96 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
97 * the system namespace is the only one searched or inserted into.
98 * initdb is also careful to set search_path to "pg_catalog" for its
99 * post-bootstrap standalone backend runs. Otherwise the default search
100 * path is determined by GUC. The factory default path contains the PUBLIC
101 * namespace (if it exists), preceded by the user's personal namespace
104 * We support a stack of "override" search path settings for use within
105 * specific sections of backend code. namespace_search_path is ignored
106 * whenever the override stack is nonempty. activeSearchPath is always
107 * the actually active path; it points either to the search list of the
108 * topmost stack entry, or to baseSearchPath which is the list derived
109 * from namespace_search_path.
111 * If baseSearchPathValid is false, then baseSearchPath (and other
112 * derived variables) need to be recomputed from namespace_search_path.
113 * We mark it invalid upon an assignment to namespace_search_path or receipt
114 * of a syscache invalidation event for pg_namespace. The recomputation
115 * is done during the next non-overridden lookup attempt. Note that an
116 * override spec is never subject to recomputation.
118 * Any namespaces mentioned in namespace_search_path that are not readable
119 * by the current user ID are simply left out of baseSearchPath; so
120 * we have to be willing to recompute the path when current userid changes.
121 * namespaceUser is the userid the path has been computed for.
123 * Note: all data pointed to by these List variables is in TopMemoryContext.
126 /* These variables define the actually active state: */
128 static List *activeSearchPath = NIL;
130 /* default place to create stuff; if InvalidOid, no default */
131 static Oid activeCreationNamespace = InvalidOid;
133 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
134 static bool activeTempCreationPending = false;
136 /* These variables are the values last derived from namespace_search_path: */
138 static List *baseSearchPath = NIL;
140 static Oid baseCreationNamespace = InvalidOid;
142 static bool baseTempCreationPending = false;
144 static Oid namespaceUser = InvalidOid;
146 /* The above four values are valid only if baseSearchPathValid */
147 static bool baseSearchPathValid = true;
149 /* Override requests are remembered in a stack of OverrideStackEntry structs */
153 List *searchPath; /* the desired search path */
154 Oid creationNamespace; /* the desired creation namespace */
155 int nestLevel; /* subtransaction nesting level */
156 } OverrideStackEntry;
158 static List *overrideStack = NIL;
161 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
162 * in a particular backend session (this happens when a CREATE TEMP TABLE
163 * command is first executed). Thereafter it's the OID of the temp namespace.
165 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
166 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
168 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
169 * current subtransaction. The flag propagates up the subtransaction tree,
170 * so the main transaction will correctly recognize the flag if all
171 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
172 * we either haven't made the TEMP namespace yet, or have successfully
173 * committed its creation, depending on whether myTempNamespace is valid.
175 static Oid myTempNamespace = InvalidOid;
177 static Oid myTempToastNamespace = InvalidOid;
179 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
182 * This is the user's textual search path specification --- it's the value
183 * of the GUC variable 'search_path'.
185 char *namespace_search_path = NULL;
188 /* Local functions */
189 static void recomputeNamespacePath(void);
190 static void InitTempTableNamespace(void);
191 static void RemoveTempRelations(Oid tempNamespaceId);
192 static void RemoveTempRelationsCallback(int code, Datum arg);
193 static void NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr);
194 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
197 /* These don't really need to appear in any header file */
198 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
199 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
200 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_opclass_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 failOK = true,
219 * otherwise raise an error.
222 RangeVarGetRelid(const RangeVar *relation, bool failOK)
228 * We check the catalog name and then ignore it.
230 if (relation->catalogname)
232 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
235 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
236 relation->catalogname, relation->schemaname,
237 relation->relname)));
241 * Some non-default relpersistence value may have been specified. The
242 * parser never generates such a RangeVar in simple DML, but it can happen
243 * in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY KEY)". Such
244 * a command will generate an added CREATE INDEX operation, which must be
245 * careful to find the temp table, even when pg_temp is not first in the
248 if (relation->relpersistence == RELPERSISTENCE_TEMP)
250 if (relation->schemaname)
252 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
253 errmsg("temporary tables cannot specify a schema name")));
254 if (OidIsValid(myTempNamespace))
255 relId = get_relname_relid(relation->relname, myTempNamespace);
256 else /* this probably can't happen? */
259 else if (relation->schemaname)
261 /* use exact schema given */
262 namespaceId = LookupExplicitNamespace(relation->schemaname);
263 relId = get_relname_relid(relation->relname, namespaceId);
267 /* search the namespace path */
268 relId = RelnameGetRelid(relation->relname);
271 if (!OidIsValid(relId) && !failOK)
273 if (relation->schemaname)
275 (errcode(ERRCODE_UNDEFINED_TABLE),
276 errmsg("relation \"%s.%s\" does not exist",
277 relation->schemaname, relation->relname)));
280 (errcode(ERRCODE_UNDEFINED_TABLE),
281 errmsg("relation \"%s\" does not exist",
282 relation->relname)));
288 * RangeVarGetCreationNamespace
289 * Given a RangeVar describing a to-be-created relation,
290 * choose which namespace to create it in.
292 * Note: calling this may result in a CommandCounterIncrement operation.
293 * That will happen on the first request for a temp table in any particular
294 * backend run; we will need to either create or clean out the temp schema.
297 RangeVarGetCreationNamespace(const RangeVar *newRelation)
302 * We check the catalog name and then ignore it.
304 if (newRelation->catalogname)
306 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
308 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
309 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
310 newRelation->catalogname, newRelation->schemaname,
311 newRelation->relname)));
314 if (newRelation->schemaname)
316 /* check for pg_temp alias */
317 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
319 /* Initialize temp namespace if first time through */
320 if (!OidIsValid(myTempNamespace))
321 InitTempTableNamespace();
322 return myTempNamespace;
324 /* use exact schema given */
325 namespaceId = get_namespace_oid(newRelation->schemaname, false);
326 /* we do not check for USAGE rights here! */
328 else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
330 /* Initialize temp namespace if first time through */
331 if (!OidIsValid(myTempNamespace))
332 InitTempTableNamespace();
333 return myTempNamespace;
337 /* use the default creation namespace */
338 recomputeNamespacePath();
339 if (activeTempCreationPending)
341 /* Need to initialize temp namespace */
342 InitTempTableNamespace();
343 return myTempNamespace;
345 namespaceId = activeCreationNamespace;
346 if (!OidIsValid(namespaceId))
348 (errcode(ERRCODE_UNDEFINED_SCHEMA),
349 errmsg("no schema has been selected to create in")));
352 /* Note: callers will check for CREATE rights when appropriate */
358 * RangeVarGetAndCheckCreationNamespace
359 * As RangeVarGetCreationNamespace, but with a permissions check.
362 RangeVarGetAndCheckCreationNamespace(const RangeVar *newRelation)
366 namespaceId = RangeVarGetCreationNamespace(newRelation);
369 * Check we have permission to create there. Skip check if bootstrapping,
370 * since permissions machinery may not be working yet.
372 if (!IsBootstrapProcessingMode())
376 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(),
378 if (aclresult != ACLCHECK_OK)
379 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
380 get_namespace_name(namespaceId));
387 * Adjust the relpersistence for an about-to-be-created relation based on the
388 * creation namespace, and throw an error for invalid combinations.
391 RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
393 switch (newRelation->relpersistence)
395 case RELPERSISTENCE_TEMP:
396 if (!isTempOrToastNamespace(nspid))
398 if (isAnyTempNamespace(nspid))
400 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
401 errmsg("cannot create relations in temporary schemas of other sessions")));
404 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
405 errmsg("cannot create temporary relation in non-temporary schema")));
408 case RELPERSISTENCE_PERMANENT:
409 if (isTempOrToastNamespace(nspid))
410 newRelation->relpersistence = RELPERSISTENCE_TEMP;
411 else if (isAnyTempNamespace(nspid))
413 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
414 errmsg("cannot create relations in temporary schemas of other sessions")));
418 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
419 errmsg("only temporary relations may be created in temporary schemas")));
425 * Try to resolve an unqualified relation name.
426 * Returns OID if relation found in search path, else InvalidOid.
429 RelnameGetRelid(const char *relname)
434 recomputeNamespacePath();
436 foreach(l, activeSearchPath)
438 Oid namespaceId = lfirst_oid(l);
440 relid = get_relname_relid(relname, namespaceId);
441 if (OidIsValid(relid))
445 /* Not found in path */
452 * Determine whether a relation (identified by OID) is visible in the
453 * current search path. Visible means "would be found by searching
454 * for the unqualified relation name".
457 RelationIsVisible(Oid relid)
460 Form_pg_class relform;
464 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
465 if (!HeapTupleIsValid(reltup))
466 elog(ERROR, "cache lookup failed for relation %u", relid);
467 relform = (Form_pg_class) GETSTRUCT(reltup);
469 recomputeNamespacePath();
472 * Quick check: if it ain't in the path at all, it ain't visible. Items in
473 * the system namespace are surely in the path and so we needn't even do
474 * list_member_oid() for them.
476 relnamespace = relform->relnamespace;
477 if (relnamespace != PG_CATALOG_NAMESPACE &&
478 !list_member_oid(activeSearchPath, relnamespace))
483 * If it is in the path, it might still not be visible; it could be
484 * hidden by another relation of the same name earlier in the path. So
485 * we must do a slow check for conflicting relations.
487 char *relname = NameStr(relform->relname);
491 foreach(l, activeSearchPath)
493 Oid namespaceId = lfirst_oid(l);
495 if (namespaceId == relnamespace)
497 /* Found it first in path */
501 if (OidIsValid(get_relname_relid(relname, namespaceId)))
503 /* Found something else first in path */
509 ReleaseSysCache(reltup);
517 * Try to resolve an unqualified datatype name.
518 * Returns OID if type found in search path, else InvalidOid.
520 * This is essentially the same as RelnameGetRelid.
523 TypenameGetTypid(const char *typname)
528 recomputeNamespacePath();
530 foreach(l, activeSearchPath)
532 Oid namespaceId = lfirst_oid(l);
534 typid = GetSysCacheOid2(TYPENAMENSP,
535 PointerGetDatum(typname),
536 ObjectIdGetDatum(namespaceId));
537 if (OidIsValid(typid))
541 /* Not found in path */
547 * Determine whether a type (identified by OID) is visible in the
548 * current search path. Visible means "would be found by searching
549 * for the unqualified type name".
552 TypeIsVisible(Oid typid)
555 Form_pg_type typform;
559 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
560 if (!HeapTupleIsValid(typtup))
561 elog(ERROR, "cache lookup failed for type %u", typid);
562 typform = (Form_pg_type) GETSTRUCT(typtup);
564 recomputeNamespacePath();
567 * Quick check: if it ain't in the path at all, it ain't visible. Items in
568 * the system namespace are surely in the path and so we needn't even do
569 * list_member_oid() for them.
571 typnamespace = typform->typnamespace;
572 if (typnamespace != PG_CATALOG_NAMESPACE &&
573 !list_member_oid(activeSearchPath, typnamespace))
578 * If it is in the path, it might still not be visible; it could be
579 * hidden by another type of the same name earlier in the path. So we
580 * must do a slow check for conflicting types.
582 char *typname = NameStr(typform->typname);
586 foreach(l, activeSearchPath)
588 Oid namespaceId = lfirst_oid(l);
590 if (namespaceId == typnamespace)
592 /* Found it first in path */
596 if (SearchSysCacheExists2(TYPENAMENSP,
597 PointerGetDatum(typname),
598 ObjectIdGetDatum(namespaceId)))
600 /* Found something else first in path */
606 ReleaseSysCache(typtup);
613 * FuncnameGetCandidates
614 * Given a possibly-qualified function name and argument count,
615 * retrieve a list of the possible matches.
617 * If nargs is -1, we return all functions matching the given name,
618 * regardless of argument count. (argnames must be NIL, and expand_variadic
619 * and expand_defaults must be false, in this case.)
621 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
622 * and only functions having all the listed argument names will be returned.
623 * (We assume that length(argnames) <= nargs and all the passed-in names are
624 * distinct.) The returned structs will include an argnumbers array showing
625 * the actual argument index for each logical argument position.
627 * If expand_variadic is true, then variadic functions having the same number
628 * or fewer arguments will be retrieved, with the variadic argument and any
629 * additional argument positions filled with the variadic element type.
630 * nvargs in the returned struct is set to the number of such arguments.
631 * If expand_variadic is false, variadic arguments are not treated specially,
632 * and the returned nvargs will always be zero.
634 * If expand_defaults is true, functions that could match after insertion of
635 * default argument values will also be retrieved. In this case the returned
636 * structs could have nargs > passed-in nargs, and ndargs is set to the number
637 * of additional args (which can be retrieved from the function's
638 * proargdefaults entry).
640 * It is not possible for nvargs and ndargs to both be nonzero in the same
641 * list entry, since default insertion allows matches to functions with more
642 * than nargs arguments while the variadic transformation requires the same
645 * When argnames isn't NIL, the returned args[] type arrays are not ordered
646 * according to the functions' declarations, but rather according to the call:
647 * first any positional arguments, then the named arguments, then defaulted
648 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
649 * array can be used to map this back to the catalog information.
650 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
652 * We search a single namespace if the function name is qualified, else
653 * all namespaces in the search path. In the multiple-namespace case,
654 * we arrange for entries in earlier namespaces to mask identical entries in
657 * When expanding variadics, we arrange for non-variadic functions to mask
658 * variadic ones if the expanded argument list is the same. It is still
659 * possible for there to be conflicts between different variadic functions,
662 * It is guaranteed that the return list will never contain multiple entries
663 * with identical argument lists. When expand_defaults is true, the entries
664 * could have more than nargs positions, but we still guarantee that they are
665 * distinct in the first nargs positions. However, if argnames isn't NIL or
666 * either expand_variadic or expand_defaults is true, there might be multiple
667 * candidate functions that expand to identical argument lists. Rather than
668 * throw error here, we report such situations by returning a single entry
669 * with oid = 0 that represents a set of such conflicting candidates.
670 * The caller might end up discarding such an entry anyway, but if it selects
671 * such an entry it should react as though the call were ambiguous.
674 FuncnameGetCandidates(List *names, int nargs, List *argnames,
675 bool expand_variadic, bool expand_defaults)
677 FuncCandidateList resultList = NULL;
678 bool any_special = false;
685 /* check for caller error */
686 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
688 /* deconstruct the name list */
689 DeconstructQualifiedName(names, &schemaname, &funcname);
693 /* use exact schema given */
694 namespaceId = LookupExplicitNamespace(schemaname);
698 /* flag to indicate we need namespace search */
699 namespaceId = InvalidOid;
700 recomputeNamespacePath();
703 /* Search syscache by name only */
704 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
706 for (i = 0; i < catlist->n_members; i++)
708 HeapTuple proctup = &catlist->members[i]->tuple;
709 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
710 int pronargs = procform->pronargs;
716 int *argnumbers = NULL;
717 FuncCandidateList newResult;
719 if (OidIsValid(namespaceId))
721 /* Consider only procs in specified namespace */
722 if (procform->pronamespace != namespaceId)
728 * Consider only procs that are in the search path and are not in
729 * the temp namespace.
733 foreach(nsp, activeSearchPath)
735 if (procform->pronamespace == lfirst_oid(nsp) &&
736 procform->pronamespace != myTempNamespace)
741 continue; /* proc is not in search path */
747 * Call uses named or mixed notation
749 * Named or mixed notation can match a variadic function only if
750 * expand_variadic is off; otherwise there is no way to match the
751 * presumed-nameless parameters expanded from the variadic array.
753 if (OidIsValid(procform->provariadic) && expand_variadic)
755 va_elem_type = InvalidOid;
759 * Check argument count.
761 Assert(nargs >= 0); /* -1 not supported with argnames */
763 if (pronargs > nargs && expand_defaults)
765 /* Ignore if not enough default expressions */
766 if (nargs + procform->pronargdefaults < pronargs)
771 use_defaults = false;
773 /* Ignore if it doesn't match requested argument count */
774 if (pronargs != nargs && !use_defaults)
777 /* Check for argument name match, generate positional mapping */
778 if (!MatchNamedCall(proctup, nargs, argnames,
782 /* Named argument matching is always "special" */
788 * Call uses positional notation
790 * Check if function is variadic, and get variadic element type if
791 * so. If expand_variadic is false, we should just ignore
794 if (pronargs <= nargs && expand_variadic)
796 va_elem_type = procform->provariadic;
797 variadic = OidIsValid(va_elem_type);
798 any_special |= variadic;
802 va_elem_type = InvalidOid;
807 * Check if function can match by using parameter defaults.
809 if (pronargs > nargs && expand_defaults)
811 /* Ignore if not enough default expressions */
812 if (nargs + procform->pronargdefaults < pronargs)
818 use_defaults = false;
820 /* Ignore if it doesn't match requested argument count */
821 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
826 * We must compute the effective argument list so that we can easily
827 * compare it to earlier results. We waste a palloc cycle if it gets
828 * masked by an earlier result, but really that's a pretty infrequent
829 * case so it's not worth worrying about.
831 effective_nargs = Max(pronargs, nargs);
832 newResult = (FuncCandidateList)
833 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
834 + effective_nargs * sizeof(Oid));
835 newResult->pathpos = pathpos;
836 newResult->oid = HeapTupleGetOid(proctup);
837 newResult->nargs = effective_nargs;
838 newResult->argnumbers = argnumbers;
841 /* Re-order the argument types into call's logical order */
842 Oid *proargtypes = procform->proargtypes.values;
845 for (i = 0; i < pronargs; i++)
846 newResult->args[i] = proargtypes[argnumbers[i]];
850 /* Simple positional case, just copy proargtypes as-is */
851 memcpy(newResult->args, procform->proargtypes.values,
852 pronargs * sizeof(Oid));
858 newResult->nvargs = effective_nargs - pronargs + 1;
859 /* Expand variadic argument into N copies of element type */
860 for (i = pronargs - 1; i < effective_nargs; i++)
861 newResult->args[i] = va_elem_type;
864 newResult->nvargs = 0;
865 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
868 * Does it have the same arguments as something we already accepted?
869 * If so, decide what to do to avoid returning duplicate argument
870 * lists. We can skip this check for the single-namespace case if no
871 * special (named, variadic or defaults) match has been made, since
872 * then the unique index on pg_proc guarantees all the matches have
873 * different argument lists.
875 if (resultList != NULL &&
876 (any_special || !OidIsValid(namespaceId)))
879 * If we have an ordered list from SearchSysCacheList (the normal
880 * case), then any conflicting proc must immediately adjoin this
881 * one in the list, so we only need to look at the newest result
882 * item. If we have an unordered list, we have to scan the whole
883 * result list. Also, if either the current candidate or any
884 * previous candidate is a special match, we can't assume that
885 * conflicts are adjacent.
887 * We ignore defaulted arguments in deciding what is a match.
889 FuncCandidateList prevResult;
891 if (catlist->ordered && !any_special)
893 /* ndargs must be 0 if !any_special */
894 if (effective_nargs == resultList->nargs &&
895 memcmp(newResult->args,
897 effective_nargs * sizeof(Oid)) == 0)
898 prevResult = resultList;
904 int cmp_nargs = newResult->nargs - newResult->ndargs;
906 for (prevResult = resultList;
908 prevResult = prevResult->next)
910 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
911 memcmp(newResult->args,
913 cmp_nargs * sizeof(Oid)) == 0)
921 * We have a match with a previous result. Decide which one
922 * to keep, or mark it ambiguous if we can't decide. The
923 * logic here is preference > 0 means prefer the old result,
924 * preference < 0 means prefer the new, preference = 0 means
929 if (pathpos != prevResult->pathpos)
932 * Prefer the one that's earlier in the search path.
934 preference = pathpos - prevResult->pathpos;
936 else if (variadic && prevResult->nvargs == 0)
939 * With variadic functions we could have, for example,
940 * both foo(numeric) and foo(variadic numeric[]) in the
941 * same namespace; if so we prefer the non-variadic match
942 * on efficiency grounds.
946 else if (!variadic && prevResult->nvargs > 0)
953 * We can't decide. This can happen with, for example,
954 * both foo(numeric, variadic numeric[]) and
955 * foo(variadic numeric[]) in the same namespace, or
956 * both foo(int) and foo (int, int default something)
957 * in the same namespace, or both foo(a int, b text)
958 * and foo(b text, a int) in the same namespace.
966 /* keep previous result */
970 else if (preference < 0)
972 /* remove previous result from the list */
973 if (prevResult == resultList)
974 resultList = prevResult->next;
977 FuncCandidateList prevPrevResult;
979 for (prevPrevResult = resultList;
981 prevPrevResult = prevPrevResult->next)
983 if (prevResult == prevPrevResult->next)
985 prevPrevResult->next = prevResult->next;
989 Assert(prevPrevResult); /* assert we found it */
992 /* fall through to add newResult to list */
996 /* mark old result as ambiguous, discard new */
997 prevResult->oid = InvalidOid;
1005 * Okay to add it to result list
1007 newResult->next = resultList;
1008 resultList = newResult;
1011 ReleaseSysCacheList(catlist);
1018 * Given a pg_proc heap tuple and a call's list of argument names,
1019 * check whether the function could match the call.
1021 * The call could match if all supplied argument names are accepted by
1022 * the function, in positions after the last positional argument, and there
1023 * are defaults for all unsupplied arguments.
1025 * The number of positional arguments is nargs - list_length(argnames).
1026 * Note caller has already done basic checks on argument count.
1028 * On match, return true and fill *argnumbers with a palloc'd array showing
1029 * the mapping from call argument positions to actual function argument
1030 * numbers. Defaulted arguments are included in this map, at positions
1031 * after the last supplied argument.
1034 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1037 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1038 int pronargs = procform->pronargs;
1039 int numposargs = nargs - list_length(argnames);
1044 bool arggiven[FUNC_MAX_ARGS];
1046 int ap; /* call args position */
1047 int pp; /* proargs position */
1050 Assert(argnames != NIL);
1051 Assert(numposargs >= 0);
1052 Assert(nargs <= pronargs);
1054 /* Ignore this function if its proargnames is null */
1055 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1060 /* OK, let's extract the argument names and types */
1061 pronallargs = get_func_arg_info(proctup,
1062 &p_argtypes, &p_argnames, &p_argmodes);
1063 Assert(p_argnames != NULL);
1065 /* initialize state for matching */
1066 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1067 memset(arggiven, false, pronargs * sizeof(bool));
1069 /* there are numposargs positional args before the named args */
1070 for (ap = 0; ap < numposargs; ap++)
1072 (*argnumbers)[ap] = ap;
1073 arggiven[ap] = true;
1076 /* now examine the named args */
1077 foreach(lc, argnames)
1079 char *argname = (char *) lfirst(lc);
1085 for (i = 0; i < pronallargs; i++)
1087 /* consider only input parameters */
1089 (p_argmodes[i] != FUNC_PARAM_IN &&
1090 p_argmodes[i] != FUNC_PARAM_INOUT &&
1091 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1093 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1095 /* fail if argname matches a positional argument */
1098 arggiven[pp] = true;
1099 (*argnumbers)[ap] = pp;
1103 /* increase pp only for input parameters */
1106 /* if name isn't in proargnames, fail */
1112 Assert(ap == nargs); /* processed all actual parameters */
1114 /* Check for default arguments */
1115 if (nargs < pronargs)
1117 int first_arg_with_default = pronargs - procform->pronargdefaults;
1119 for (pp = numposargs; pp < pronargs; pp++)
1123 /* fail if arg not given and no default available */
1124 if (pp < first_arg_with_default)
1126 (*argnumbers)[ap++] = pp;
1130 Assert(ap == pronargs); /* processed all function parameters */
1137 * Determine whether a function (identified by OID) is visible in the
1138 * current search path. Visible means "would be found by searching
1139 * for the unqualified function name with exact argument matches".
1142 FunctionIsVisible(Oid funcid)
1145 Form_pg_proc procform;
1149 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1150 if (!HeapTupleIsValid(proctup))
1151 elog(ERROR, "cache lookup failed for function %u", funcid);
1152 procform = (Form_pg_proc) GETSTRUCT(proctup);
1154 recomputeNamespacePath();
1157 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1158 * the system namespace are surely in the path and so we needn't even do
1159 * list_member_oid() for them.
1161 pronamespace = procform->pronamespace;
1162 if (pronamespace != PG_CATALOG_NAMESPACE &&
1163 !list_member_oid(activeSearchPath, pronamespace))
1168 * If it is in the path, it might still not be visible; it could be
1169 * hidden by another proc of the same name and arguments earlier in
1170 * the path. So we must do a slow check to see if this is the same
1171 * proc that would be found by FuncnameGetCandidates.
1173 char *proname = NameStr(procform->proname);
1174 int nargs = procform->pronargs;
1175 FuncCandidateList clist;
1179 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1180 nargs, NIL, false, false);
1182 for (; clist; clist = clist->next)
1184 if (memcmp(clist->args, procform->proargtypes.values,
1185 nargs * sizeof(Oid)) == 0)
1187 /* Found the expected entry; is it the right proc? */
1188 visible = (clist->oid == funcid);
1194 ReleaseSysCache(proctup);
1202 * Given a possibly-qualified operator name and exact input datatypes,
1203 * look up the operator. Returns InvalidOid if not found.
1205 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1208 * If the operator name is not schema-qualified, it is sought in the current
1209 * namespace search path.
1212 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1219 /* deconstruct the name list */
1220 DeconstructQualifiedName(names, &schemaname, &opername);
1224 /* search only in exact schema given */
1228 namespaceId = LookupExplicitNamespace(schemaname);
1229 opertup = SearchSysCache4(OPERNAMENSP,
1230 CStringGetDatum(opername),
1231 ObjectIdGetDatum(oprleft),
1232 ObjectIdGetDatum(oprright),
1233 ObjectIdGetDatum(namespaceId));
1234 if (HeapTupleIsValid(opertup))
1236 Oid result = HeapTupleGetOid(opertup);
1238 ReleaseSysCache(opertup);
1244 /* Search syscache by name and argument types */
1245 catlist = SearchSysCacheList3(OPERNAMENSP,
1246 CStringGetDatum(opername),
1247 ObjectIdGetDatum(oprleft),
1248 ObjectIdGetDatum(oprright));
1250 if (catlist->n_members == 0)
1252 /* no hope, fall out early */
1253 ReleaseSysCacheList(catlist);
1258 * We have to find the list member that is first in the search path, if
1259 * there's more than one. This doubly-nested loop looks ugly, but in
1260 * practice there should usually be few catlist members.
1262 recomputeNamespacePath();
1264 foreach(l, activeSearchPath)
1266 Oid namespaceId = lfirst_oid(l);
1269 if (namespaceId == myTempNamespace)
1270 continue; /* do not look in temp namespace */
1272 for (i = 0; i < catlist->n_members; i++)
1274 HeapTuple opertup = &catlist->members[i]->tuple;
1275 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1277 if (operform->oprnamespace == namespaceId)
1279 Oid result = HeapTupleGetOid(opertup);
1281 ReleaseSysCacheList(catlist);
1287 ReleaseSysCacheList(catlist);
1292 * OpernameGetCandidates
1293 * Given a possibly-qualified operator name and operator kind,
1294 * retrieve a list of the possible matches.
1296 * If oprkind is '\0', we return all operators matching the given name,
1297 * regardless of arguments.
1299 * We search a single namespace if the operator name is qualified, else
1300 * all namespaces in the search path. The return list will never contain
1301 * multiple entries with identical argument lists --- in the multiple-
1302 * namespace case, we arrange for entries in earlier namespaces to mask
1303 * identical entries in later namespaces.
1305 * The returned items always have two args[] entries --- one or the other
1306 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1309 OpernameGetCandidates(List *names, char oprkind)
1311 FuncCandidateList resultList = NULL;
1312 char *resultSpace = NULL;
1320 /* deconstruct the name list */
1321 DeconstructQualifiedName(names, &schemaname, &opername);
1325 /* use exact schema given */
1326 namespaceId = LookupExplicitNamespace(schemaname);
1330 /* flag to indicate we need namespace search */
1331 namespaceId = InvalidOid;
1332 recomputeNamespacePath();
1335 /* Search syscache by name only */
1336 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1339 * In typical scenarios, most if not all of the operators found by the
1340 * catcache search will end up getting returned; and there can be quite a
1341 * few, for common operator names such as '=' or '+'. To reduce the time
1342 * spent in palloc, we allocate the result space as an array large enough
1343 * to hold all the operators. The original coding of this routine did a
1344 * separate palloc for each operator, but profiling revealed that the
1345 * pallocs used an unreasonably large fraction of parsing time.
1347 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1349 if (catlist->n_members > 0)
1350 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1352 for (i = 0; i < catlist->n_members; i++)
1354 HeapTuple opertup = &catlist->members[i]->tuple;
1355 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1357 FuncCandidateList newResult;
1359 /* Ignore operators of wrong kind, if specific kind requested */
1360 if (oprkind && operform->oprkind != oprkind)
1363 if (OidIsValid(namespaceId))
1365 /* Consider only opers in specified namespace */
1366 if (operform->oprnamespace != namespaceId)
1368 /* No need to check args, they must all be different */
1373 * Consider only opers that are in the search path and are not in
1374 * the temp namespace.
1378 foreach(nsp, activeSearchPath)
1380 if (operform->oprnamespace == lfirst_oid(nsp) &&
1381 operform->oprnamespace != myTempNamespace)
1386 continue; /* oper is not in search path */
1389 * Okay, it's in the search path, but does it have the same
1390 * arguments as something we already accepted? If so, keep only
1391 * the one that appears earlier in the search path.
1393 * If we have an ordered list from SearchSysCacheList (the normal
1394 * case), then any conflicting oper must immediately adjoin this
1395 * one in the list, so we only need to look at the newest result
1396 * item. If we have an unordered list, we have to scan the whole
1401 FuncCandidateList prevResult;
1403 if (catlist->ordered)
1405 if (operform->oprleft == resultList->args[0] &&
1406 operform->oprright == resultList->args[1])
1407 prevResult = resultList;
1413 for (prevResult = resultList;
1415 prevResult = prevResult->next)
1417 if (operform->oprleft == prevResult->args[0] &&
1418 operform->oprright == prevResult->args[1])
1424 /* We have a match with a previous result */
1425 Assert(pathpos != prevResult->pathpos);
1426 if (pathpos > prevResult->pathpos)
1427 continue; /* keep previous result */
1428 /* replace previous result */
1429 prevResult->pathpos = pathpos;
1430 prevResult->oid = HeapTupleGetOid(opertup);
1431 continue; /* args are same, of course */
1437 * Okay to add it to result list
1439 newResult = (FuncCandidateList) (resultSpace + nextResult);
1440 nextResult += SPACE_PER_OP;
1442 newResult->pathpos = pathpos;
1443 newResult->oid = HeapTupleGetOid(opertup);
1444 newResult->nargs = 2;
1445 newResult->nvargs = 0;
1446 newResult->ndargs = 0;
1447 newResult->argnumbers = NULL;
1448 newResult->args[0] = operform->oprleft;
1449 newResult->args[1] = operform->oprright;
1450 newResult->next = resultList;
1451 resultList = newResult;
1454 ReleaseSysCacheList(catlist);
1461 * Determine whether an operator (identified by OID) is visible in the
1462 * current search path. Visible means "would be found by searching
1463 * for the unqualified operator name with exact argument matches".
1466 OperatorIsVisible(Oid oprid)
1469 Form_pg_operator oprform;
1473 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1474 if (!HeapTupleIsValid(oprtup))
1475 elog(ERROR, "cache lookup failed for operator %u", oprid);
1476 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1478 recomputeNamespacePath();
1481 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1482 * the system namespace are surely in the path and so we needn't even do
1483 * list_member_oid() for them.
1485 oprnamespace = oprform->oprnamespace;
1486 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1487 !list_member_oid(activeSearchPath, oprnamespace))
1492 * If it is in the path, it might still not be visible; it could be
1493 * hidden by another operator of the same name and arguments earlier
1494 * in the path. So we must do a slow check to see if this is the same
1495 * operator that would be found by OpernameGetOprId.
1497 char *oprname = NameStr(oprform->oprname);
1499 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1500 oprform->oprleft, oprform->oprright)
1504 ReleaseSysCache(oprtup);
1511 * OpclassnameGetOpcid
1512 * Try to resolve an unqualified index opclass name.
1513 * Returns OID if opclass found in search path, else InvalidOid.
1515 * This is essentially the same as TypenameGetTypid, but we have to have
1516 * an extra argument for the index AM OID.
1519 OpclassnameGetOpcid(Oid amid, const char *opcname)
1524 recomputeNamespacePath();
1526 foreach(l, activeSearchPath)
1528 Oid namespaceId = lfirst_oid(l);
1530 if (namespaceId == myTempNamespace)
1531 continue; /* do not look in temp namespace */
1533 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1534 ObjectIdGetDatum(amid),
1535 PointerGetDatum(opcname),
1536 ObjectIdGetDatum(namespaceId));
1537 if (OidIsValid(opcid))
1541 /* Not found in path */
1547 * Determine whether an opclass (identified by OID) is visible in the
1548 * current search path. Visible means "would be found by searching
1549 * for the unqualified opclass name".
1552 OpclassIsVisible(Oid opcid)
1555 Form_pg_opclass opcform;
1559 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1560 if (!HeapTupleIsValid(opctup))
1561 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1562 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1564 recomputeNamespacePath();
1567 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1568 * the system namespace are surely in the path and so we needn't even do
1569 * list_member_oid() for them.
1571 opcnamespace = opcform->opcnamespace;
1572 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1573 !list_member_oid(activeSearchPath, opcnamespace))
1578 * If it is in the path, it might still not be visible; it could be
1579 * hidden by another opclass of the same name earlier in the path. So
1580 * we must do a slow check to see if this opclass would be found by
1581 * OpclassnameGetOpcid.
1583 char *opcname = NameStr(opcform->opcname);
1585 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1588 ReleaseSysCache(opctup);
1594 * OpfamilynameGetOpfid
1595 * Try to resolve an unqualified index opfamily name.
1596 * Returns OID if opfamily found in search path, else InvalidOid.
1598 * This is essentially the same as TypenameGetTypid, but we have to have
1599 * an extra argument for the index AM OID.
1602 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1607 recomputeNamespacePath();
1609 foreach(l, activeSearchPath)
1611 Oid namespaceId = lfirst_oid(l);
1613 if (namespaceId == myTempNamespace)
1614 continue; /* do not look in temp namespace */
1616 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1617 ObjectIdGetDatum(amid),
1618 PointerGetDatum(opfname),
1619 ObjectIdGetDatum(namespaceId));
1620 if (OidIsValid(opfid))
1624 /* Not found in path */
1630 * Determine whether an opfamily (identified by OID) is visible in the
1631 * current search path. Visible means "would be found by searching
1632 * for the unqualified opfamily name".
1635 OpfamilyIsVisible(Oid opfid)
1638 Form_pg_opfamily opfform;
1642 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1643 if (!HeapTupleIsValid(opftup))
1644 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1645 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1647 recomputeNamespacePath();
1650 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1651 * the system namespace are surely in the path and so we needn't even do
1652 * list_member_oid() for them.
1654 opfnamespace = opfform->opfnamespace;
1655 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1656 !list_member_oid(activeSearchPath, opfnamespace))
1661 * If it is in the path, it might still not be visible; it could be
1662 * hidden by another opfamily of the same name earlier in the path. So
1663 * we must do a slow check to see if this opfamily would be found by
1664 * OpfamilynameGetOpfid.
1666 char *opfname = NameStr(opfform->opfname);
1668 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1671 ReleaseSysCache(opftup);
1677 * CollationGetCollid
1678 * Try to resolve an unqualified collation name.
1679 * Returns OID if collation found in search path, else InvalidOid.
1682 CollationGetCollid(const char *collname)
1684 int32 dbencoding = GetDatabaseEncoding();
1687 recomputeNamespacePath();
1689 foreach(l, activeSearchPath)
1691 Oid namespaceId = lfirst_oid(l);
1694 if (namespaceId == myTempNamespace)
1695 continue; /* do not look in temp namespace */
1697 /* Check for database-encoding-specific entry */
1698 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1699 PointerGetDatum(collname),
1700 Int32GetDatum(dbencoding),
1701 ObjectIdGetDatum(namespaceId));
1702 if (OidIsValid(collid))
1705 /* Check for any-encoding entry */
1706 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1707 PointerGetDatum(collname),
1709 ObjectIdGetDatum(namespaceId));
1710 if (OidIsValid(collid))
1714 /* Not found in path */
1719 * CollationIsVisible
1720 * Determine whether a collation (identified by OID) is visible in the
1721 * current search path. Visible means "would be found by searching
1722 * for the unqualified collation name".
1725 CollationIsVisible(Oid collid)
1728 Form_pg_collation collform;
1732 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1733 if (!HeapTupleIsValid(colltup))
1734 elog(ERROR, "cache lookup failed for collation %u", collid);
1735 collform = (Form_pg_collation) GETSTRUCT(colltup);
1737 recomputeNamespacePath();
1740 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1741 * the system namespace are surely in the path and so we needn't even do
1742 * list_member_oid() for them.
1744 collnamespace = collform->collnamespace;
1745 if (collnamespace != PG_CATALOG_NAMESPACE &&
1746 !list_member_oid(activeSearchPath, collnamespace))
1751 * If it is in the path, it might still not be visible; it could be
1752 * hidden by another conversion of the same name earlier in the path.
1753 * So we must do a slow check to see if this conversion would be found
1754 * by CollationGetCollid.
1756 char *collname = NameStr(collform->collname);
1758 visible = (CollationGetCollid(collname) == collid);
1761 ReleaseSysCache(colltup);
1768 * ConversionGetConid
1769 * Try to resolve an unqualified conversion name.
1770 * Returns OID if conversion found in search path, else InvalidOid.
1772 * This is essentially the same as RelnameGetRelid.
1775 ConversionGetConid(const char *conname)
1780 recomputeNamespacePath();
1782 foreach(l, activeSearchPath)
1784 Oid namespaceId = lfirst_oid(l);
1786 if (namespaceId == myTempNamespace)
1787 continue; /* do not look in temp namespace */
1789 conid = GetSysCacheOid2(CONNAMENSP,
1790 PointerGetDatum(conname),
1791 ObjectIdGetDatum(namespaceId));
1792 if (OidIsValid(conid))
1796 /* Not found in path */
1801 * ConversionIsVisible
1802 * Determine whether a conversion (identified by OID) is visible in the
1803 * current search path. Visible means "would be found by searching
1804 * for the unqualified conversion name".
1807 ConversionIsVisible(Oid conid)
1810 Form_pg_conversion conform;
1814 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1815 if (!HeapTupleIsValid(contup))
1816 elog(ERROR, "cache lookup failed for conversion %u", conid);
1817 conform = (Form_pg_conversion) GETSTRUCT(contup);
1819 recomputeNamespacePath();
1822 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1823 * the system namespace are surely in the path and so we needn't even do
1824 * list_member_oid() for them.
1826 connamespace = conform->connamespace;
1827 if (connamespace != PG_CATALOG_NAMESPACE &&
1828 !list_member_oid(activeSearchPath, connamespace))
1833 * If it is in the path, it might still not be visible; it could be
1834 * hidden by another conversion of the same name earlier in the path.
1835 * So we must do a slow check to see if this conversion would be found
1836 * by ConversionGetConid.
1838 char *conname = NameStr(conform->conname);
1840 visible = (ConversionGetConid(conname) == conid);
1843 ReleaseSysCache(contup);
1849 * get_ts_parser_oid - find a TS parser by possibly qualified name
1851 * If not found, returns InvalidOid if missing_ok, else throws error
1854 get_ts_parser_oid(List *names, bool missing_ok)
1859 Oid prsoid = InvalidOid;
1862 /* deconstruct the name list */
1863 DeconstructQualifiedName(names, &schemaname, &parser_name);
1867 /* use exact schema given */
1868 namespaceId = LookupExplicitNamespace(schemaname);
1869 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1870 PointerGetDatum(parser_name),
1871 ObjectIdGetDatum(namespaceId));
1875 /* search for it in search path */
1876 recomputeNamespacePath();
1878 foreach(l, activeSearchPath)
1880 namespaceId = lfirst_oid(l);
1882 if (namespaceId == myTempNamespace)
1883 continue; /* do not look in temp namespace */
1885 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1886 PointerGetDatum(parser_name),
1887 ObjectIdGetDatum(namespaceId));
1888 if (OidIsValid(prsoid))
1893 if (!OidIsValid(prsoid) && !missing_ok)
1895 (errcode(ERRCODE_UNDEFINED_OBJECT),
1896 errmsg("text search parser \"%s\" does not exist",
1897 NameListToString(names))));
1904 * Determine whether a parser (identified by OID) is visible in the
1905 * current search path. Visible means "would be found by searching
1906 * for the unqualified parser name".
1909 TSParserIsVisible(Oid prsId)
1912 Form_pg_ts_parser form;
1916 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1917 if (!HeapTupleIsValid(tup))
1918 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1919 form = (Form_pg_ts_parser) GETSTRUCT(tup);
1921 recomputeNamespacePath();
1924 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1925 * the system namespace are surely in the path and so we needn't even do
1926 * list_member_oid() for them.
1928 namespace = form->prsnamespace;
1929 if (namespace != PG_CATALOG_NAMESPACE &&
1930 !list_member_oid(activeSearchPath, namespace))
1935 * If it is in the path, it might still not be visible; it could be
1936 * hidden by another parser of the same name earlier in the path. So
1937 * we must do a slow check for conflicting parsers.
1939 char *name = NameStr(form->prsname);
1943 foreach(l, activeSearchPath)
1945 Oid namespaceId = lfirst_oid(l);
1947 if (namespaceId == myTempNamespace)
1948 continue; /* do not look in temp namespace */
1950 if (namespaceId == namespace)
1952 /* Found it first in path */
1956 if (SearchSysCacheExists2(TSPARSERNAMENSP,
1957 PointerGetDatum(name),
1958 ObjectIdGetDatum(namespaceId)))
1960 /* Found something else first in path */
1966 ReleaseSysCache(tup);
1972 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
1974 * If not found, returns InvalidOid if failOK, else throws error
1977 get_ts_dict_oid(List *names, bool missing_ok)
1982 Oid dictoid = InvalidOid;
1985 /* deconstruct the name list */
1986 DeconstructQualifiedName(names, &schemaname, &dict_name);
1990 /* use exact schema given */
1991 namespaceId = LookupExplicitNamespace(schemaname);
1992 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1993 PointerGetDatum(dict_name),
1994 ObjectIdGetDatum(namespaceId));
1998 /* search for it in search path */
1999 recomputeNamespacePath();
2001 foreach(l, activeSearchPath)
2003 namespaceId = lfirst_oid(l);
2005 if (namespaceId == myTempNamespace)
2006 continue; /* do not look in temp namespace */
2008 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2009 PointerGetDatum(dict_name),
2010 ObjectIdGetDatum(namespaceId));
2011 if (OidIsValid(dictoid))
2016 if (!OidIsValid(dictoid) && !missing_ok)
2018 (errcode(ERRCODE_UNDEFINED_OBJECT),
2019 errmsg("text search dictionary \"%s\" does not exist",
2020 NameListToString(names))));
2026 * TSDictionaryIsVisible
2027 * Determine whether a dictionary (identified by OID) is visible in the
2028 * current search path. Visible means "would be found by searching
2029 * for the unqualified dictionary name".
2032 TSDictionaryIsVisible(Oid dictId)
2035 Form_pg_ts_dict form;
2039 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2040 if (!HeapTupleIsValid(tup))
2041 elog(ERROR, "cache lookup failed for text search dictionary %u",
2043 form = (Form_pg_ts_dict) GETSTRUCT(tup);
2045 recomputeNamespacePath();
2048 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2049 * the system namespace are surely in the path and so we needn't even do
2050 * list_member_oid() for them.
2052 namespace = form->dictnamespace;
2053 if (namespace != PG_CATALOG_NAMESPACE &&
2054 !list_member_oid(activeSearchPath, namespace))
2059 * If it is in the path, it might still not be visible; it could be
2060 * hidden by another dictionary of the same name earlier in the path.
2061 * So we must do a slow check for conflicting dictionaries.
2063 char *name = NameStr(form->dictname);
2067 foreach(l, activeSearchPath)
2069 Oid namespaceId = lfirst_oid(l);
2071 if (namespaceId == myTempNamespace)
2072 continue; /* do not look in temp namespace */
2074 if (namespaceId == namespace)
2076 /* Found it first in path */
2080 if (SearchSysCacheExists2(TSDICTNAMENSP,
2081 PointerGetDatum(name),
2082 ObjectIdGetDatum(namespaceId)))
2084 /* Found something else first in path */
2090 ReleaseSysCache(tup);
2096 * get_ts_template_oid - find a TS template by possibly qualified name
2098 * If not found, returns InvalidOid if missing_ok, else throws error
2101 get_ts_template_oid(List *names, bool missing_ok)
2104 char *template_name;
2106 Oid tmploid = InvalidOid;
2109 /* deconstruct the name list */
2110 DeconstructQualifiedName(names, &schemaname, &template_name);
2114 /* use exact schema given */
2115 namespaceId = LookupExplicitNamespace(schemaname);
2116 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2117 PointerGetDatum(template_name),
2118 ObjectIdGetDatum(namespaceId));
2122 /* search for it in search path */
2123 recomputeNamespacePath();
2125 foreach(l, activeSearchPath)
2127 namespaceId = lfirst_oid(l);
2129 if (namespaceId == myTempNamespace)
2130 continue; /* do not look in temp namespace */
2132 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2133 PointerGetDatum(template_name),
2134 ObjectIdGetDatum(namespaceId));
2135 if (OidIsValid(tmploid))
2140 if (!OidIsValid(tmploid) && !missing_ok)
2142 (errcode(ERRCODE_UNDEFINED_OBJECT),
2143 errmsg("text search template \"%s\" does not exist",
2144 NameListToString(names))));
2150 * TSTemplateIsVisible
2151 * Determine whether a template (identified by OID) is visible in the
2152 * current search path. Visible means "would be found by searching
2153 * for the unqualified template name".
2156 TSTemplateIsVisible(Oid tmplId)
2159 Form_pg_ts_template form;
2163 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2164 if (!HeapTupleIsValid(tup))
2165 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2166 form = (Form_pg_ts_template) GETSTRUCT(tup);
2168 recomputeNamespacePath();
2171 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2172 * the system namespace are surely in the path and so we needn't even do
2173 * list_member_oid() for them.
2175 namespace = form->tmplnamespace;
2176 if (namespace != PG_CATALOG_NAMESPACE &&
2177 !list_member_oid(activeSearchPath, namespace))
2182 * If it is in the path, it might still not be visible; it could be
2183 * hidden by another template of the same name earlier in the path. So
2184 * we must do a slow check for conflicting templates.
2186 char *name = NameStr(form->tmplname);
2190 foreach(l, activeSearchPath)
2192 Oid namespaceId = lfirst_oid(l);
2194 if (namespaceId == myTempNamespace)
2195 continue; /* do not look in temp namespace */
2197 if (namespaceId == namespace)
2199 /* Found it first in path */
2203 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2204 PointerGetDatum(name),
2205 ObjectIdGetDatum(namespaceId)))
2207 /* Found something else first in path */
2213 ReleaseSysCache(tup);
2219 * get_ts_config_oid - find a TS config by possibly qualified name
2221 * If not found, returns InvalidOid if missing_ok, else throws error
2224 get_ts_config_oid(List *names, bool missing_ok)
2229 Oid cfgoid = InvalidOid;
2232 /* deconstruct the name list */
2233 DeconstructQualifiedName(names, &schemaname, &config_name);
2237 /* use exact schema given */
2238 namespaceId = LookupExplicitNamespace(schemaname);
2239 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2240 PointerGetDatum(config_name),
2241 ObjectIdGetDatum(namespaceId));
2245 /* search for it in search path */
2246 recomputeNamespacePath();
2248 foreach(l, activeSearchPath)
2250 namespaceId = lfirst_oid(l);
2252 if (namespaceId == myTempNamespace)
2253 continue; /* do not look in temp namespace */
2255 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2256 PointerGetDatum(config_name),
2257 ObjectIdGetDatum(namespaceId));
2258 if (OidIsValid(cfgoid))
2263 if (!OidIsValid(cfgoid) && !missing_ok)
2265 (errcode(ERRCODE_UNDEFINED_OBJECT),
2266 errmsg("text search configuration \"%s\" does not exist",
2267 NameListToString(names))));
2274 * Determine whether a text search configuration (identified by OID)
2275 * is visible in the current search path. Visible means "would be found
2276 * by searching for the unqualified text search configuration name".
2279 TSConfigIsVisible(Oid cfgid)
2282 Form_pg_ts_config form;
2286 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2287 if (!HeapTupleIsValid(tup))
2288 elog(ERROR, "cache lookup failed for text search configuration %u",
2290 form = (Form_pg_ts_config) GETSTRUCT(tup);
2292 recomputeNamespacePath();
2295 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2296 * the system namespace are surely in the path and so we needn't even do
2297 * list_member_oid() for them.
2299 namespace = form->cfgnamespace;
2300 if (namespace != PG_CATALOG_NAMESPACE &&
2301 !list_member_oid(activeSearchPath, namespace))
2306 * If it is in the path, it might still not be visible; it could be
2307 * hidden by another configuration of the same name earlier in the
2308 * path. So we must do a slow check for conflicting configurations.
2310 char *name = NameStr(form->cfgname);
2314 foreach(l, activeSearchPath)
2316 Oid namespaceId = lfirst_oid(l);
2318 if (namespaceId == myTempNamespace)
2319 continue; /* do not look in temp namespace */
2321 if (namespaceId == namespace)
2323 /* Found it first in path */
2327 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2328 PointerGetDatum(name),
2329 ObjectIdGetDatum(namespaceId)))
2331 /* Found something else first in path */
2337 ReleaseSysCache(tup);
2344 * DeconstructQualifiedName
2345 * Given a possibly-qualified name expressed as a list of String nodes,
2346 * extract the schema name and object name.
2348 * *nspname_p is set to NULL if there is no explicit schema name.
2351 DeconstructQualifiedName(List *names,
2356 char *schemaname = NULL;
2357 char *objname = NULL;
2359 switch (list_length(names))
2362 objname = strVal(linitial(names));
2365 schemaname = strVal(linitial(names));
2366 objname = strVal(lsecond(names));
2369 catalogname = strVal(linitial(names));
2370 schemaname = strVal(lsecond(names));
2371 objname = strVal(lthird(names));
2374 * We check the catalog name and then ignore it.
2376 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2378 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2379 errmsg("cross-database references are not implemented: %s",
2380 NameListToString(names))));
2384 (errcode(ERRCODE_SYNTAX_ERROR),
2385 errmsg("improper qualified name (too many dotted names): %s",
2386 NameListToString(names))));
2390 *nspname_p = schemaname;
2391 *objname_p = objname;
2395 * LookupNamespaceNoError
2396 * Look up a schema name.
2398 * Returns the namespace OID, or InvalidOid if not found.
2400 * Note this does NOT perform any permissions check --- callers are
2401 * responsible for being sure that an appropriate check is made.
2402 * In the majority of cases LookupExplicitNamespace is preferable.
2405 LookupNamespaceNoError(const char *nspname)
2407 /* check for pg_temp alias */
2408 if (strcmp(nspname, "pg_temp") == 0)
2410 if (OidIsValid(myTempNamespace))
2411 return myTempNamespace;
2414 * Since this is used only for looking up existing objects, there is
2415 * no point in trying to initialize the temp namespace here; and doing
2416 * so might create problems for some callers. Just report "not found".
2421 return get_namespace_oid(nspname, true);
2425 * LookupExplicitNamespace
2426 * Process an explicitly-specified schema name: look up the schema
2427 * and verify we have USAGE (lookup) rights in it.
2429 * Returns the namespace OID. Raises ereport if any problem.
2432 LookupExplicitNamespace(const char *nspname)
2435 AclResult aclresult;
2437 /* check for pg_temp alias */
2438 if (strcmp(nspname, "pg_temp") == 0)
2440 if (OidIsValid(myTempNamespace))
2441 return myTempNamespace;
2444 * Since this is used only for looking up existing objects, there is
2445 * no point in trying to initialize the temp namespace here; and doing
2446 * so might create problems for some callers. Just fall through and
2447 * give the "does not exist" error.
2451 namespaceId = get_namespace_oid(nspname, false);
2453 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2454 if (aclresult != ACLCHECK_OK)
2455 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2462 * LookupCreationNamespace
2463 * Look up the schema and verify we have CREATE rights on it.
2465 * This is just like LookupExplicitNamespace except for the different
2466 * permission check, and that we are willing to create pg_temp if needed.
2468 * Note: calling this may result in a CommandCounterIncrement operation,
2469 * if we have to create or clean out the temp namespace.
2472 LookupCreationNamespace(const char *nspname)
2475 AclResult aclresult;
2477 /* check for pg_temp alias */
2478 if (strcmp(nspname, "pg_temp") == 0)
2480 /* Initialize temp namespace if first time through */
2481 if (!OidIsValid(myTempNamespace))
2482 InitTempTableNamespace();
2483 return myTempNamespace;
2486 namespaceId = get_namespace_oid(nspname, false);
2488 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2489 if (aclresult != ACLCHECK_OK)
2490 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2497 * Common checks on switching namespaces.
2499 * We complain if (1) the old and new namespaces are the same, (2) either the
2500 * old or new namespaces is a temporary schema (or temporary toast schema), or
2501 * (3) either the old or new namespaces is the TOAST schema.
2504 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2506 if (oldNspOid == nspOid)
2508 (classid == RelationRelationId ?
2509 errcode(ERRCODE_DUPLICATE_TABLE) :
2510 classid == ProcedureRelationId ?
2511 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2512 errcode(ERRCODE_DUPLICATE_OBJECT),
2513 errmsg("%s is already in schema \"%s\"",
2514 getObjectDescriptionOids(classid, objid),
2515 get_namespace_name(nspOid))));
2517 /* disallow renaming into or out of temp schemas */
2518 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2520 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2521 errmsg("cannot move objects into or out of temporary schemas")));
2523 /* same for TOAST schema */
2524 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2526 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2527 errmsg("cannot move objects into or out of TOAST schema")));
2531 * QualifiedNameGetCreationNamespace
2532 * Given a possibly-qualified name for an object (in List-of-Values
2533 * format), determine what namespace the object should be created in.
2534 * Also extract and return the object name (last component of list).
2536 * Note: this does not apply any permissions check. Callers must check
2537 * for CREATE rights on the selected namespace when appropriate.
2539 * Note: calling this may result in a CommandCounterIncrement operation,
2540 * if we have to create or clean out the temp namespace.
2543 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2548 /* deconstruct the name list */
2549 DeconstructQualifiedName(names, &schemaname, objname_p);
2553 /* check for pg_temp alias */
2554 if (strcmp(schemaname, "pg_temp") == 0)
2556 /* Initialize temp namespace if first time through */
2557 if (!OidIsValid(myTempNamespace))
2558 InitTempTableNamespace();
2559 return myTempNamespace;
2561 /* use exact schema given */
2562 namespaceId = get_namespace_oid(schemaname, false);
2563 /* we do not check for USAGE rights here! */
2567 /* use the default creation namespace */
2568 recomputeNamespacePath();
2569 if (activeTempCreationPending)
2571 /* Need to initialize temp namespace */
2572 InitTempTableNamespace();
2573 return myTempNamespace;
2575 namespaceId = activeCreationNamespace;
2576 if (!OidIsValid(namespaceId))
2578 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2579 errmsg("no schema has been selected to create in")));
2586 * get_namespace_oid - given a namespace name, look up the OID
2588 * If missing_ok is false, throw an error if namespace name not found. If
2589 * true, just return InvalidOid.
2592 get_namespace_oid(const char *nspname, bool missing_ok)
2596 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2597 if (!OidIsValid(oid) && !missing_ok)
2599 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2600 errmsg("schema \"%s\" does not exist", nspname)));
2606 * makeRangeVarFromNameList
2607 * Utility routine to convert a qualified-name list into RangeVar form.
2610 makeRangeVarFromNameList(List *names)
2612 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2614 switch (list_length(names))
2617 rel->relname = strVal(linitial(names));
2620 rel->schemaname = strVal(linitial(names));
2621 rel->relname = strVal(lsecond(names));
2624 rel->catalogname = strVal(linitial(names));
2625 rel->schemaname = strVal(lsecond(names));
2626 rel->relname = strVal(lthird(names));
2630 (errcode(ERRCODE_SYNTAX_ERROR),
2631 errmsg("improper relation name (too many dotted names): %s",
2632 NameListToString(names))));
2641 * Utility routine to convert a qualified-name list into a string.
2643 * This is used primarily to form error messages, and so we do not quote
2644 * the list elements, for the sake of legibility.
2646 * In most scenarios the list elements should always be Value strings,
2647 * but we also allow A_Star for the convenience of ColumnRef processing.
2650 NameListToString(List *names)
2652 StringInfoData string;
2655 initStringInfo(&string);
2659 Node *name = (Node *) lfirst(l);
2661 if (l != list_head(names))
2662 appendStringInfoChar(&string, '.');
2664 if (IsA(name, String))
2665 appendStringInfoString(&string, strVal(name));
2666 else if (IsA(name, A_Star))
2667 appendStringInfoString(&string, "*");
2669 elog(ERROR, "unexpected node type in name list: %d",
2670 (int) nodeTag(name));
2677 * NameListToQuotedString
2678 * Utility routine to convert a qualified-name list into a string.
2680 * Same as above except that names will be double-quoted where necessary,
2681 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2684 NameListToQuotedString(List *names)
2686 StringInfoData string;
2689 initStringInfo(&string);
2693 if (l != list_head(names))
2694 appendStringInfoChar(&string, '.');
2695 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2702 * isTempNamespace - is the given namespace my temporary-table namespace?
2705 isTempNamespace(Oid namespaceId)
2707 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2713 * isTempToastNamespace - is the given namespace my temporary-toast-table
2717 isTempToastNamespace(Oid namespaceId)
2719 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2725 * isTempOrToastNamespace - is the given namespace my temporary-table
2726 * namespace or my temporary-toast-table namespace?
2729 isTempOrToastNamespace(Oid namespaceId)
2731 if (OidIsValid(myTempNamespace) &&
2732 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2738 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2739 * (either my own, or another backend's)? Temporary-toast-table namespaces
2740 * are included, too.
2743 isAnyTempNamespace(Oid namespaceId)
2748 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2749 nspname = get_namespace_name(namespaceId);
2751 return false; /* no such namespace? */
2752 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2753 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2759 * isOtherTempNamespace - is the given namespace some other backend's
2760 * temporary-table namespace (including temporary-toast-table namespaces)?
2762 * Note: for most purposes in the C code, this function is obsolete. Use
2763 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2766 isOtherTempNamespace(Oid namespaceId)
2768 /* If it's my own temp namespace, say "false" */
2769 if (isTempOrToastNamespace(namespaceId))
2771 /* Else, if it's any temp namespace, say "true" */
2772 return isAnyTempNamespace(namespaceId);
2776 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
2777 * namespace (either my own, or another backend's), return the BackendId
2778 * that owns it. Temporary-toast-table namespaces are included, too.
2779 * If it isn't a temp namespace, return InvalidBackendId.
2782 GetTempNamespaceBackendId(Oid namespaceId)
2787 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2788 nspname = get_namespace_name(namespaceId);
2790 return InvalidBackendId; /* no such namespace? */
2791 if (strncmp(nspname, "pg_temp_", 8) == 0)
2792 result = atoi(nspname + 8);
2793 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
2794 result = atoi(nspname + 14);
2796 result = InvalidBackendId;
2802 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
2803 * which must already be assigned. (This is only used when creating a toast
2804 * table for a temp table, so we must have already done InitTempTableNamespace)
2807 GetTempToastNamespace(void)
2809 Assert(OidIsValid(myTempToastNamespace));
2810 return myTempToastNamespace;
2815 * GetOverrideSearchPath - fetch current search path definition in form
2816 * used by PushOverrideSearchPath.
2818 * The result structure is allocated in the specified memory context
2819 * (which might or might not be equal to CurrentMemoryContext); but any
2820 * junk created by revalidation calculations will be in CurrentMemoryContext.
2822 OverrideSearchPath *
2823 GetOverrideSearchPath(MemoryContext context)
2825 OverrideSearchPath *result;
2827 MemoryContext oldcxt;
2829 recomputeNamespacePath();
2831 oldcxt = MemoryContextSwitchTo(context);
2833 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
2834 schemas = list_copy(activeSearchPath);
2835 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
2837 if (linitial_oid(schemas) == myTempNamespace)
2838 result->addTemp = true;
2841 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
2842 result->addCatalog = true;
2844 schemas = list_delete_first(schemas);
2846 result->schemas = schemas;
2848 MemoryContextSwitchTo(oldcxt);
2854 * PushOverrideSearchPath - temporarily override the search path
2856 * We allow nested overrides, hence the push/pop terminology. The GUC
2857 * search_path variable is ignored while an override is active.
2859 * It's possible that newpath->useTemp is set but there is no longer any
2860 * active temp namespace, if the path was saved during a transaction that
2861 * created a temp namespace and was later rolled back. In that case we just
2862 * ignore useTemp. A plausible alternative would be to create a new temp
2863 * namespace, but for existing callers that's not necessary because an empty
2864 * temp namespace wouldn't affect their results anyway.
2866 * It's also worth noting that other schemas listed in newpath might not
2867 * exist anymore either. We don't worry about this because OIDs that match
2868 * no existing namespace will simply not produce any hits during searches.
2871 PushOverrideSearchPath(OverrideSearchPath *newpath)
2873 OverrideStackEntry *entry;
2876 MemoryContext oldcxt;
2879 * Copy the list for safekeeping, and insert implicitly-searched
2880 * namespaces as needed. This code should track recomputeNamespacePath.
2882 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2884 oidlist = list_copy(newpath->schemas);
2887 * Remember the first member of the explicit list.
2890 firstNS = InvalidOid;
2892 firstNS = linitial_oid(oidlist);
2895 * Add any implicitly-searched namespaces to the list. Note these go on
2896 * the front, not the back; also notice that we do not check USAGE
2897 * permissions for these.
2899 if (newpath->addCatalog)
2900 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2902 if (newpath->addTemp && OidIsValid(myTempNamespace))
2903 oidlist = lcons_oid(myTempNamespace, oidlist);
2906 * Build the new stack entry, then insert it at the head of the list.
2908 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
2909 entry->searchPath = oidlist;
2910 entry->creationNamespace = firstNS;
2911 entry->nestLevel = GetCurrentTransactionNestLevel();
2913 overrideStack = lcons(entry, overrideStack);
2915 /* And make it active. */
2916 activeSearchPath = entry->searchPath;
2917 activeCreationNamespace = entry->creationNamespace;
2918 activeTempCreationPending = false; /* XXX is this OK? */
2920 MemoryContextSwitchTo(oldcxt);
2924 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
2926 * Any push during a (sub)transaction will be popped automatically at abort.
2927 * But it's caller error if a push isn't popped in normal control flow.
2930 PopOverrideSearchPath(void)
2932 OverrideStackEntry *entry;
2934 /* Sanity checks. */
2935 if (overrideStack == NIL)
2936 elog(ERROR, "bogus PopOverrideSearchPath call");
2937 entry = (OverrideStackEntry *) linitial(overrideStack);
2938 if (entry->nestLevel != GetCurrentTransactionNestLevel())
2939 elog(ERROR, "bogus PopOverrideSearchPath call");
2941 /* Pop the stack and free storage. */
2942 overrideStack = list_delete_first(overrideStack);
2943 list_free(entry->searchPath);
2946 /* Activate the next level down. */
2949 entry = (OverrideStackEntry *) linitial(overrideStack);
2950 activeSearchPath = entry->searchPath;
2951 activeCreationNamespace = entry->creationNamespace;
2952 activeTempCreationPending = false; /* XXX is this OK? */
2956 /* If not baseSearchPathValid, this is useless but harmless */
2957 activeSearchPath = baseSearchPath;
2958 activeCreationNamespace = baseCreationNamespace;
2959 activeTempCreationPending = baseTempCreationPending;
2965 * get_collation_oid - find a collation by possibly qualified name
2968 get_collation_oid(List *name, bool missing_ok)
2971 char *collation_name;
2972 int32 dbencoding = GetDatabaseEncoding();
2977 /* deconstruct the name list */
2978 DeconstructQualifiedName(name, &schemaname, &collation_name);
2982 /* use exact schema given */
2983 namespaceId = LookupExplicitNamespace(schemaname);
2985 /* first try for encoding-specific entry, then any-encoding */
2986 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
2987 PointerGetDatum(collation_name),
2988 Int32GetDatum(dbencoding),
2989 ObjectIdGetDatum(namespaceId));
2990 if (OidIsValid(colloid))
2992 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
2993 PointerGetDatum(collation_name),
2995 ObjectIdGetDatum(namespaceId));
2996 if (OidIsValid(colloid))
3001 /* search for it in search path */
3002 recomputeNamespacePath();
3004 foreach(l, activeSearchPath)
3006 namespaceId = lfirst_oid(l);
3008 if (namespaceId == myTempNamespace)
3009 continue; /* do not look in temp namespace */
3011 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3012 PointerGetDatum(collation_name),
3013 Int32GetDatum(dbencoding),
3014 ObjectIdGetDatum(namespaceId));
3015 if (OidIsValid(colloid))
3017 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3018 PointerGetDatum(collation_name),
3020 ObjectIdGetDatum(namespaceId));
3021 if (OidIsValid(colloid))
3026 /* Not found in path */
3029 (errcode(ERRCODE_UNDEFINED_OBJECT),
3030 errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3031 NameListToString(name), GetDatabaseEncodingName())));
3036 * get_conversion_oid - find a conversion by possibly qualified name
3039 get_conversion_oid(List *name, bool missing_ok)
3042 char *conversion_name;
3044 Oid conoid = InvalidOid;
3047 /* deconstruct the name list */
3048 DeconstructQualifiedName(name, &schemaname, &conversion_name);
3052 /* use exact schema given */
3053 namespaceId = LookupExplicitNamespace(schemaname);
3054 conoid = GetSysCacheOid2(CONNAMENSP,
3055 PointerGetDatum(conversion_name),
3056 ObjectIdGetDatum(namespaceId));
3060 /* search for it in search path */
3061 recomputeNamespacePath();
3063 foreach(l, activeSearchPath)
3065 namespaceId = lfirst_oid(l);
3067 if (namespaceId == myTempNamespace)
3068 continue; /* do not look in temp namespace */
3070 conoid = GetSysCacheOid2(CONNAMENSP,
3071 PointerGetDatum(conversion_name),
3072 ObjectIdGetDatum(namespaceId));
3073 if (OidIsValid(conoid))
3078 /* Not found in path */
3079 if (!OidIsValid(conoid) && !missing_ok)
3081 (errcode(ERRCODE_UNDEFINED_OBJECT),
3082 errmsg("conversion \"%s\" does not exist",
3083 NameListToString(name))));
3088 * FindDefaultConversionProc - find default encoding conversion proc
3091 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
3096 recomputeNamespacePath();
3098 foreach(l, activeSearchPath)
3100 Oid namespaceId = lfirst_oid(l);
3102 if (namespaceId == myTempNamespace)
3103 continue; /* do not look in temp namespace */
3105 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3106 if (OidIsValid(proc))
3110 /* Not found in path */
3115 * recomputeNamespacePath - recompute path derived variables if needed.
3118 recomputeNamespacePath(void)
3120 Oid roleid = GetUserId();
3128 MemoryContext oldcxt;
3130 /* Do nothing if an override search spec is active. */
3134 /* Do nothing if path is already valid. */
3135 if (baseSearchPathValid && namespaceUser == roleid)
3138 /* Need a modifiable copy of namespace_search_path string */
3139 rawname = pstrdup(namespace_search_path);
3141 /* Parse string into list of identifiers */
3142 if (!SplitIdentifierString(rawname, ',', &namelist))
3144 /* syntax error in name list */
3145 /* this should not happen if GUC checked check_search_path */
3146 elog(ERROR, "invalid list syntax");
3150 * Convert the list of names to a list of OIDs. If any names are not
3151 * recognizable or we don't have read access, just leave them out of the
3152 * list. (We can't raise an error, since the search_path setting has
3153 * already been accepted.) Don't make duplicate entries, either.
3156 temp_missing = false;
3157 foreach(l, namelist)
3159 char *curname = (char *) lfirst(l);
3162 if (strcmp(curname, "$user") == 0)
3164 /* $user --- substitute namespace matching user name, if any */
3167 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3168 if (HeapTupleIsValid(tuple))
3172 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3173 namespaceId = get_namespace_oid(rname, true);
3174 ReleaseSysCache(tuple);
3175 if (OidIsValid(namespaceId) &&
3176 !list_member_oid(oidlist, namespaceId) &&
3177 pg_namespace_aclcheck(namespaceId, roleid,
3178 ACL_USAGE) == ACLCHECK_OK)
3179 oidlist = lappend_oid(oidlist, namespaceId);
3182 else if (strcmp(curname, "pg_temp") == 0)
3184 /* pg_temp --- substitute temp namespace, if any */
3185 if (OidIsValid(myTempNamespace))
3187 if (!list_member_oid(oidlist, myTempNamespace))
3188 oidlist = lappend_oid(oidlist, myTempNamespace);
3192 /* If it ought to be the creation namespace, set flag */
3194 temp_missing = true;
3199 /* normal namespace reference */
3200 namespaceId = get_namespace_oid(curname, true);
3201 if (OidIsValid(namespaceId) &&
3202 !list_member_oid(oidlist, namespaceId) &&
3203 pg_namespace_aclcheck(namespaceId, roleid,
3204 ACL_USAGE) == ACLCHECK_OK)
3205 oidlist = lappend_oid(oidlist, namespaceId);
3210 * Remember the first member of the explicit list. (Note: this is
3211 * nominally wrong if temp_missing, but we need it anyway to distinguish
3212 * explicit from implicit mention of pg_catalog.)
3215 firstNS = InvalidOid;
3217 firstNS = linitial_oid(oidlist);
3220 * Add any implicitly-searched namespaces to the list. Note these go on
3221 * the front, not the back; also notice that we do not check USAGE
3222 * permissions for these.
3224 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3225 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3227 if (OidIsValid(myTempNamespace) &&
3228 !list_member_oid(oidlist, myTempNamespace))
3229 oidlist = lcons_oid(myTempNamespace, oidlist);
3232 * Now that we've successfully built the new list of namespace OIDs, save
3233 * it in permanent storage.
3235 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3236 newpath = list_copy(oidlist);
3237 MemoryContextSwitchTo(oldcxt);
3239 /* Now safe to assign to state variables. */
3240 list_free(baseSearchPath);
3241 baseSearchPath = newpath;
3242 baseCreationNamespace = firstNS;
3243 baseTempCreationPending = temp_missing;
3245 /* Mark the path valid. */
3246 baseSearchPathValid = true;
3247 namespaceUser = roleid;
3249 /* And make it active. */
3250 activeSearchPath = baseSearchPath;
3251 activeCreationNamespace = baseCreationNamespace;
3252 activeTempCreationPending = baseTempCreationPending;
3256 list_free(namelist);
3261 * InitTempTableNamespace
3262 * Initialize temp table namespace on first use in a particular backend
3265 InitTempTableNamespace(void)
3267 char namespaceName[NAMEDATALEN];
3271 Assert(!OidIsValid(myTempNamespace));
3274 * First, do permission check to see if we are authorized to make temp
3275 * tables. We use a nonstandard error message here since "databasename:
3276 * permission denied" might be a tad cryptic.
3278 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3279 * that's necessary since current user ID could change during the session.
3280 * But there's no need to make the namespace in the first place until a
3281 * temp table creation request is made by someone with appropriate rights.
3283 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3284 ACL_CREATE_TEMP) != ACLCHECK_OK)
3286 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3287 errmsg("permission denied to create temporary tables in database \"%s\"",
3288 get_database_name(MyDatabaseId))));
3291 * Do not allow a Hot Standby slave session to make temp tables. Aside
3292 * from problems with modifying the system catalogs, there is a naming
3293 * conflict: pg_temp_N belongs to the session with BackendId N on the
3294 * master, not to a slave session with the same BackendId. We should not
3295 * be able to get here anyway due to XactReadOnly checks, but let's just
3296 * make real sure. Note that this also backstops various operations that
3297 * allow XactReadOnly transactions to modify temp tables; they'd need
3298 * RecoveryInProgress checks if not for this.
3300 if (RecoveryInProgress())
3302 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3303 errmsg("cannot create temporary tables during recovery")));
3305 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3307 namespaceId = get_namespace_oid(namespaceName, true);
3308 if (!OidIsValid(namespaceId))
3311 * First use of this temp namespace in this database; create it. The
3312 * temp namespaces are always owned by the superuser. We leave their
3313 * permissions at default --- i.e., no access except to superuser ---
3314 * to ensure that unprivileged users can't peek at other backends'
3315 * temp tables. This works because the places that access the temp
3316 * namespace for my own backend skip permissions checks on it.
3318 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3319 /* Advance command counter to make namespace visible */
3320 CommandCounterIncrement();
3325 * If the namespace already exists, clean it out (in case the former
3326 * owner crashed without doing so).
3328 RemoveTempRelations(namespaceId);
3332 * If the corresponding toast-table namespace doesn't exist yet, create
3333 * it. (We assume there is no need to clean it out if it does exist, since
3334 * dropping a parent table should make its toast table go away.)
3336 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3339 toastspaceId = get_namespace_oid(namespaceName, true);
3340 if (!OidIsValid(toastspaceId))
3342 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3343 /* Advance command counter to make namespace visible */
3344 CommandCounterIncrement();
3348 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3349 * so all our work could be undone by transaction rollback. Set flag for
3350 * AtEOXact_Namespace to know what to do.
3352 myTempNamespace = namespaceId;
3353 myTempToastNamespace = toastspaceId;
3355 /* It should not be done already. */
3356 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3357 myTempNamespaceSubID = GetCurrentSubTransactionId();
3359 baseSearchPathValid = false; /* need to rebuild list */
3363 * End-of-transaction cleanup for namespaces.
3366 AtEOXact_Namespace(bool isCommit)
3369 * If we abort the transaction in which a temp namespace was selected,
3370 * we'll have to do any creation or cleanout work over again. So, just
3371 * forget the namespace entirely until next time. On the other hand, if
3372 * we commit then register an exit callback to clean out the temp tables
3373 * at backend shutdown. (We only want to register the callback once per
3374 * session, so this is a good place to do it.)
3376 if (myTempNamespaceSubID != InvalidSubTransactionId)
3379 on_shmem_exit(RemoveTempRelationsCallback, 0);
3382 myTempNamespace = InvalidOid;
3383 myTempToastNamespace = InvalidOid;
3384 baseSearchPathValid = false; /* need to rebuild list */
3386 myTempNamespaceSubID = InvalidSubTransactionId;
3390 * Clean up if someone failed to do PopOverrideSearchPath
3395 elog(WARNING, "leaked override search path");
3396 while (overrideStack)
3398 OverrideStackEntry *entry;
3400 entry = (OverrideStackEntry *) linitial(overrideStack);
3401 overrideStack = list_delete_first(overrideStack);
3402 list_free(entry->searchPath);
3405 /* If not baseSearchPathValid, this is useless but harmless */
3406 activeSearchPath = baseSearchPath;
3407 activeCreationNamespace = baseCreationNamespace;
3408 activeTempCreationPending = baseTempCreationPending;
3413 * AtEOSubXact_Namespace
3415 * At subtransaction commit, propagate the temp-namespace-creation
3416 * flag to the parent subtransaction.
3418 * At subtransaction abort, forget the flag if we set it up.
3421 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3422 SubTransactionId parentSubid)
3424 OverrideStackEntry *entry;
3426 if (myTempNamespaceSubID == mySubid)
3429 myTempNamespaceSubID = parentSubid;
3432 myTempNamespaceSubID = InvalidSubTransactionId;
3433 /* TEMP namespace creation failed, so reset state */
3434 myTempNamespace = InvalidOid;
3435 myTempToastNamespace = InvalidOid;
3436 baseSearchPathValid = false; /* need to rebuild list */
3441 * Clean up if someone failed to do PopOverrideSearchPath
3443 while (overrideStack)
3445 entry = (OverrideStackEntry *) linitial(overrideStack);
3446 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3449 elog(WARNING, "leaked override search path");
3450 overrideStack = list_delete_first(overrideStack);
3451 list_free(entry->searchPath);
3455 /* Activate the next level down. */
3458 entry = (OverrideStackEntry *) linitial(overrideStack);
3459 activeSearchPath = entry->searchPath;
3460 activeCreationNamespace = entry->creationNamespace;
3461 activeTempCreationPending = false; /* XXX is this OK? */
3465 /* If not baseSearchPathValid, this is useless but harmless */
3466 activeSearchPath = baseSearchPath;
3467 activeCreationNamespace = baseCreationNamespace;
3468 activeTempCreationPending = baseTempCreationPending;
3473 * Remove all relations in the specified temp namespace.
3475 * This is called at backend shutdown (if we made any temp relations).
3476 * It is also called when we begin using a pre-existing temp namespace,
3477 * in order to clean out any relations that might have been created by
3478 * a crashed backend.
3481 RemoveTempRelations(Oid tempNamespaceId)
3483 ObjectAddress object;
3486 * We want to get rid of everything in the target namespace, but not the
3487 * namespace itself (deleting it only to recreate it later would be a
3488 * waste of cycles). We do this by finding everything that has a
3489 * dependency on the namespace.
3491 object.classId = NamespaceRelationId;
3492 object.objectId = tempNamespaceId;
3493 object.objectSubId = 0;
3495 deleteWhatDependsOn(&object, false);
3499 * Callback to remove temp relations at backend exit.
3502 RemoveTempRelationsCallback(int code, Datum arg)
3504 if (OidIsValid(myTempNamespace)) /* should always be true */
3506 /* Need to ensure we have a usable transaction. */
3507 AbortOutOfAnyTransaction();
3508 StartTransactionCommand();
3510 RemoveTempRelations(myTempNamespace);
3512 CommitTransactionCommand();
3517 * Remove all temp tables from the temporary namespace.
3520 ResetTempTableNamespace(void)
3522 if (OidIsValid(myTempNamespace))
3523 RemoveTempRelations(myTempNamespace);
3528 * Routines for handling the GUC variable 'search_path'.
3531 /* check_hook: validate new search_path, if possible */
3533 check_search_path(char **newval, void **extra, GucSource source)
3540 /* Need a modifiable copy of string */
3541 rawname = pstrdup(*newval);
3543 /* Parse string into list of identifiers */
3544 if (!SplitIdentifierString(rawname, ',', &namelist))
3546 /* syntax error in name list */
3547 GUC_check_errdetail("List syntax is invalid.");
3549 list_free(namelist);
3554 * If we aren't inside a transaction, we cannot do database access so
3555 * cannot verify the individual names. Must accept the list on faith.
3557 if (IsTransactionState())
3560 * Verify that all the names are either valid namespace names or
3561 * "$user" or "pg_temp". We do not require $user to correspond to a
3562 * valid namespace, and pg_temp might not exist yet. We do not check
3563 * for USAGE rights, either; should we?
3565 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3566 * DATABASE SET or ALTER USER SET command. It could be that the
3567 * intended use of the search path is for some other database, so we
3568 * should not error out if it mentions schemas not present in the
3569 * current database. We issue a NOTICE instead.
3571 foreach(l, namelist)
3573 char *curname = (char *) lfirst(l);
3575 if (strcmp(curname, "$user") == 0)
3577 if (strcmp(curname, "pg_temp") == 0)
3579 if (!SearchSysCacheExists1(NAMESPACENAME,
3580 CStringGetDatum(curname)))
3582 if (source == PGC_S_TEST)
3584 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3585 errmsg("schema \"%s\" does not exist", curname)));
3588 GUC_check_errdetail("schema \"%s\" does not exist", curname);
3597 list_free(namelist);
3602 /* assign_hook: do extra actions as needed */
3604 assign_search_path(const char *newval, void *extra)
3607 * We mark the path as needing recomputation, but don't do anything until
3608 * it's needed. This avoids trying to do database access during GUC
3609 * initialization, or outside a transaction.
3611 baseSearchPathValid = false;
3615 * InitializeSearchPath: initialize module during InitPostgres.
3617 * This is called after we are up enough to be able to do catalog lookups.
3620 InitializeSearchPath(void)
3622 if (IsBootstrapProcessingMode())
3625 * In bootstrap mode, the search path must be 'pg_catalog' so that
3626 * tables are created in the proper namespace; ignore the GUC setting.
3628 MemoryContext oldcxt;
3630 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3631 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3632 MemoryContextSwitchTo(oldcxt);
3633 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3634 baseTempCreationPending = false;
3635 baseSearchPathValid = true;
3636 namespaceUser = GetUserId();
3637 activeSearchPath = baseSearchPath;
3638 activeCreationNamespace = baseCreationNamespace;
3639 activeTempCreationPending = baseTempCreationPending;
3644 * In normal mode, arrange for a callback on any syscache invalidation
3645 * of pg_namespace rows.
3647 CacheRegisterSyscacheCallback(NAMESPACEOID,
3650 /* Force search path to be recomputed on next use */
3651 baseSearchPathValid = false;
3657 * Syscache inval callback function
3660 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3662 /* Force search path to be recomputed on next use */
3663 baseSearchPathValid = false;
3667 * Fetch the active search path. The return value is a palloc'ed list
3668 * of OIDs; the caller is responsible for freeing this storage as
3671 * The returned list includes the implicitly-prepended namespaces only if
3672 * includeImplicit is true.
3674 * Note: calling this may result in a CommandCounterIncrement operation,
3675 * if we have to create or clean out the temp namespace.
3678 fetch_search_path(bool includeImplicit)
3682 recomputeNamespacePath();
3685 * If the temp namespace should be first, force it to exist. This is so
3686 * that callers can trust the result to reflect the actual default
3687 * creation namespace. It's a bit bogus to do this here, since
3688 * current_schema() is supposedly a stable function without side-effects,
3689 * but the alternatives seem worse.
3691 if (activeTempCreationPending)
3693 InitTempTableNamespace();
3694 recomputeNamespacePath();
3697 result = list_copy(activeSearchPath);
3698 if (!includeImplicit)
3700 while (result && linitial_oid(result) != activeCreationNamespace)
3701 result = list_delete_first(result);
3708 * Fetch the active search path into a caller-allocated array of OIDs.
3709 * Returns the number of path entries. (If this is more than sarray_len,
3710 * then the data didn't fit and is not all stored.)
3712 * The returned list always includes the implicitly-prepended namespaces,
3713 * but never includes the temp namespace. (This is suitable for existing
3714 * users, which would want to ignore the temp namespace anyway.) This
3715 * definition allows us to not worry about initializing the temp namespace.
3718 fetch_search_path_array(Oid *sarray, int sarray_len)
3723 recomputeNamespacePath();
3725 foreach(l, activeSearchPath)
3727 Oid namespaceId = lfirst_oid(l);
3729 if (namespaceId == myTempNamespace)
3730 continue; /* do not include temp namespace */
3732 if (count < sarray_len)
3733 sarray[count] = namespaceId;
3742 * Export the FooIsVisible functions as SQL-callable functions.
3744 * Note: as of Postgres 8.4, these will silently return NULL if called on
3745 * a nonexistent object OID, rather than failing. This is to avoid race
3746 * condition errors when a query that's scanning a catalog using an MVCC
3747 * snapshot uses one of these functions. The underlying IsVisible functions
3748 * operate on SnapshotNow semantics and so might see the object as already
3749 * gone when it's still visible to the MVCC snapshot. (There is no race
3750 * condition in the current coding because we don't accept sinval messages
3751 * between the SearchSysCacheExists test and the subsequent lookup.)
3755 pg_table_is_visible(PG_FUNCTION_ARGS)
3757 Oid oid = PG_GETARG_OID(0);
3759 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3762 PG_RETURN_BOOL(RelationIsVisible(oid));
3766 pg_type_is_visible(PG_FUNCTION_ARGS)
3768 Oid oid = PG_GETARG_OID(0);
3770 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3773 PG_RETURN_BOOL(TypeIsVisible(oid));
3777 pg_function_is_visible(PG_FUNCTION_ARGS)
3779 Oid oid = PG_GETARG_OID(0);
3781 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3784 PG_RETURN_BOOL(FunctionIsVisible(oid));
3788 pg_operator_is_visible(PG_FUNCTION_ARGS)
3790 Oid oid = PG_GETARG_OID(0);
3792 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3795 PG_RETURN_BOOL(OperatorIsVisible(oid));
3799 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3801 Oid oid = PG_GETARG_OID(0);
3803 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3806 PG_RETURN_BOOL(OpclassIsVisible(oid));
3810 pg_collation_is_visible(PG_FUNCTION_ARGS)
3812 Oid oid = PG_GETARG_OID(0);
3814 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
3817 PG_RETURN_BOOL(CollationIsVisible(oid));
3821 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3823 Oid oid = PG_GETARG_OID(0);
3825 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3828 PG_RETURN_BOOL(ConversionIsVisible(oid));
3832 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3834 Oid oid = PG_GETARG_OID(0);
3836 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3839 PG_RETURN_BOOL(TSParserIsVisible(oid));
3843 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3845 Oid oid = PG_GETARG_OID(0);
3847 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3850 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3854 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3856 Oid oid = PG_GETARG_OID(0);
3858 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3861 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3865 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3867 Oid oid = PG_GETARG_OID(0);
3869 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3872 PG_RETURN_BOOL(TSConfigIsVisible(oid));
3876 pg_my_temp_schema(PG_FUNCTION_ARGS)
3878 PG_RETURN_OID(myTempNamespace);
3882 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3884 Oid oid = PG_GETARG_OID(0);
3886 PG_RETURN_BOOL(isOtherTempNamespace(oid));