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->relpersistence == RELPERSISTENCE_TEMP)
316 /* TEMP tables are created in our backend-local temp namespace */
317 if (newRelation->schemaname)
319 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
320 errmsg("temporary tables cannot specify a schema name")));
321 /* Initialize temp namespace if first time through */
322 if (!OidIsValid(myTempNamespace))
323 InitTempTableNamespace();
324 return myTempNamespace;
327 if (newRelation->schemaname)
329 /* check for pg_temp alias */
330 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
332 /* Initialize temp namespace if first time through */
333 if (!OidIsValid(myTempNamespace))
334 InitTempTableNamespace();
335 return myTempNamespace;
337 /* use exact schema given */
338 namespaceId = get_namespace_oid(newRelation->schemaname, false);
339 /* we do not check for USAGE rights here! */
343 /* use the default creation namespace */
344 recomputeNamespacePath();
345 if (activeTempCreationPending)
347 /* Need to initialize temp namespace */
348 InitTempTableNamespace();
349 return myTempNamespace;
351 namespaceId = activeCreationNamespace;
352 if (!OidIsValid(namespaceId))
354 (errcode(ERRCODE_UNDEFINED_SCHEMA),
355 errmsg("no schema has been selected to create in")));
358 /* Note: callers will check for CREATE rights when appropriate */
365 * Try to resolve an unqualified relation name.
366 * Returns OID if relation found in search path, else InvalidOid.
369 RelnameGetRelid(const char *relname)
374 recomputeNamespacePath();
376 foreach(l, activeSearchPath)
378 Oid namespaceId = lfirst_oid(l);
380 relid = get_relname_relid(relname, namespaceId);
381 if (OidIsValid(relid))
385 /* Not found in path */
392 * Determine whether a relation (identified by OID) is visible in the
393 * current search path. Visible means "would be found by searching
394 * for the unqualified relation name".
397 RelationIsVisible(Oid relid)
400 Form_pg_class relform;
404 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
405 if (!HeapTupleIsValid(reltup))
406 elog(ERROR, "cache lookup failed for relation %u", relid);
407 relform = (Form_pg_class) GETSTRUCT(reltup);
409 recomputeNamespacePath();
412 * Quick check: if it ain't in the path at all, it ain't visible. Items in
413 * the system namespace are surely in the path and so we needn't even do
414 * list_member_oid() for them.
416 relnamespace = relform->relnamespace;
417 if (relnamespace != PG_CATALOG_NAMESPACE &&
418 !list_member_oid(activeSearchPath, relnamespace))
423 * If it is in the path, it might still not be visible; it could be
424 * hidden by another relation of the same name earlier in the path. So
425 * we must do a slow check for conflicting relations.
427 char *relname = NameStr(relform->relname);
431 foreach(l, activeSearchPath)
433 Oid namespaceId = lfirst_oid(l);
435 if (namespaceId == relnamespace)
437 /* Found it first in path */
441 if (OidIsValid(get_relname_relid(relname, namespaceId)))
443 /* Found something else first in path */
449 ReleaseSysCache(reltup);
457 * Try to resolve an unqualified datatype name.
458 * Returns OID if type found in search path, else InvalidOid.
460 * This is essentially the same as RelnameGetRelid.
463 TypenameGetTypid(const char *typname)
468 recomputeNamespacePath();
470 foreach(l, activeSearchPath)
472 Oid namespaceId = lfirst_oid(l);
474 typid = GetSysCacheOid2(TYPENAMENSP,
475 PointerGetDatum(typname),
476 ObjectIdGetDatum(namespaceId));
477 if (OidIsValid(typid))
481 /* Not found in path */
487 * Determine whether a type (identified by OID) is visible in the
488 * current search path. Visible means "would be found by searching
489 * for the unqualified type name".
492 TypeIsVisible(Oid typid)
495 Form_pg_type typform;
499 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
500 if (!HeapTupleIsValid(typtup))
501 elog(ERROR, "cache lookup failed for type %u", typid);
502 typform = (Form_pg_type) GETSTRUCT(typtup);
504 recomputeNamespacePath();
507 * Quick check: if it ain't in the path at all, it ain't visible. Items in
508 * the system namespace are surely in the path and so we needn't even do
509 * list_member_oid() for them.
511 typnamespace = typform->typnamespace;
512 if (typnamespace != PG_CATALOG_NAMESPACE &&
513 !list_member_oid(activeSearchPath, typnamespace))
518 * If it is in the path, it might still not be visible; it could be
519 * hidden by another type of the same name earlier in the path. So we
520 * must do a slow check for conflicting types.
522 char *typname = NameStr(typform->typname);
526 foreach(l, activeSearchPath)
528 Oid namespaceId = lfirst_oid(l);
530 if (namespaceId == typnamespace)
532 /* Found it first in path */
536 if (SearchSysCacheExists2(TYPENAMENSP,
537 PointerGetDatum(typname),
538 ObjectIdGetDatum(namespaceId)))
540 /* Found something else first in path */
546 ReleaseSysCache(typtup);
553 * FuncnameGetCandidates
554 * Given a possibly-qualified function name and argument count,
555 * retrieve a list of the possible matches.
557 * If nargs is -1, we return all functions matching the given name,
558 * regardless of argument count. (argnames must be NIL, and expand_variadic
559 * and expand_defaults must be false, in this case.)
561 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
562 * and only functions having all the listed argument names will be returned.
563 * (We assume that length(argnames) <= nargs and all the passed-in names are
564 * distinct.) The returned structs will include an argnumbers array showing
565 * the actual argument index for each logical argument position.
567 * If expand_variadic is true, then variadic functions having the same number
568 * or fewer arguments will be retrieved, with the variadic argument and any
569 * additional argument positions filled with the variadic element type.
570 * nvargs in the returned struct is set to the number of such arguments.
571 * If expand_variadic is false, variadic arguments are not treated specially,
572 * and the returned nvargs will always be zero.
574 * If expand_defaults is true, functions that could match after insertion of
575 * default argument values will also be retrieved. In this case the returned
576 * structs could have nargs > passed-in nargs, and ndargs is set to the number
577 * of additional args (which can be retrieved from the function's
578 * proargdefaults entry).
580 * It is not possible for nvargs and ndargs to both be nonzero in the same
581 * list entry, since default insertion allows matches to functions with more
582 * than nargs arguments while the variadic transformation requires the same
585 * When argnames isn't NIL, the returned args[] type arrays are not ordered
586 * according to the functions' declarations, but rather according to the call:
587 * first any positional arguments, then the named arguments, then defaulted
588 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
589 * array can be used to map this back to the catalog information.
590 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
592 * We search a single namespace if the function name is qualified, else
593 * all namespaces in the search path. In the multiple-namespace case,
594 * we arrange for entries in earlier namespaces to mask identical entries in
597 * When expanding variadics, we arrange for non-variadic functions to mask
598 * variadic ones if the expanded argument list is the same. It is still
599 * possible for there to be conflicts between different variadic functions,
602 * It is guaranteed that the return list will never contain multiple entries
603 * with identical argument lists. When expand_defaults is true, the entries
604 * could have more than nargs positions, but we still guarantee that they are
605 * distinct in the first nargs positions. However, if argnames isn't NIL or
606 * either expand_variadic or expand_defaults is true, there might be multiple
607 * candidate functions that expand to identical argument lists. Rather than
608 * throw error here, we report such situations by returning a single entry
609 * with oid = 0 that represents a set of such conflicting candidates.
610 * The caller might end up discarding such an entry anyway, but if it selects
611 * such an entry it should react as though the call were ambiguous.
614 FuncnameGetCandidates(List *names, int nargs, List *argnames,
615 bool expand_variadic, bool expand_defaults)
617 FuncCandidateList resultList = NULL;
618 bool any_special = false;
625 /* check for caller error */
626 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
628 /* deconstruct the name list */
629 DeconstructQualifiedName(names, &schemaname, &funcname);
633 /* use exact schema given */
634 namespaceId = LookupExplicitNamespace(schemaname);
638 /* flag to indicate we need namespace search */
639 namespaceId = InvalidOid;
640 recomputeNamespacePath();
643 /* Search syscache by name only */
644 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
646 for (i = 0; i < catlist->n_members; i++)
648 HeapTuple proctup = &catlist->members[i]->tuple;
649 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
650 int pronargs = procform->pronargs;
656 int *argnumbers = NULL;
657 FuncCandidateList newResult;
659 if (OidIsValid(namespaceId))
661 /* Consider only procs in specified namespace */
662 if (procform->pronamespace != namespaceId)
668 * Consider only procs that are in the search path and are not in
669 * the temp namespace.
673 foreach(nsp, activeSearchPath)
675 if (procform->pronamespace == lfirst_oid(nsp) &&
676 procform->pronamespace != myTempNamespace)
681 continue; /* proc is not in search path */
687 * Call uses named or mixed notation
689 * Named or mixed notation can match a variadic function only if
690 * expand_variadic is off; otherwise there is no way to match the
691 * presumed-nameless parameters expanded from the variadic array.
693 if (OidIsValid(procform->provariadic) && expand_variadic)
695 va_elem_type = InvalidOid;
699 * Check argument count.
701 Assert(nargs >= 0); /* -1 not supported with argnames */
703 if (pronargs > nargs && expand_defaults)
705 /* Ignore if not enough default expressions */
706 if (nargs + procform->pronargdefaults < pronargs)
711 use_defaults = false;
713 /* Ignore if it doesn't match requested argument count */
714 if (pronargs != nargs && !use_defaults)
717 /* Check for argument name match, generate positional mapping */
718 if (!MatchNamedCall(proctup, nargs, argnames,
722 /* Named argument matching is always "special" */
728 * Call uses positional notation
730 * Check if function is variadic, and get variadic element type if
731 * so. If expand_variadic is false, we should just ignore
734 if (pronargs <= nargs && expand_variadic)
736 va_elem_type = procform->provariadic;
737 variadic = OidIsValid(va_elem_type);
738 any_special |= variadic;
742 va_elem_type = InvalidOid;
747 * Check if function can match by using parameter defaults.
749 if (pronargs > nargs && expand_defaults)
751 /* Ignore if not enough default expressions */
752 if (nargs + procform->pronargdefaults < pronargs)
758 use_defaults = false;
760 /* Ignore if it doesn't match requested argument count */
761 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
766 * We must compute the effective argument list so that we can easily
767 * compare it to earlier results. We waste a palloc cycle if it gets
768 * masked by an earlier result, but really that's a pretty infrequent
769 * case so it's not worth worrying about.
771 effective_nargs = Max(pronargs, nargs);
772 newResult = (FuncCandidateList)
773 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
774 + effective_nargs * sizeof(Oid));
775 newResult->pathpos = pathpos;
776 newResult->oid = HeapTupleGetOid(proctup);
777 newResult->nargs = effective_nargs;
778 newResult->argnumbers = argnumbers;
781 /* Re-order the argument types into call's logical order */
782 Oid *proargtypes = procform->proargtypes.values;
785 for (i = 0; i < pronargs; i++)
786 newResult->args[i] = proargtypes[argnumbers[i]];
790 /* Simple positional case, just copy proargtypes as-is */
791 memcpy(newResult->args, procform->proargtypes.values,
792 pronargs * sizeof(Oid));
798 newResult->nvargs = effective_nargs - pronargs + 1;
799 /* Expand variadic argument into N copies of element type */
800 for (i = pronargs - 1; i < effective_nargs; i++)
801 newResult->args[i] = va_elem_type;
804 newResult->nvargs = 0;
805 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
808 * Does it have the same arguments as something we already accepted?
809 * If so, decide what to do to avoid returning duplicate argument
810 * lists. We can skip this check for the single-namespace case if no
811 * special (named, variadic or defaults) match has been made, since
812 * then the unique index on pg_proc guarantees all the matches have
813 * different argument lists.
815 if (resultList != NULL &&
816 (any_special || !OidIsValid(namespaceId)))
819 * If we have an ordered list from SearchSysCacheList (the normal
820 * case), then any conflicting proc must immediately adjoin this
821 * one in the list, so we only need to look at the newest result
822 * item. If we have an unordered list, we have to scan the whole
823 * result list. Also, if either the current candidate or any
824 * previous candidate is a special match, we can't assume that
825 * conflicts are adjacent.
827 * We ignore defaulted arguments in deciding what is a match.
829 FuncCandidateList prevResult;
831 if (catlist->ordered && !any_special)
833 /* ndargs must be 0 if !any_special */
834 if (effective_nargs == resultList->nargs &&
835 memcmp(newResult->args,
837 effective_nargs * sizeof(Oid)) == 0)
838 prevResult = resultList;
844 int cmp_nargs = newResult->nargs - newResult->ndargs;
846 for (prevResult = resultList;
848 prevResult = prevResult->next)
850 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
851 memcmp(newResult->args,
853 cmp_nargs * sizeof(Oid)) == 0)
861 * We have a match with a previous result. Decide which one
862 * to keep, or mark it ambiguous if we can't decide. The
863 * logic here is preference > 0 means prefer the old result,
864 * preference < 0 means prefer the new, preference = 0 means
869 if (pathpos != prevResult->pathpos)
872 * Prefer the one that's earlier in the search path.
874 preference = pathpos - prevResult->pathpos;
876 else if (variadic && prevResult->nvargs == 0)
879 * With variadic functions we could have, for example,
880 * both foo(numeric) and foo(variadic numeric[]) in the
881 * same namespace; if so we prefer the non-variadic match
882 * on efficiency grounds.
886 else if (!variadic && prevResult->nvargs > 0)
893 * We can't decide. This can happen with, for example,
894 * both foo(numeric, variadic numeric[]) and
895 * foo(variadic numeric[]) in the same namespace, or
896 * both foo(int) and foo (int, int default something)
897 * in the same namespace, or both foo(a int, b text)
898 * and foo(b text, a int) in the same namespace.
906 /* keep previous result */
910 else if (preference < 0)
912 /* remove previous result from the list */
913 if (prevResult == resultList)
914 resultList = prevResult->next;
917 FuncCandidateList prevPrevResult;
919 for (prevPrevResult = resultList;
921 prevPrevResult = prevPrevResult->next)
923 if (prevResult == prevPrevResult->next)
925 prevPrevResult->next = prevResult->next;
929 Assert(prevPrevResult); /* assert we found it */
932 /* fall through to add newResult to list */
936 /* mark old result as ambiguous, discard new */
937 prevResult->oid = InvalidOid;
945 * Okay to add it to result list
947 newResult->next = resultList;
948 resultList = newResult;
951 ReleaseSysCacheList(catlist);
958 * Given a pg_proc heap tuple and a call's list of argument names,
959 * check whether the function could match the call.
961 * The call could match if all supplied argument names are accepted by
962 * the function, in positions after the last positional argument, and there
963 * are defaults for all unsupplied arguments.
965 * The number of positional arguments is nargs - list_length(argnames).
966 * Note caller has already done basic checks on argument count.
968 * On match, return true and fill *argnumbers with a palloc'd array showing
969 * the mapping from call argument positions to actual function argument
970 * numbers. Defaulted arguments are included in this map, at positions
971 * after the last supplied argument.
974 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
977 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
978 int pronargs = procform->pronargs;
979 int numposargs = nargs - list_length(argnames);
984 bool arggiven[FUNC_MAX_ARGS];
986 int ap; /* call args position */
987 int pp; /* proargs position */
990 Assert(argnames != NIL);
991 Assert(numposargs >= 0);
992 Assert(nargs <= pronargs);
994 /* Ignore this function if its proargnames is null */
995 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1000 /* OK, let's extract the argument names and types */
1001 pronallargs = get_func_arg_info(proctup,
1002 &p_argtypes, &p_argnames, &p_argmodes);
1003 Assert(p_argnames != NULL);
1005 /* initialize state for matching */
1006 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1007 memset(arggiven, false, pronargs * sizeof(bool));
1009 /* there are numposargs positional args before the named args */
1010 for (ap = 0; ap < numposargs; ap++)
1012 (*argnumbers)[ap] = ap;
1013 arggiven[ap] = true;
1016 /* now examine the named args */
1017 foreach(lc, argnames)
1019 char *argname = (char *) lfirst(lc);
1025 for (i = 0; i < pronallargs; i++)
1027 /* consider only input parameters */
1029 (p_argmodes[i] != FUNC_PARAM_IN &&
1030 p_argmodes[i] != FUNC_PARAM_INOUT &&
1031 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1033 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1035 /* fail if argname matches a positional argument */
1038 arggiven[pp] = true;
1039 (*argnumbers)[ap] = pp;
1043 /* increase pp only for input parameters */
1046 /* if name isn't in proargnames, fail */
1052 Assert(ap == nargs); /* processed all actual parameters */
1054 /* Check for default arguments */
1055 if (nargs < pronargs)
1057 int first_arg_with_default = pronargs - procform->pronargdefaults;
1059 for (pp = numposargs; pp < pronargs; pp++)
1063 /* fail if arg not given and no default available */
1064 if (pp < first_arg_with_default)
1066 (*argnumbers)[ap++] = pp;
1070 Assert(ap == pronargs); /* processed all function parameters */
1077 * Determine whether a function (identified by OID) is visible in the
1078 * current search path. Visible means "would be found by searching
1079 * for the unqualified function name with exact argument matches".
1082 FunctionIsVisible(Oid funcid)
1085 Form_pg_proc procform;
1089 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1090 if (!HeapTupleIsValid(proctup))
1091 elog(ERROR, "cache lookup failed for function %u", funcid);
1092 procform = (Form_pg_proc) GETSTRUCT(proctup);
1094 recomputeNamespacePath();
1097 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1098 * the system namespace are surely in the path and so we needn't even do
1099 * list_member_oid() for them.
1101 pronamespace = procform->pronamespace;
1102 if (pronamespace != PG_CATALOG_NAMESPACE &&
1103 !list_member_oid(activeSearchPath, pronamespace))
1108 * If it is in the path, it might still not be visible; it could be
1109 * hidden by another proc of the same name and arguments earlier in
1110 * the path. So we must do a slow check to see if this is the same
1111 * proc that would be found by FuncnameGetCandidates.
1113 char *proname = NameStr(procform->proname);
1114 int nargs = procform->pronargs;
1115 FuncCandidateList clist;
1119 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1120 nargs, NIL, false, false);
1122 for (; clist; clist = clist->next)
1124 if (memcmp(clist->args, procform->proargtypes.values,
1125 nargs * sizeof(Oid)) == 0)
1127 /* Found the expected entry; is it the right proc? */
1128 visible = (clist->oid == funcid);
1134 ReleaseSysCache(proctup);
1142 * Given a possibly-qualified operator name and exact input datatypes,
1143 * look up the operator. Returns InvalidOid if not found.
1145 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1148 * If the operator name is not schema-qualified, it is sought in the current
1149 * namespace search path.
1152 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1159 /* deconstruct the name list */
1160 DeconstructQualifiedName(names, &schemaname, &opername);
1164 /* search only in exact schema given */
1168 namespaceId = LookupExplicitNamespace(schemaname);
1169 opertup = SearchSysCache4(OPERNAMENSP,
1170 CStringGetDatum(opername),
1171 ObjectIdGetDatum(oprleft),
1172 ObjectIdGetDatum(oprright),
1173 ObjectIdGetDatum(namespaceId));
1174 if (HeapTupleIsValid(opertup))
1176 Oid result = HeapTupleGetOid(opertup);
1178 ReleaseSysCache(opertup);
1184 /* Search syscache by name and argument types */
1185 catlist = SearchSysCacheList3(OPERNAMENSP,
1186 CStringGetDatum(opername),
1187 ObjectIdGetDatum(oprleft),
1188 ObjectIdGetDatum(oprright));
1190 if (catlist->n_members == 0)
1192 /* no hope, fall out early */
1193 ReleaseSysCacheList(catlist);
1198 * We have to find the list member that is first in the search path, if
1199 * there's more than one. This doubly-nested loop looks ugly, but in
1200 * practice there should usually be few catlist members.
1202 recomputeNamespacePath();
1204 foreach(l, activeSearchPath)
1206 Oid namespaceId = lfirst_oid(l);
1209 if (namespaceId == myTempNamespace)
1210 continue; /* do not look in temp namespace */
1212 for (i = 0; i < catlist->n_members; i++)
1214 HeapTuple opertup = &catlist->members[i]->tuple;
1215 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1217 if (operform->oprnamespace == namespaceId)
1219 Oid result = HeapTupleGetOid(opertup);
1221 ReleaseSysCacheList(catlist);
1227 ReleaseSysCacheList(catlist);
1232 * OpernameGetCandidates
1233 * Given a possibly-qualified operator name and operator kind,
1234 * retrieve a list of the possible matches.
1236 * If oprkind is '\0', we return all operators matching the given name,
1237 * regardless of arguments.
1239 * We search a single namespace if the operator name is qualified, else
1240 * all namespaces in the search path. The return list will never contain
1241 * multiple entries with identical argument lists --- in the multiple-
1242 * namespace case, we arrange for entries in earlier namespaces to mask
1243 * identical entries in later namespaces.
1245 * The returned items always have two args[] entries --- one or the other
1246 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1249 OpernameGetCandidates(List *names, char oprkind)
1251 FuncCandidateList resultList = NULL;
1252 char *resultSpace = NULL;
1260 /* deconstruct the name list */
1261 DeconstructQualifiedName(names, &schemaname, &opername);
1265 /* use exact schema given */
1266 namespaceId = LookupExplicitNamespace(schemaname);
1270 /* flag to indicate we need namespace search */
1271 namespaceId = InvalidOid;
1272 recomputeNamespacePath();
1275 /* Search syscache by name only */
1276 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1279 * In typical scenarios, most if not all of the operators found by the
1280 * catcache search will end up getting returned; and there can be quite a
1281 * few, for common operator names such as '=' or '+'. To reduce the time
1282 * spent in palloc, we allocate the result space as an array large enough
1283 * to hold all the operators. The original coding of this routine did a
1284 * separate palloc for each operator, but profiling revealed that the
1285 * pallocs used an unreasonably large fraction of parsing time.
1287 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1289 if (catlist->n_members > 0)
1290 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1292 for (i = 0; i < catlist->n_members; i++)
1294 HeapTuple opertup = &catlist->members[i]->tuple;
1295 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1297 FuncCandidateList newResult;
1299 /* Ignore operators of wrong kind, if specific kind requested */
1300 if (oprkind && operform->oprkind != oprkind)
1303 if (OidIsValid(namespaceId))
1305 /* Consider only opers in specified namespace */
1306 if (operform->oprnamespace != namespaceId)
1308 /* No need to check args, they must all be different */
1313 * Consider only opers that are in the search path and are not in
1314 * the temp namespace.
1318 foreach(nsp, activeSearchPath)
1320 if (operform->oprnamespace == lfirst_oid(nsp) &&
1321 operform->oprnamespace != myTempNamespace)
1326 continue; /* oper is not in search path */
1329 * Okay, it's in the search path, but does it have the same
1330 * arguments as something we already accepted? If so, keep only
1331 * the one that appears earlier in the search path.
1333 * If we have an ordered list from SearchSysCacheList (the normal
1334 * case), then any conflicting oper must immediately adjoin this
1335 * one in the list, so we only need to look at the newest result
1336 * item. If we have an unordered list, we have to scan the whole
1341 FuncCandidateList prevResult;
1343 if (catlist->ordered)
1345 if (operform->oprleft == resultList->args[0] &&
1346 operform->oprright == resultList->args[1])
1347 prevResult = resultList;
1353 for (prevResult = resultList;
1355 prevResult = prevResult->next)
1357 if (operform->oprleft == prevResult->args[0] &&
1358 operform->oprright == prevResult->args[1])
1364 /* We have a match with a previous result */
1365 Assert(pathpos != prevResult->pathpos);
1366 if (pathpos > prevResult->pathpos)
1367 continue; /* keep previous result */
1368 /* replace previous result */
1369 prevResult->pathpos = pathpos;
1370 prevResult->oid = HeapTupleGetOid(opertup);
1371 continue; /* args are same, of course */
1377 * Okay to add it to result list
1379 newResult = (FuncCandidateList) (resultSpace + nextResult);
1380 nextResult += SPACE_PER_OP;
1382 newResult->pathpos = pathpos;
1383 newResult->oid = HeapTupleGetOid(opertup);
1384 newResult->nargs = 2;
1385 newResult->nvargs = 0;
1386 newResult->ndargs = 0;
1387 newResult->argnumbers = NULL;
1388 newResult->args[0] = operform->oprleft;
1389 newResult->args[1] = operform->oprright;
1390 newResult->next = resultList;
1391 resultList = newResult;
1394 ReleaseSysCacheList(catlist);
1401 * Determine whether an operator (identified by OID) is visible in the
1402 * current search path. Visible means "would be found by searching
1403 * for the unqualified operator name with exact argument matches".
1406 OperatorIsVisible(Oid oprid)
1409 Form_pg_operator oprform;
1413 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1414 if (!HeapTupleIsValid(oprtup))
1415 elog(ERROR, "cache lookup failed for operator %u", oprid);
1416 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1418 recomputeNamespacePath();
1421 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1422 * the system namespace are surely in the path and so we needn't even do
1423 * list_member_oid() for them.
1425 oprnamespace = oprform->oprnamespace;
1426 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1427 !list_member_oid(activeSearchPath, oprnamespace))
1432 * If it is in the path, it might still not be visible; it could be
1433 * hidden by another operator of the same name and arguments earlier
1434 * in the path. So we must do a slow check to see if this is the same
1435 * operator that would be found by OpernameGetOprId.
1437 char *oprname = NameStr(oprform->oprname);
1439 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1440 oprform->oprleft, oprform->oprright)
1444 ReleaseSysCache(oprtup);
1451 * OpclassnameGetOpcid
1452 * Try to resolve an unqualified index opclass name.
1453 * Returns OID if opclass found in search path, else InvalidOid.
1455 * This is essentially the same as TypenameGetTypid, but we have to have
1456 * an extra argument for the index AM OID.
1459 OpclassnameGetOpcid(Oid amid, const char *opcname)
1464 recomputeNamespacePath();
1466 foreach(l, activeSearchPath)
1468 Oid namespaceId = lfirst_oid(l);
1470 if (namespaceId == myTempNamespace)
1471 continue; /* do not look in temp namespace */
1473 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1474 ObjectIdGetDatum(amid),
1475 PointerGetDatum(opcname),
1476 ObjectIdGetDatum(namespaceId));
1477 if (OidIsValid(opcid))
1481 /* Not found in path */
1487 * Determine whether an opclass (identified by OID) is visible in the
1488 * current search path. Visible means "would be found by searching
1489 * for the unqualified opclass name".
1492 OpclassIsVisible(Oid opcid)
1495 Form_pg_opclass opcform;
1499 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1500 if (!HeapTupleIsValid(opctup))
1501 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1502 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1504 recomputeNamespacePath();
1507 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1508 * the system namespace are surely in the path and so we needn't even do
1509 * list_member_oid() for them.
1511 opcnamespace = opcform->opcnamespace;
1512 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1513 !list_member_oid(activeSearchPath, opcnamespace))
1518 * If it is in the path, it might still not be visible; it could be
1519 * hidden by another opclass of the same name earlier in the path. So
1520 * we must do a slow check to see if this opclass would be found by
1521 * OpclassnameGetOpcid.
1523 char *opcname = NameStr(opcform->opcname);
1525 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1528 ReleaseSysCache(opctup);
1534 * OpfamilynameGetOpfid
1535 * Try to resolve an unqualified index opfamily name.
1536 * Returns OID if opfamily found in search path, else InvalidOid.
1538 * This is essentially the same as TypenameGetTypid, but we have to have
1539 * an extra argument for the index AM OID.
1542 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1547 recomputeNamespacePath();
1549 foreach(l, activeSearchPath)
1551 Oid namespaceId = lfirst_oid(l);
1553 if (namespaceId == myTempNamespace)
1554 continue; /* do not look in temp namespace */
1556 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1557 ObjectIdGetDatum(amid),
1558 PointerGetDatum(opfname),
1559 ObjectIdGetDatum(namespaceId));
1560 if (OidIsValid(opfid))
1564 /* Not found in path */
1570 * Determine whether an opfamily (identified by OID) is visible in the
1571 * current search path. Visible means "would be found by searching
1572 * for the unqualified opfamily name".
1575 OpfamilyIsVisible(Oid opfid)
1578 Form_pg_opfamily opfform;
1582 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1583 if (!HeapTupleIsValid(opftup))
1584 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1585 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1587 recomputeNamespacePath();
1590 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1591 * the system namespace are surely in the path and so we needn't even do
1592 * list_member_oid() for them.
1594 opfnamespace = opfform->opfnamespace;
1595 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1596 !list_member_oid(activeSearchPath, opfnamespace))
1601 * If it is in the path, it might still not be visible; it could be
1602 * hidden by another opfamily of the same name earlier in the path. So
1603 * we must do a slow check to see if this opfamily would be found by
1604 * OpfamilynameGetOpfid.
1606 char *opfname = NameStr(opfform->opfname);
1608 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1611 ReleaseSysCache(opftup);
1617 * CollationGetCollid
1618 * Try to resolve an unqualified collation name.
1619 * Returns OID if collation found in search path, else InvalidOid.
1621 * This is essentially the same as RelnameGetRelid.
1624 CollationGetCollid(const char *collname)
1629 recomputeNamespacePath();
1631 foreach(l, activeSearchPath)
1633 Oid namespaceId = lfirst_oid(l);
1635 if (namespaceId == myTempNamespace)
1636 continue; /* do not look in temp namespace */
1638 collid = GetSysCacheOid3(COLLNAMEENCNSP,
1639 PointerGetDatum(collname),
1640 Int32GetDatum(GetDatabaseEncoding()),
1641 ObjectIdGetDatum(namespaceId));
1642 if (OidIsValid(collid))
1646 /* Not found in path */
1651 * CollationIsVisible
1652 * Determine whether a collation (identified by OID) is visible in the
1653 * current search path. Visible means "would be found by searching
1654 * for the unqualified collation name".
1657 CollationIsVisible(Oid collid)
1660 Form_pg_collation collform;
1664 colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1665 if (!HeapTupleIsValid(colltup))
1666 elog(ERROR, "cache lookup failed for collation %u", collid);
1667 collform = (Form_pg_collation) GETSTRUCT(colltup);
1669 recomputeNamespacePath();
1672 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1673 * the system namespace are surely in the path and so we needn't even do
1674 * list_member_oid() for them.
1676 collnamespace = collform->collnamespace;
1677 if (collnamespace != PG_CATALOG_NAMESPACE &&
1678 !list_member_oid(activeSearchPath, collnamespace))
1683 * If it is in the path, it might still not be visible; it could be
1684 * hidden by another conversion of the same name earlier in the path.
1685 * So we must do a slow check to see if this conversion would be found
1686 * by CollationGetCollid.
1688 char *collname = NameStr(collform->collname);
1690 visible = (CollationGetCollid(collname) == collid);
1693 ReleaseSysCache(colltup);
1700 * ConversionGetConid
1701 * Try to resolve an unqualified conversion name.
1702 * Returns OID if conversion found in search path, else InvalidOid.
1704 * This is essentially the same as RelnameGetRelid.
1707 ConversionGetConid(const char *conname)
1712 recomputeNamespacePath();
1714 foreach(l, activeSearchPath)
1716 Oid namespaceId = lfirst_oid(l);
1718 if (namespaceId == myTempNamespace)
1719 continue; /* do not look in temp namespace */
1721 conid = GetSysCacheOid2(CONNAMENSP,
1722 PointerGetDatum(conname),
1723 ObjectIdGetDatum(namespaceId));
1724 if (OidIsValid(conid))
1728 /* Not found in path */
1733 * ConversionIsVisible
1734 * Determine whether a conversion (identified by OID) is visible in the
1735 * current search path. Visible means "would be found by searching
1736 * for the unqualified conversion name".
1739 ConversionIsVisible(Oid conid)
1742 Form_pg_conversion conform;
1746 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1747 if (!HeapTupleIsValid(contup))
1748 elog(ERROR, "cache lookup failed for conversion %u", conid);
1749 conform = (Form_pg_conversion) GETSTRUCT(contup);
1751 recomputeNamespacePath();
1754 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1755 * the system namespace are surely in the path and so we needn't even do
1756 * list_member_oid() for them.
1758 connamespace = conform->connamespace;
1759 if (connamespace != PG_CATALOG_NAMESPACE &&
1760 !list_member_oid(activeSearchPath, connamespace))
1765 * If it is in the path, it might still not be visible; it could be
1766 * hidden by another conversion of the same name earlier in the path.
1767 * So we must do a slow check to see if this conversion would be found
1768 * by ConversionGetConid.
1770 char *conname = NameStr(conform->conname);
1772 visible = (ConversionGetConid(conname) == conid);
1775 ReleaseSysCache(contup);
1781 * get_ts_parser_oid - find a TS parser by possibly qualified name
1783 * If not found, returns InvalidOid if missing_ok, else throws error
1786 get_ts_parser_oid(List *names, bool missing_ok)
1791 Oid prsoid = InvalidOid;
1794 /* deconstruct the name list */
1795 DeconstructQualifiedName(names, &schemaname, &parser_name);
1799 /* use exact schema given */
1800 namespaceId = LookupExplicitNamespace(schemaname);
1801 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1802 PointerGetDatum(parser_name),
1803 ObjectIdGetDatum(namespaceId));
1807 /* search for it in search path */
1808 recomputeNamespacePath();
1810 foreach(l, activeSearchPath)
1812 namespaceId = lfirst_oid(l);
1814 if (namespaceId == myTempNamespace)
1815 continue; /* do not look in temp namespace */
1817 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1818 PointerGetDatum(parser_name),
1819 ObjectIdGetDatum(namespaceId));
1820 if (OidIsValid(prsoid))
1825 if (!OidIsValid(prsoid) && !missing_ok)
1827 (errcode(ERRCODE_UNDEFINED_OBJECT),
1828 errmsg("text search parser \"%s\" does not exist",
1829 NameListToString(names))));
1836 * Determine whether a parser (identified by OID) is visible in the
1837 * current search path. Visible means "would be found by searching
1838 * for the unqualified parser name".
1841 TSParserIsVisible(Oid prsId)
1844 Form_pg_ts_parser form;
1848 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1849 if (!HeapTupleIsValid(tup))
1850 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1851 form = (Form_pg_ts_parser) GETSTRUCT(tup);
1853 recomputeNamespacePath();
1856 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1857 * the system namespace are surely in the path and so we needn't even do
1858 * list_member_oid() for them.
1860 namespace = form->prsnamespace;
1861 if (namespace != PG_CATALOG_NAMESPACE &&
1862 !list_member_oid(activeSearchPath, namespace))
1867 * If it is in the path, it might still not be visible; it could be
1868 * hidden by another parser of the same name earlier in the path. So
1869 * we must do a slow check for conflicting parsers.
1871 char *name = NameStr(form->prsname);
1875 foreach(l, activeSearchPath)
1877 Oid namespaceId = lfirst_oid(l);
1879 if (namespaceId == myTempNamespace)
1880 continue; /* do not look in temp namespace */
1882 if (namespaceId == namespace)
1884 /* Found it first in path */
1888 if (SearchSysCacheExists2(TSPARSERNAMENSP,
1889 PointerGetDatum(name),
1890 ObjectIdGetDatum(namespaceId)))
1892 /* Found something else first in path */
1898 ReleaseSysCache(tup);
1904 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
1906 * If not found, returns InvalidOid if failOK, else throws error
1909 get_ts_dict_oid(List *names, bool missing_ok)
1914 Oid dictoid = InvalidOid;
1917 /* deconstruct the name list */
1918 DeconstructQualifiedName(names, &schemaname, &dict_name);
1922 /* use exact schema given */
1923 namespaceId = LookupExplicitNamespace(schemaname);
1924 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1925 PointerGetDatum(dict_name),
1926 ObjectIdGetDatum(namespaceId));
1930 /* search for it in search path */
1931 recomputeNamespacePath();
1933 foreach(l, activeSearchPath)
1935 namespaceId = lfirst_oid(l);
1937 if (namespaceId == myTempNamespace)
1938 continue; /* do not look in temp namespace */
1940 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1941 PointerGetDatum(dict_name),
1942 ObjectIdGetDatum(namespaceId));
1943 if (OidIsValid(dictoid))
1948 if (!OidIsValid(dictoid) && !missing_ok)
1950 (errcode(ERRCODE_UNDEFINED_OBJECT),
1951 errmsg("text search dictionary \"%s\" does not exist",
1952 NameListToString(names))));
1958 * TSDictionaryIsVisible
1959 * Determine whether a dictionary (identified by OID) is visible in the
1960 * current search path. Visible means "would be found by searching
1961 * for the unqualified dictionary name".
1964 TSDictionaryIsVisible(Oid dictId)
1967 Form_pg_ts_dict form;
1971 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
1972 if (!HeapTupleIsValid(tup))
1973 elog(ERROR, "cache lookup failed for text search dictionary %u",
1975 form = (Form_pg_ts_dict) GETSTRUCT(tup);
1977 recomputeNamespacePath();
1980 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1981 * the system namespace are surely in the path and so we needn't even do
1982 * list_member_oid() for them.
1984 namespace = form->dictnamespace;
1985 if (namespace != PG_CATALOG_NAMESPACE &&
1986 !list_member_oid(activeSearchPath, namespace))
1991 * If it is in the path, it might still not be visible; it could be
1992 * hidden by another dictionary of the same name earlier in the path.
1993 * So we must do a slow check for conflicting dictionaries.
1995 char *name = NameStr(form->dictname);
1999 foreach(l, activeSearchPath)
2001 Oid namespaceId = lfirst_oid(l);
2003 if (namespaceId == myTempNamespace)
2004 continue; /* do not look in temp namespace */
2006 if (namespaceId == namespace)
2008 /* Found it first in path */
2012 if (SearchSysCacheExists2(TSDICTNAMENSP,
2013 PointerGetDatum(name),
2014 ObjectIdGetDatum(namespaceId)))
2016 /* Found something else first in path */
2022 ReleaseSysCache(tup);
2028 * get_ts_template_oid - find a TS template by possibly qualified name
2030 * If not found, returns InvalidOid if missing_ok, else throws error
2033 get_ts_template_oid(List *names, bool missing_ok)
2036 char *template_name;
2038 Oid tmploid = InvalidOid;
2041 /* deconstruct the name list */
2042 DeconstructQualifiedName(names, &schemaname, &template_name);
2046 /* use exact schema given */
2047 namespaceId = LookupExplicitNamespace(schemaname);
2048 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2049 PointerGetDatum(template_name),
2050 ObjectIdGetDatum(namespaceId));
2054 /* search for it in search path */
2055 recomputeNamespacePath();
2057 foreach(l, activeSearchPath)
2059 namespaceId = lfirst_oid(l);
2061 if (namespaceId == myTempNamespace)
2062 continue; /* do not look in temp namespace */
2064 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
2065 PointerGetDatum(template_name),
2066 ObjectIdGetDatum(namespaceId));
2067 if (OidIsValid(tmploid))
2072 if (!OidIsValid(tmploid) && !missing_ok)
2074 (errcode(ERRCODE_UNDEFINED_OBJECT),
2075 errmsg("text search template \"%s\" does not exist",
2076 NameListToString(names))));
2082 * TSTemplateIsVisible
2083 * Determine whether a template (identified by OID) is visible in the
2084 * current search path. Visible means "would be found by searching
2085 * for the unqualified template name".
2088 TSTemplateIsVisible(Oid tmplId)
2091 Form_pg_ts_template form;
2095 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2096 if (!HeapTupleIsValid(tup))
2097 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2098 form = (Form_pg_ts_template) GETSTRUCT(tup);
2100 recomputeNamespacePath();
2103 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2104 * the system namespace are surely in the path and so we needn't even do
2105 * list_member_oid() for them.
2107 namespace = form->tmplnamespace;
2108 if (namespace != PG_CATALOG_NAMESPACE &&
2109 !list_member_oid(activeSearchPath, namespace))
2114 * If it is in the path, it might still not be visible; it could be
2115 * hidden by another template of the same name earlier in the path. So
2116 * we must do a slow check for conflicting templates.
2118 char *name = NameStr(form->tmplname);
2122 foreach(l, activeSearchPath)
2124 Oid namespaceId = lfirst_oid(l);
2126 if (namespaceId == myTempNamespace)
2127 continue; /* do not look in temp namespace */
2129 if (namespaceId == namespace)
2131 /* Found it first in path */
2135 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2136 PointerGetDatum(name),
2137 ObjectIdGetDatum(namespaceId)))
2139 /* Found something else first in path */
2145 ReleaseSysCache(tup);
2151 * get_ts_config_oid - find a TS config by possibly qualified name
2153 * If not found, returns InvalidOid if missing_ok, else throws error
2156 get_ts_config_oid(List *names, bool missing_ok)
2161 Oid cfgoid = InvalidOid;
2164 /* deconstruct the name list */
2165 DeconstructQualifiedName(names, &schemaname, &config_name);
2169 /* use exact schema given */
2170 namespaceId = LookupExplicitNamespace(schemaname);
2171 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2172 PointerGetDatum(config_name),
2173 ObjectIdGetDatum(namespaceId));
2177 /* search for it in search path */
2178 recomputeNamespacePath();
2180 foreach(l, activeSearchPath)
2182 namespaceId = lfirst_oid(l);
2184 if (namespaceId == myTempNamespace)
2185 continue; /* do not look in temp namespace */
2187 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2188 PointerGetDatum(config_name),
2189 ObjectIdGetDatum(namespaceId));
2190 if (OidIsValid(cfgoid))
2195 if (!OidIsValid(cfgoid) && !missing_ok)
2197 (errcode(ERRCODE_UNDEFINED_OBJECT),
2198 errmsg("text search configuration \"%s\" does not exist",
2199 NameListToString(names))));
2206 * Determine whether a text search configuration (identified by OID)
2207 * is visible in the current search path. Visible means "would be found
2208 * by searching for the unqualified text search configuration name".
2211 TSConfigIsVisible(Oid cfgid)
2214 Form_pg_ts_config form;
2218 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2219 if (!HeapTupleIsValid(tup))
2220 elog(ERROR, "cache lookup failed for text search configuration %u",
2222 form = (Form_pg_ts_config) GETSTRUCT(tup);
2224 recomputeNamespacePath();
2227 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2228 * the system namespace are surely in the path and so we needn't even do
2229 * list_member_oid() for them.
2231 namespace = form->cfgnamespace;
2232 if (namespace != PG_CATALOG_NAMESPACE &&
2233 !list_member_oid(activeSearchPath, namespace))
2238 * If it is in the path, it might still not be visible; it could be
2239 * hidden by another configuration of the same name earlier in the
2240 * path. So we must do a slow check for conflicting configurations.
2242 char *name = NameStr(form->cfgname);
2246 foreach(l, activeSearchPath)
2248 Oid namespaceId = lfirst_oid(l);
2250 if (namespaceId == myTempNamespace)
2251 continue; /* do not look in temp namespace */
2253 if (namespaceId == namespace)
2255 /* Found it first in path */
2259 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2260 PointerGetDatum(name),
2261 ObjectIdGetDatum(namespaceId)))
2263 /* Found something else first in path */
2269 ReleaseSysCache(tup);
2276 * DeconstructQualifiedName
2277 * Given a possibly-qualified name expressed as a list of String nodes,
2278 * extract the schema name and object name.
2280 * *nspname_p is set to NULL if there is no explicit schema name.
2283 DeconstructQualifiedName(List *names,
2288 char *schemaname = NULL;
2289 char *objname = NULL;
2291 switch (list_length(names))
2294 objname = strVal(linitial(names));
2297 schemaname = strVal(linitial(names));
2298 objname = strVal(lsecond(names));
2301 catalogname = strVal(linitial(names));
2302 schemaname = strVal(lsecond(names));
2303 objname = strVal(lthird(names));
2306 * We check the catalog name and then ignore it.
2308 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2310 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2311 errmsg("cross-database references are not implemented: %s",
2312 NameListToString(names))));
2316 (errcode(ERRCODE_SYNTAX_ERROR),
2317 errmsg("improper qualified name (too many dotted names): %s",
2318 NameListToString(names))));
2322 *nspname_p = schemaname;
2323 *objname_p = objname;
2327 * LookupNamespaceNoError
2328 * Look up a schema name.
2330 * Returns the namespace OID, or InvalidOid if not found.
2332 * Note this does NOT perform any permissions check --- callers are
2333 * responsible for being sure that an appropriate check is made.
2334 * In the majority of cases LookupExplicitNamespace is preferable.
2337 LookupNamespaceNoError(const char *nspname)
2339 /* check for pg_temp alias */
2340 if (strcmp(nspname, "pg_temp") == 0)
2342 if (OidIsValid(myTempNamespace))
2343 return myTempNamespace;
2346 * Since this is used only for looking up existing objects, there is
2347 * no point in trying to initialize the temp namespace here; and doing
2348 * so might create problems for some callers. Just report "not found".
2353 return get_namespace_oid(nspname, true);
2357 * LookupExplicitNamespace
2358 * Process an explicitly-specified schema name: look up the schema
2359 * and verify we have USAGE (lookup) rights in it.
2361 * Returns the namespace OID. Raises ereport if any problem.
2364 LookupExplicitNamespace(const char *nspname)
2367 AclResult aclresult;
2369 /* check for pg_temp alias */
2370 if (strcmp(nspname, "pg_temp") == 0)
2372 if (OidIsValid(myTempNamespace))
2373 return myTempNamespace;
2376 * Since this is used only for looking up existing objects, there is
2377 * no point in trying to initialize the temp namespace here; and doing
2378 * so might create problems for some callers. Just fall through and
2379 * give the "does not exist" error.
2383 namespaceId = get_namespace_oid(nspname, false);
2385 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2386 if (aclresult != ACLCHECK_OK)
2387 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2394 * LookupCreationNamespace
2395 * Look up the schema and verify we have CREATE rights on it.
2397 * This is just like LookupExplicitNamespace except for the different
2398 * permission check, and that we are willing to create pg_temp if needed.
2400 * Note: calling this may result in a CommandCounterIncrement operation,
2401 * if we have to create or clean out the temp namespace.
2404 LookupCreationNamespace(const char *nspname)
2407 AclResult aclresult;
2409 /* check for pg_temp alias */
2410 if (strcmp(nspname, "pg_temp") == 0)
2412 /* Initialize temp namespace if first time through */
2413 if (!OidIsValid(myTempNamespace))
2414 InitTempTableNamespace();
2415 return myTempNamespace;
2418 namespaceId = get_namespace_oid(nspname, false);
2420 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2421 if (aclresult != ACLCHECK_OK)
2422 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2429 * Common checks on switching namespaces.
2431 * We complain if (1) the old and new namespaces are the same, (2) either the
2432 * old or new namespaces is a temporary schema (or temporary toast schema), or
2433 * (3) either the old or new namespaces is the TOAST schema.
2436 CheckSetNamespace(Oid oldNspOid, Oid nspOid, Oid classid, Oid objid)
2438 if (oldNspOid == nspOid)
2440 (classid == RelationRelationId ?
2441 errcode(ERRCODE_DUPLICATE_TABLE) :
2442 classid == ProcedureRelationId ?
2443 errcode(ERRCODE_DUPLICATE_FUNCTION) :
2444 errcode(ERRCODE_DUPLICATE_OBJECT),
2445 errmsg("%s is already in schema \"%s\"",
2446 getObjectDescriptionOids(classid, objid),
2447 get_namespace_name(nspOid))));
2449 /* disallow renaming into or out of temp schemas */
2450 if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2453 errmsg("cannot move objects into or out of temporary schemas")));
2455 /* same for TOAST schema */
2456 if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2458 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2459 errmsg("cannot move objects into or out of TOAST schema")));
2463 * QualifiedNameGetCreationNamespace
2464 * Given a possibly-qualified name for an object (in List-of-Values
2465 * format), determine what namespace the object should be created in.
2466 * Also extract and return the object name (last component of list).
2468 * Note: this does not apply any permissions check. Callers must check
2469 * for CREATE rights on the selected namespace when appropriate.
2471 * Note: calling this may result in a CommandCounterIncrement operation,
2472 * if we have to create or clean out the temp namespace.
2475 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2480 /* deconstruct the name list */
2481 DeconstructQualifiedName(names, &schemaname, objname_p);
2485 /* check for pg_temp alias */
2486 if (strcmp(schemaname, "pg_temp") == 0)
2488 /* Initialize temp namespace if first time through */
2489 if (!OidIsValid(myTempNamespace))
2490 InitTempTableNamespace();
2491 return myTempNamespace;
2493 /* use exact schema given */
2494 namespaceId = get_namespace_oid(schemaname, false);
2495 /* we do not check for USAGE rights here! */
2499 /* use the default creation namespace */
2500 recomputeNamespacePath();
2501 if (activeTempCreationPending)
2503 /* Need to initialize temp namespace */
2504 InitTempTableNamespace();
2505 return myTempNamespace;
2507 namespaceId = activeCreationNamespace;
2508 if (!OidIsValid(namespaceId))
2510 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2511 errmsg("no schema has been selected to create in")));
2518 * get_namespace_oid - given a namespace name, look up the OID
2520 * If missing_ok is false, throw an error if namespace name not found. If
2521 * true, just return InvalidOid.
2524 get_namespace_oid(const char *nspname, bool missing_ok)
2528 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2529 if (!OidIsValid(oid) && !missing_ok)
2531 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2532 errmsg("schema \"%s\" does not exist", nspname)));
2538 * makeRangeVarFromNameList
2539 * Utility routine to convert a qualified-name list into RangeVar form.
2542 makeRangeVarFromNameList(List *names)
2544 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2546 switch (list_length(names))
2549 rel->relname = strVal(linitial(names));
2552 rel->schemaname = strVal(linitial(names));
2553 rel->relname = strVal(lsecond(names));
2556 rel->catalogname = strVal(linitial(names));
2557 rel->schemaname = strVal(lsecond(names));
2558 rel->relname = strVal(lthird(names));
2562 (errcode(ERRCODE_SYNTAX_ERROR),
2563 errmsg("improper relation name (too many dotted names): %s",
2564 NameListToString(names))));
2573 * Utility routine to convert a qualified-name list into a string.
2575 * This is used primarily to form error messages, and so we do not quote
2576 * the list elements, for the sake of legibility.
2578 * In most scenarios the list elements should always be Value strings,
2579 * but we also allow A_Star for the convenience of ColumnRef processing.
2582 NameListToString(List *names)
2584 StringInfoData string;
2587 initStringInfo(&string);
2591 Node *name = (Node *) lfirst(l);
2593 if (l != list_head(names))
2594 appendStringInfoChar(&string, '.');
2596 if (IsA(name, String))
2597 appendStringInfoString(&string, strVal(name));
2598 else if (IsA(name, A_Star))
2599 appendStringInfoString(&string, "*");
2601 elog(ERROR, "unexpected node type in name list: %d",
2602 (int) nodeTag(name));
2609 * NameListToQuotedString
2610 * Utility routine to convert a qualified-name list into a string.
2612 * Same as above except that names will be double-quoted where necessary,
2613 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2616 NameListToQuotedString(List *names)
2618 StringInfoData string;
2621 initStringInfo(&string);
2625 if (l != list_head(names))
2626 appendStringInfoChar(&string, '.');
2627 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2634 * isTempNamespace - is the given namespace my temporary-table namespace?
2637 isTempNamespace(Oid namespaceId)
2639 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2645 * isTempToastNamespace - is the given namespace my temporary-toast-table
2649 isTempToastNamespace(Oid namespaceId)
2651 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2657 * isTempOrToastNamespace - is the given namespace my temporary-table
2658 * namespace or my temporary-toast-table namespace?
2661 isTempOrToastNamespace(Oid namespaceId)
2663 if (OidIsValid(myTempNamespace) &&
2664 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2670 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2671 * (either my own, or another backend's)? Temporary-toast-table namespaces
2672 * are included, too.
2675 isAnyTempNamespace(Oid namespaceId)
2680 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2681 nspname = get_namespace_name(namespaceId);
2683 return false; /* no such namespace? */
2684 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2685 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2691 * isOtherTempNamespace - is the given namespace some other backend's
2692 * temporary-table namespace (including temporary-toast-table namespaces)?
2694 * Note: for most purposes in the C code, this function is obsolete. Use
2695 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2698 isOtherTempNamespace(Oid namespaceId)
2700 /* If it's my own temp namespace, say "false" */
2701 if (isTempOrToastNamespace(namespaceId))
2703 /* Else, if it's any temp namespace, say "true" */
2704 return isAnyTempNamespace(namespaceId);
2708 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
2709 * namespace (either my own, or another backend's), return the BackendId
2710 * that owns it. Temporary-toast-table namespaces are included, too.
2711 * If it isn't a temp namespace, return InvalidBackendId.
2714 GetTempNamespaceBackendId(Oid namespaceId)
2719 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2720 nspname = get_namespace_name(namespaceId);
2722 return InvalidBackendId; /* no such namespace? */
2723 if (strncmp(nspname, "pg_temp_", 8) == 0)
2724 result = atoi(nspname + 8);
2725 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
2726 result = atoi(nspname + 14);
2728 result = InvalidBackendId;
2734 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
2735 * which must already be assigned. (This is only used when creating a toast
2736 * table for a temp table, so we must have already done InitTempTableNamespace)
2739 GetTempToastNamespace(void)
2741 Assert(OidIsValid(myTempToastNamespace));
2742 return myTempToastNamespace;
2747 * GetOverrideSearchPath - fetch current search path definition in form
2748 * used by PushOverrideSearchPath.
2750 * The result structure is allocated in the specified memory context
2751 * (which might or might not be equal to CurrentMemoryContext); but any
2752 * junk created by revalidation calculations will be in CurrentMemoryContext.
2754 OverrideSearchPath *
2755 GetOverrideSearchPath(MemoryContext context)
2757 OverrideSearchPath *result;
2759 MemoryContext oldcxt;
2761 recomputeNamespacePath();
2763 oldcxt = MemoryContextSwitchTo(context);
2765 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
2766 schemas = list_copy(activeSearchPath);
2767 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
2769 if (linitial_oid(schemas) == myTempNamespace)
2770 result->addTemp = true;
2773 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
2774 result->addCatalog = true;
2776 schemas = list_delete_first(schemas);
2778 result->schemas = schemas;
2780 MemoryContextSwitchTo(oldcxt);
2786 * PushOverrideSearchPath - temporarily override the search path
2788 * We allow nested overrides, hence the push/pop terminology. The GUC
2789 * search_path variable is ignored while an override is active.
2791 * It's possible that newpath->useTemp is set but there is no longer any
2792 * active temp namespace, if the path was saved during a transaction that
2793 * created a temp namespace and was later rolled back. In that case we just
2794 * ignore useTemp. A plausible alternative would be to create a new temp
2795 * namespace, but for existing callers that's not necessary because an empty
2796 * temp namespace wouldn't affect their results anyway.
2798 * It's also worth noting that other schemas listed in newpath might not
2799 * exist anymore either. We don't worry about this because OIDs that match
2800 * no existing namespace will simply not produce any hits during searches.
2803 PushOverrideSearchPath(OverrideSearchPath *newpath)
2805 OverrideStackEntry *entry;
2808 MemoryContext oldcxt;
2811 * Copy the list for safekeeping, and insert implicitly-searched
2812 * namespaces as needed. This code should track recomputeNamespacePath.
2814 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2816 oidlist = list_copy(newpath->schemas);
2819 * Remember the first member of the explicit list.
2822 firstNS = InvalidOid;
2824 firstNS = linitial_oid(oidlist);
2827 * Add any implicitly-searched namespaces to the list. Note these go on
2828 * the front, not the back; also notice that we do not check USAGE
2829 * permissions for these.
2831 if (newpath->addCatalog)
2832 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2834 if (newpath->addTemp && OidIsValid(myTempNamespace))
2835 oidlist = lcons_oid(myTempNamespace, oidlist);
2838 * Build the new stack entry, then insert it at the head of the list.
2840 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
2841 entry->searchPath = oidlist;
2842 entry->creationNamespace = firstNS;
2843 entry->nestLevel = GetCurrentTransactionNestLevel();
2845 overrideStack = lcons(entry, overrideStack);
2847 /* And make it active. */
2848 activeSearchPath = entry->searchPath;
2849 activeCreationNamespace = entry->creationNamespace;
2850 activeTempCreationPending = false; /* XXX is this OK? */
2852 MemoryContextSwitchTo(oldcxt);
2856 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
2858 * Any push during a (sub)transaction will be popped automatically at abort.
2859 * But it's caller error if a push isn't popped in normal control flow.
2862 PopOverrideSearchPath(void)
2864 OverrideStackEntry *entry;
2866 /* Sanity checks. */
2867 if (overrideStack == NIL)
2868 elog(ERROR, "bogus PopOverrideSearchPath call");
2869 entry = (OverrideStackEntry *) linitial(overrideStack);
2870 if (entry->nestLevel != GetCurrentTransactionNestLevel())
2871 elog(ERROR, "bogus PopOverrideSearchPath call");
2873 /* Pop the stack and free storage. */
2874 overrideStack = list_delete_first(overrideStack);
2875 list_free(entry->searchPath);
2878 /* Activate the next level down. */
2881 entry = (OverrideStackEntry *) linitial(overrideStack);
2882 activeSearchPath = entry->searchPath;
2883 activeCreationNamespace = entry->creationNamespace;
2884 activeTempCreationPending = false; /* XXX is this OK? */
2888 /* If not baseSearchPathValid, this is useless but harmless */
2889 activeSearchPath = baseSearchPath;
2890 activeCreationNamespace = baseCreationNamespace;
2891 activeTempCreationPending = baseTempCreationPending;
2897 * get_collation_oid - find a collation by possibly qualified name
2900 get_collation_oid(List *name, bool missing_ok)
2903 char *collation_name;
2905 Oid colloid = InvalidOid;
2909 encoding = GetDatabaseEncoding();
2911 /* deconstruct the name list */
2912 DeconstructQualifiedName(name, &schemaname, &collation_name);
2916 /* use exact schema given */
2917 namespaceId = LookupExplicitNamespace(schemaname);
2918 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
2919 PointerGetDatum(collation_name),
2920 Int32GetDatum(encoding),
2921 ObjectIdGetDatum(namespaceId));
2925 /* search for it in search path */
2926 recomputeNamespacePath();
2928 foreach(l, activeSearchPath)
2930 namespaceId = lfirst_oid(l);
2932 if (namespaceId == myTempNamespace)
2933 continue; /* do not look in temp namespace */
2935 colloid = GetSysCacheOid3(COLLNAMEENCNSP,
2936 PointerGetDatum(collation_name),
2937 Int32GetDatum(encoding),
2938 ObjectIdGetDatum(namespaceId));
2939 if (OidIsValid(colloid))
2944 /* Not found in path */
2945 if (!OidIsValid(colloid) && !missing_ok)
2947 (errcode(ERRCODE_UNDEFINED_OBJECT),
2948 errmsg("collation \"%s\" for current database encoding \"%s\" does not exist",
2949 NameListToString(name), GetDatabaseEncodingName())));
2954 * get_conversion_oid - find a conversion by possibly qualified name
2957 get_conversion_oid(List *name, bool missing_ok)
2960 char *conversion_name;
2962 Oid conoid = InvalidOid;
2965 /* deconstruct the name list */
2966 DeconstructQualifiedName(name, &schemaname, &conversion_name);
2970 /* use exact schema given */
2971 namespaceId = LookupExplicitNamespace(schemaname);
2972 conoid = GetSysCacheOid2(CONNAMENSP,
2973 PointerGetDatum(conversion_name),
2974 ObjectIdGetDatum(namespaceId));
2978 /* search for it in search path */
2979 recomputeNamespacePath();
2981 foreach(l, activeSearchPath)
2983 namespaceId = lfirst_oid(l);
2985 if (namespaceId == myTempNamespace)
2986 continue; /* do not look in temp namespace */
2988 conoid = GetSysCacheOid2(CONNAMENSP,
2989 PointerGetDatum(conversion_name),
2990 ObjectIdGetDatum(namespaceId));
2991 if (OidIsValid(conoid))
2996 /* Not found in path */
2997 if (!OidIsValid(conoid) && !missing_ok)
2999 (errcode(ERRCODE_UNDEFINED_OBJECT),
3000 errmsg("conversion \"%s\" does not exist",
3001 NameListToString(name))));
3006 * FindDefaultConversionProc - find default encoding conversion proc
3009 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
3014 recomputeNamespacePath();
3016 foreach(l, activeSearchPath)
3018 Oid namespaceId = lfirst_oid(l);
3020 if (namespaceId == myTempNamespace)
3021 continue; /* do not look in temp namespace */
3023 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3024 if (OidIsValid(proc))
3028 /* Not found in path */
3033 * recomputeNamespacePath - recompute path derived variables if needed.
3036 recomputeNamespacePath(void)
3038 Oid roleid = GetUserId();
3046 MemoryContext oldcxt;
3048 /* Do nothing if an override search spec is active. */
3052 /* Do nothing if path is already valid. */
3053 if (baseSearchPathValid && namespaceUser == roleid)
3056 /* Need a modifiable copy of namespace_search_path string */
3057 rawname = pstrdup(namespace_search_path);
3059 /* Parse string into list of identifiers */
3060 if (!SplitIdentifierString(rawname, ',', &namelist))
3062 /* syntax error in name list */
3063 /* this should not happen if GUC checked check_search_path */
3064 elog(ERROR, "invalid list syntax");
3068 * Convert the list of names to a list of OIDs. If any names are not
3069 * recognizable or we don't have read access, just leave them out of the
3070 * list. (We can't raise an error, since the search_path setting has
3071 * already been accepted.) Don't make duplicate entries, either.
3074 temp_missing = false;
3075 foreach(l, namelist)
3077 char *curname = (char *) lfirst(l);
3080 if (strcmp(curname, "$user") == 0)
3082 /* $user --- substitute namespace matching user name, if any */
3085 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3086 if (HeapTupleIsValid(tuple))
3090 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3091 namespaceId = get_namespace_oid(rname, true);
3092 ReleaseSysCache(tuple);
3093 if (OidIsValid(namespaceId) &&
3094 !list_member_oid(oidlist, namespaceId) &&
3095 pg_namespace_aclcheck(namespaceId, roleid,
3096 ACL_USAGE) == ACLCHECK_OK)
3097 oidlist = lappend_oid(oidlist, namespaceId);
3100 else if (strcmp(curname, "pg_temp") == 0)
3102 /* pg_temp --- substitute temp namespace, if any */
3103 if (OidIsValid(myTempNamespace))
3105 if (!list_member_oid(oidlist, myTempNamespace))
3106 oidlist = lappend_oid(oidlist, myTempNamespace);
3110 /* If it ought to be the creation namespace, set flag */
3112 temp_missing = true;
3117 /* normal namespace reference */
3118 namespaceId = get_namespace_oid(curname, true);
3119 if (OidIsValid(namespaceId) &&
3120 !list_member_oid(oidlist, namespaceId) &&
3121 pg_namespace_aclcheck(namespaceId, roleid,
3122 ACL_USAGE) == ACLCHECK_OK)
3123 oidlist = lappend_oid(oidlist, namespaceId);
3128 * Remember the first member of the explicit list. (Note: this is
3129 * nominally wrong if temp_missing, but we need it anyway to distinguish
3130 * explicit from implicit mention of pg_catalog.)
3133 firstNS = InvalidOid;
3135 firstNS = linitial_oid(oidlist);
3138 * Add any implicitly-searched namespaces to the list. Note these go on
3139 * the front, not the back; also notice that we do not check USAGE
3140 * permissions for these.
3142 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3143 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3145 if (OidIsValid(myTempNamespace) &&
3146 !list_member_oid(oidlist, myTempNamespace))
3147 oidlist = lcons_oid(myTempNamespace, oidlist);
3150 * Now that we've successfully built the new list of namespace OIDs, save
3151 * it in permanent storage.
3153 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3154 newpath = list_copy(oidlist);
3155 MemoryContextSwitchTo(oldcxt);
3157 /* Now safe to assign to state variables. */
3158 list_free(baseSearchPath);
3159 baseSearchPath = newpath;
3160 baseCreationNamespace = firstNS;
3161 baseTempCreationPending = temp_missing;
3163 /* Mark the path valid. */
3164 baseSearchPathValid = true;
3165 namespaceUser = roleid;
3167 /* And make it active. */
3168 activeSearchPath = baseSearchPath;
3169 activeCreationNamespace = baseCreationNamespace;
3170 activeTempCreationPending = baseTempCreationPending;
3174 list_free(namelist);
3179 * InitTempTableNamespace
3180 * Initialize temp table namespace on first use in a particular backend
3183 InitTempTableNamespace(void)
3185 char namespaceName[NAMEDATALEN];
3189 Assert(!OidIsValid(myTempNamespace));
3192 * First, do permission check to see if we are authorized to make temp
3193 * tables. We use a nonstandard error message here since "databasename:
3194 * permission denied" might be a tad cryptic.
3196 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3197 * that's necessary since current user ID could change during the session.
3198 * But there's no need to make the namespace in the first place until a
3199 * temp table creation request is made by someone with appropriate rights.
3201 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3202 ACL_CREATE_TEMP) != ACLCHECK_OK)
3204 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3205 errmsg("permission denied to create temporary tables in database \"%s\"",
3206 get_database_name(MyDatabaseId))));
3209 * Do not allow a Hot Standby slave session to make temp tables. Aside
3210 * from problems with modifying the system catalogs, there is a naming
3211 * conflict: pg_temp_N belongs to the session with BackendId N on the
3212 * master, not to a slave session with the same BackendId. We should not
3213 * be able to get here anyway due to XactReadOnly checks, but let's just
3214 * make real sure. Note that this also backstops various operations that
3215 * allow XactReadOnly transactions to modify temp tables; they'd need
3216 * RecoveryInProgress checks if not for this.
3218 if (RecoveryInProgress())
3220 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3221 errmsg("cannot create temporary tables during recovery")));
3223 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3225 namespaceId = get_namespace_oid(namespaceName, true);
3226 if (!OidIsValid(namespaceId))
3229 * First use of this temp namespace in this database; create it. The
3230 * temp namespaces are always owned by the superuser. We leave their
3231 * permissions at default --- i.e., no access except to superuser ---
3232 * to ensure that unprivileged users can't peek at other backends'
3233 * temp tables. This works because the places that access the temp
3234 * namespace for my own backend skip permissions checks on it.
3236 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3237 /* Advance command counter to make namespace visible */
3238 CommandCounterIncrement();
3243 * If the namespace already exists, clean it out (in case the former
3244 * owner crashed without doing so).
3246 RemoveTempRelations(namespaceId);
3250 * If the corresponding toast-table namespace doesn't exist yet, create
3251 * it. (We assume there is no need to clean it out if it does exist, since
3252 * dropping a parent table should make its toast table go away.)
3254 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3257 toastspaceId = get_namespace_oid(namespaceName, true);
3258 if (!OidIsValid(toastspaceId))
3260 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3261 /* Advance command counter to make namespace visible */
3262 CommandCounterIncrement();
3266 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3267 * so all our work could be undone by transaction rollback. Set flag for
3268 * AtEOXact_Namespace to know what to do.
3270 myTempNamespace = namespaceId;
3271 myTempToastNamespace = toastspaceId;
3273 /* It should not be done already. */
3274 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3275 myTempNamespaceSubID = GetCurrentSubTransactionId();
3277 baseSearchPathValid = false; /* need to rebuild list */
3281 * End-of-transaction cleanup for namespaces.
3284 AtEOXact_Namespace(bool isCommit)
3287 * If we abort the transaction in which a temp namespace was selected,
3288 * we'll have to do any creation or cleanout work over again. So, just
3289 * forget the namespace entirely until next time. On the other hand, if
3290 * we commit then register an exit callback to clean out the temp tables
3291 * at backend shutdown. (We only want to register the callback once per
3292 * session, so this is a good place to do it.)
3294 if (myTempNamespaceSubID != InvalidSubTransactionId)
3297 on_shmem_exit(RemoveTempRelationsCallback, 0);
3300 myTempNamespace = InvalidOid;
3301 myTempToastNamespace = InvalidOid;
3302 baseSearchPathValid = false; /* need to rebuild list */
3304 myTempNamespaceSubID = InvalidSubTransactionId;
3308 * Clean up if someone failed to do PopOverrideSearchPath
3313 elog(WARNING, "leaked override search path");
3314 while (overrideStack)
3316 OverrideStackEntry *entry;
3318 entry = (OverrideStackEntry *) linitial(overrideStack);
3319 overrideStack = list_delete_first(overrideStack);
3320 list_free(entry->searchPath);
3323 /* If not baseSearchPathValid, this is useless but harmless */
3324 activeSearchPath = baseSearchPath;
3325 activeCreationNamespace = baseCreationNamespace;
3326 activeTempCreationPending = baseTempCreationPending;
3331 * AtEOSubXact_Namespace
3333 * At subtransaction commit, propagate the temp-namespace-creation
3334 * flag to the parent subtransaction.
3336 * At subtransaction abort, forget the flag if we set it up.
3339 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3340 SubTransactionId parentSubid)
3342 OverrideStackEntry *entry;
3344 if (myTempNamespaceSubID == mySubid)
3347 myTempNamespaceSubID = parentSubid;
3350 myTempNamespaceSubID = InvalidSubTransactionId;
3351 /* TEMP namespace creation failed, so reset state */
3352 myTempNamespace = InvalidOid;
3353 myTempToastNamespace = InvalidOid;
3354 baseSearchPathValid = false; /* need to rebuild list */
3359 * Clean up if someone failed to do PopOverrideSearchPath
3361 while (overrideStack)
3363 entry = (OverrideStackEntry *) linitial(overrideStack);
3364 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3367 elog(WARNING, "leaked override search path");
3368 overrideStack = list_delete_first(overrideStack);
3369 list_free(entry->searchPath);
3373 /* Activate the next level down. */
3376 entry = (OverrideStackEntry *) linitial(overrideStack);
3377 activeSearchPath = entry->searchPath;
3378 activeCreationNamespace = entry->creationNamespace;
3379 activeTempCreationPending = false; /* XXX is this OK? */
3383 /* If not baseSearchPathValid, this is useless but harmless */
3384 activeSearchPath = baseSearchPath;
3385 activeCreationNamespace = baseCreationNamespace;
3386 activeTempCreationPending = baseTempCreationPending;
3391 * Remove all relations in the specified temp namespace.
3393 * This is called at backend shutdown (if we made any temp relations).
3394 * It is also called when we begin using a pre-existing temp namespace,
3395 * in order to clean out any relations that might have been created by
3396 * a crashed backend.
3399 RemoveTempRelations(Oid tempNamespaceId)
3401 ObjectAddress object;
3404 * We want to get rid of everything in the target namespace, but not the
3405 * namespace itself (deleting it only to recreate it later would be a
3406 * waste of cycles). We do this by finding everything that has a
3407 * dependency on the namespace.
3409 object.classId = NamespaceRelationId;
3410 object.objectId = tempNamespaceId;
3411 object.objectSubId = 0;
3413 deleteWhatDependsOn(&object, false);
3417 * Callback to remove temp relations at backend exit.
3420 RemoveTempRelationsCallback(int code, Datum arg)
3422 if (OidIsValid(myTempNamespace)) /* should always be true */
3424 /* Need to ensure we have a usable transaction. */
3425 AbortOutOfAnyTransaction();
3426 StartTransactionCommand();
3428 RemoveTempRelations(myTempNamespace);
3430 CommitTransactionCommand();
3435 * Remove all temp tables from the temporary namespace.
3438 ResetTempTableNamespace(void)
3440 if (OidIsValid(myTempNamespace))
3441 RemoveTempRelations(myTempNamespace);
3446 * Routines for handling the GUC variable 'search_path'.
3449 /* assign_hook: validate new search_path, do extra actions as needed */
3451 assign_search_path(const char *newval, bool doit, GucSource source)
3457 /* Need a modifiable copy of string */
3458 rawname = pstrdup(newval);
3460 /* Parse string into list of identifiers */
3461 if (!SplitIdentifierString(rawname, ',', &namelist))
3463 /* syntax error in name list */
3465 list_free(namelist);
3470 * If we aren't inside a transaction, we cannot do database access so
3471 * cannot verify the individual names. Must accept the list on faith.
3473 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3476 * Verify that all the names are either valid namespace names or
3477 * "$user" or "pg_temp". We do not require $user to correspond to a
3478 * valid namespace, and pg_temp might not exist yet. We do not check
3479 * for USAGE rights, either; should we?
3481 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3482 * DATABASE SET or ALTER USER SET command. It could be that the
3483 * intended use of the search path is for some other database, so we
3484 * should not error out if it mentions schemas not present in the
3485 * current database. We reduce the message to NOTICE instead.
3487 foreach(l, namelist)
3489 char *curname = (char *) lfirst(l);
3491 if (strcmp(curname, "$user") == 0)
3493 if (strcmp(curname, "pg_temp") == 0)
3495 if (!SearchSysCacheExists1(NAMESPACENAME,
3496 CStringGetDatum(curname)))
3497 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3498 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3499 errmsg("schema \"%s\" does not exist", curname)));
3504 list_free(namelist);
3507 * We mark the path as needing recomputation, but don't do anything until
3508 * it's needed. This avoids trying to do database access during GUC
3512 baseSearchPathValid = false;
3518 * InitializeSearchPath: initialize module during InitPostgres.
3520 * This is called after we are up enough to be able to do catalog lookups.
3523 InitializeSearchPath(void)
3525 if (IsBootstrapProcessingMode())
3528 * In bootstrap mode, the search path must be 'pg_catalog' so that
3529 * tables are created in the proper namespace; ignore the GUC setting.
3531 MemoryContext oldcxt;
3533 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3534 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3535 MemoryContextSwitchTo(oldcxt);
3536 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3537 baseTempCreationPending = false;
3538 baseSearchPathValid = true;
3539 namespaceUser = GetUserId();
3540 activeSearchPath = baseSearchPath;
3541 activeCreationNamespace = baseCreationNamespace;
3542 activeTempCreationPending = baseTempCreationPending;
3547 * In normal mode, arrange for a callback on any syscache invalidation
3548 * of pg_namespace rows.
3550 CacheRegisterSyscacheCallback(NAMESPACEOID,
3553 /* Force search path to be recomputed on next use */
3554 baseSearchPathValid = false;
3560 * Syscache inval callback function
3563 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3565 /* Force search path to be recomputed on next use */
3566 baseSearchPathValid = false;
3570 * Fetch the active search path. The return value is a palloc'ed list
3571 * of OIDs; the caller is responsible for freeing this storage as
3574 * The returned list includes the implicitly-prepended namespaces only if
3575 * includeImplicit is true.
3577 * Note: calling this may result in a CommandCounterIncrement operation,
3578 * if we have to create or clean out the temp namespace.
3581 fetch_search_path(bool includeImplicit)
3585 recomputeNamespacePath();
3588 * If the temp namespace should be first, force it to exist. This is so
3589 * that callers can trust the result to reflect the actual default
3590 * creation namespace. It's a bit bogus to do this here, since
3591 * current_schema() is supposedly a stable function without side-effects,
3592 * but the alternatives seem worse.
3594 if (activeTempCreationPending)
3596 InitTempTableNamespace();
3597 recomputeNamespacePath();
3600 result = list_copy(activeSearchPath);
3601 if (!includeImplicit)
3603 while (result && linitial_oid(result) != activeCreationNamespace)
3604 result = list_delete_first(result);
3611 * Fetch the active search path into a caller-allocated array of OIDs.
3612 * Returns the number of path entries. (If this is more than sarray_len,
3613 * then the data didn't fit and is not all stored.)
3615 * The returned list always includes the implicitly-prepended namespaces,
3616 * but never includes the temp namespace. (This is suitable for existing
3617 * users, which would want to ignore the temp namespace anyway.) This
3618 * definition allows us to not worry about initializing the temp namespace.
3621 fetch_search_path_array(Oid *sarray, int sarray_len)
3626 recomputeNamespacePath();
3628 foreach(l, activeSearchPath)
3630 Oid namespaceId = lfirst_oid(l);
3632 if (namespaceId == myTempNamespace)
3633 continue; /* do not include temp namespace */
3635 if (count < sarray_len)
3636 sarray[count] = namespaceId;
3645 * Export the FooIsVisible functions as SQL-callable functions.
3647 * Note: as of Postgres 8.4, these will silently return NULL if called on
3648 * a nonexistent object OID, rather than failing. This is to avoid race
3649 * condition errors when a query that's scanning a catalog using an MVCC
3650 * snapshot uses one of these functions. The underlying IsVisible functions
3651 * operate on SnapshotNow semantics and so might see the object as already
3652 * gone when it's still visible to the MVCC snapshot. (There is no race
3653 * condition in the current coding because we don't accept sinval messages
3654 * between the SearchSysCacheExists test and the subsequent lookup.)
3658 pg_table_is_visible(PG_FUNCTION_ARGS)
3660 Oid oid = PG_GETARG_OID(0);
3662 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3665 PG_RETURN_BOOL(RelationIsVisible(oid));
3669 pg_type_is_visible(PG_FUNCTION_ARGS)
3671 Oid oid = PG_GETARG_OID(0);
3673 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3676 PG_RETURN_BOOL(TypeIsVisible(oid));
3680 pg_function_is_visible(PG_FUNCTION_ARGS)
3682 Oid oid = PG_GETARG_OID(0);
3684 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3687 PG_RETURN_BOOL(FunctionIsVisible(oid));
3691 pg_operator_is_visible(PG_FUNCTION_ARGS)
3693 Oid oid = PG_GETARG_OID(0);
3695 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3698 PG_RETURN_BOOL(OperatorIsVisible(oid));
3702 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3704 Oid oid = PG_GETARG_OID(0);
3706 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3709 PG_RETURN_BOOL(OpclassIsVisible(oid));
3713 pg_collation_is_visible(PG_FUNCTION_ARGS)
3715 Oid oid = PG_GETARG_OID(0);
3717 if (!SearchSysCacheExists1(COLLOID, ObjectIdGetDatum(oid)))
3720 PG_RETURN_BOOL(CollationIsVisible(oid));
3724 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3726 Oid oid = PG_GETARG_OID(0);
3728 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3731 PG_RETURN_BOOL(ConversionIsVisible(oid));
3735 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3737 Oid oid = PG_GETARG_OID(0);
3739 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3742 PG_RETURN_BOOL(TSParserIsVisible(oid));
3746 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3748 Oid oid = PG_GETARG_OID(0);
3750 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3753 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3757 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3759 Oid oid = PG_GETARG_OID(0);
3761 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3764 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3768 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3770 Oid oid = PG_GETARG_OID(0);
3772 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3775 PG_RETURN_BOOL(TSConfigIsVisible(oid));
3779 pg_my_temp_schema(PG_FUNCTION_ARGS)
3781 PG_RETURN_OID(myTempNamespace);
3785 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3787 Oid oid = PG_GETARG_OID(0);
3789 PG_RETURN_BOOL(isOtherTempNamespace(oid));