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-2010, 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_conversion.h"
27 #include "catalog/pg_conversion_fn.h"
28 #include "catalog/pg_namespace.h"
29 #include "catalog/pg_opclass.h"
30 #include "catalog/pg_operator.h"
31 #include "catalog/pg_opfamily.h"
32 #include "catalog/pg_proc.h"
33 #include "catalog/pg_ts_config.h"
34 #include "catalog/pg_ts_dict.h"
35 #include "catalog/pg_ts_parser.h"
36 #include "catalog/pg_ts_template.h"
37 #include "catalog/pg_type.h"
38 #include "commands/dbcommands.h"
40 #include "miscadmin.h"
41 #include "nodes/makefuncs.h"
42 #include "parser/parse_func.h"
43 #include "storage/backendid.h"
44 #include "storage/ipc.h"
45 #include "utils/acl.h"
46 #include "utils/builtins.h"
47 #include "utils/guc.h"
48 #include "utils/inval.h"
49 #include "utils/lsyscache.h"
50 #include "utils/memutils.h"
51 #include "utils/rel.h"
52 #include "utils/syscache.h"
56 * The namespace search path is a possibly-empty list of namespace OIDs.
57 * In addition to the explicit list, implicitly-searched namespaces
60 * 1. If a TEMP table namespace has been initialized in this session, it
61 * is implicitly searched first. (The only time this doesn't happen is
62 * when we are obeying an override search path spec that says not to use the
63 * temp namespace, or the temp namespace is included in the explicit list.)
65 * 2. The system catalog namespace is always searched. If the system
66 * namespace is present in the explicit path then it will be searched in
67 * the specified order; otherwise it will be searched after TEMP tables and
68 * *before* the explicit list. (It might seem that the system namespace
69 * should be implicitly last, but this behavior appears to be required by
70 * SQL99. Also, this provides a way to search the system namespace first
71 * without thereby making it the default creation target namespace.)
73 * For security reasons, searches using the search path will ignore the temp
74 * namespace when searching for any object type other than relations and
75 * types. (We must allow types since temp tables have rowtypes.)
77 * The default creation target namespace is always the first element of the
78 * explicit list. If the explicit list is empty, there is no default target.
80 * The textual specification of search_path can include "$user" to refer to
81 * the namespace named the same as the current user, if any. (This is just
82 * ignored if there is no such namespace.) Also, it can include "pg_temp"
83 * to refer to the current backend's temp namespace. This is usually also
84 * ignorable if the temp namespace hasn't been set up, but there's a special
85 * case: if "pg_temp" appears first then it should be the default creation
86 * target. We kluge this case a little bit so that the temp namespace isn't
87 * set up until the first attempt to create something in it. (The reason for
88 * klugery is that we can't create the temp namespace outside a transaction,
89 * but initial GUC processing of search_path happens outside a transaction.)
90 * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
91 * but is not reflected in activeCreationNamespace because the namespace isn't
94 * In bootstrap mode, the search path is set equal to "pg_catalog", so that
95 * the system namespace is the only one searched or inserted into.
96 * initdb is also careful to set search_path to "pg_catalog" for its
97 * post-bootstrap standalone backend runs. Otherwise the default search
98 * path is determined by GUC. The factory default path contains the PUBLIC
99 * namespace (if it exists), preceded by the user's personal namespace
102 * We support a stack of "override" search path settings for use within
103 * specific sections of backend code. namespace_search_path is ignored
104 * whenever the override stack is nonempty. activeSearchPath is always
105 * the actually active path; it points either to the search list of the
106 * topmost stack entry, or to baseSearchPath which is the list derived
107 * from namespace_search_path.
109 * If baseSearchPathValid is false, then baseSearchPath (and other
110 * derived variables) need to be recomputed from namespace_search_path.
111 * We mark it invalid upon an assignment to namespace_search_path or receipt
112 * of a syscache invalidation event for pg_namespace. The recomputation
113 * is done during the next non-overridden lookup attempt. Note that an
114 * override spec is never subject to recomputation.
116 * Any namespaces mentioned in namespace_search_path that are not readable
117 * by the current user ID are simply left out of baseSearchPath; so
118 * we have to be willing to recompute the path when current userid changes.
119 * namespaceUser is the userid the path has been computed for.
121 * Note: all data pointed to by these List variables is in TopMemoryContext.
124 /* These variables define the actually active state: */
126 static List *activeSearchPath = NIL;
128 /* default place to create stuff; if InvalidOid, no default */
129 static Oid activeCreationNamespace = InvalidOid;
131 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
132 static bool activeTempCreationPending = false;
134 /* These variables are the values last derived from namespace_search_path: */
136 static List *baseSearchPath = NIL;
138 static Oid baseCreationNamespace = InvalidOid;
140 static bool baseTempCreationPending = false;
142 static Oid namespaceUser = InvalidOid;
144 /* The above four values are valid only if baseSearchPathValid */
145 static bool baseSearchPathValid = true;
147 /* Override requests are remembered in a stack of OverrideStackEntry structs */
151 List *searchPath; /* the desired search path */
152 Oid creationNamespace; /* the desired creation namespace */
153 int nestLevel; /* subtransaction nesting level */
154 } OverrideStackEntry;
156 static List *overrideStack = NIL;
159 * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
160 * in a particular backend session (this happens when a CREATE TEMP TABLE
161 * command is first executed). Thereafter it's the OID of the temp namespace.
163 * myTempToastNamespace is the OID of the namespace for my temp tables' toast
164 * tables. It is set when myTempNamespace is, and is InvalidOid before that.
166 * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
167 * current subtransaction. The flag propagates up the subtransaction tree,
168 * so the main transaction will correctly recognize the flag if all
169 * intermediate subtransactions commit. When it is InvalidSubTransactionId,
170 * we either haven't made the TEMP namespace yet, or have successfully
171 * committed its creation, depending on whether myTempNamespace is valid.
173 static Oid myTempNamespace = InvalidOid;
175 static Oid myTempToastNamespace = InvalidOid;
177 static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
180 * This is the user's textual search path specification --- it's the value
181 * of the GUC variable 'search_path'.
183 char *namespace_search_path = NULL;
186 /* Local functions */
187 static void recomputeNamespacePath(void);
188 static void InitTempTableNamespace(void);
189 static void RemoveTempRelations(Oid tempNamespaceId);
190 static void RemoveTempRelationsCallback(int code, Datum arg);
191 static void NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr);
192 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
195 /* These don't really need to appear in any header file */
196 Datum pg_table_is_visible(PG_FUNCTION_ARGS);
197 Datum pg_type_is_visible(PG_FUNCTION_ARGS);
198 Datum pg_function_is_visible(PG_FUNCTION_ARGS);
199 Datum pg_operator_is_visible(PG_FUNCTION_ARGS);
200 Datum pg_opclass_is_visible(PG_FUNCTION_ARGS);
201 Datum pg_conversion_is_visible(PG_FUNCTION_ARGS);
202 Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS);
203 Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS);
204 Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS);
205 Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS);
206 Datum pg_my_temp_schema(PG_FUNCTION_ARGS);
207 Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS);
212 * Given a RangeVar describing an existing relation,
213 * select the proper namespace and look up the relation OID.
215 * If the relation is not found, return InvalidOid if failOK = true,
216 * otherwise raise an error.
219 RangeVarGetRelid(const RangeVar *relation, bool failOK)
225 * We check the catalog name and then ignore it.
227 if (relation->catalogname)
229 if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
231 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
232 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
233 relation->catalogname, relation->schemaname,
234 relation->relname)));
238 * If istemp is set, this is a reference to a temp relation. The parser
239 * never generates such a RangeVar in simple DML, but it can happen in
240 * contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY KEY)". Such a
241 * command will generate an added CREATE INDEX operation, which must be
242 * careful to find the temp table, even when pg_temp is not first in the
245 if (relation->istemp)
247 if (relation->schemaname)
249 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
250 errmsg("temporary tables cannot specify a schema name")));
251 if (OidIsValid(myTempNamespace))
252 relId = get_relname_relid(relation->relname, myTempNamespace);
253 else /* this probably can't happen? */
256 else if (relation->schemaname)
258 /* use exact schema given */
259 namespaceId = LookupExplicitNamespace(relation->schemaname);
260 relId = get_relname_relid(relation->relname, namespaceId);
264 /* search the namespace path */
265 relId = RelnameGetRelid(relation->relname);
268 if (!OidIsValid(relId) && !failOK)
270 if (relation->schemaname)
272 (errcode(ERRCODE_UNDEFINED_TABLE),
273 errmsg("relation \"%s.%s\" does not exist",
274 relation->schemaname, relation->relname)));
277 (errcode(ERRCODE_UNDEFINED_TABLE),
278 errmsg("relation \"%s\" does not exist",
279 relation->relname)));
285 * RangeVarGetCreationNamespace
286 * Given a RangeVar describing a to-be-created relation,
287 * choose which namespace to create it in.
289 * Note: calling this may result in a CommandCounterIncrement operation.
290 * That will happen on the first request for a temp table in any particular
291 * backend run; we will need to either create or clean out the temp schema.
294 RangeVarGetCreationNamespace(const RangeVar *newRelation)
299 * We check the catalog name and then ignore it.
301 if (newRelation->catalogname)
303 if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
305 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
306 errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
307 newRelation->catalogname, newRelation->schemaname,
308 newRelation->relname)));
311 if (newRelation->istemp)
313 /* TEMP tables are created in our backend-local temp namespace */
314 if (newRelation->schemaname)
316 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
317 errmsg("temporary tables cannot specify a schema name")));
318 /* Initialize temp namespace if first time through */
319 if (!OidIsValid(myTempNamespace))
320 InitTempTableNamespace();
321 return myTempNamespace;
324 if (newRelation->schemaname)
326 /* check for pg_temp alias */
327 if (strcmp(newRelation->schemaname, "pg_temp") == 0)
329 /* Initialize temp namespace if first time through */
330 if (!OidIsValid(myTempNamespace))
331 InitTempTableNamespace();
332 return myTempNamespace;
334 /* use exact schema given */
335 namespaceId = get_namespace_oid(newRelation->schemaname, false);
336 /* we do not check for USAGE rights here! */
340 /* use the default creation namespace */
341 recomputeNamespacePath();
342 if (activeTempCreationPending)
344 /* Need to initialize temp namespace */
345 InitTempTableNamespace();
346 return myTempNamespace;
348 namespaceId = activeCreationNamespace;
349 if (!OidIsValid(namespaceId))
351 (errcode(ERRCODE_UNDEFINED_SCHEMA),
352 errmsg("no schema has been selected to create in")));
355 /* Note: callers will check for CREATE rights when appropriate */
362 * Try to resolve an unqualified relation name.
363 * Returns OID if relation found in search path, else InvalidOid.
366 RelnameGetRelid(const char *relname)
371 recomputeNamespacePath();
373 foreach(l, activeSearchPath)
375 Oid namespaceId = lfirst_oid(l);
377 relid = get_relname_relid(relname, namespaceId);
378 if (OidIsValid(relid))
382 /* Not found in path */
389 * Determine whether a relation (identified by OID) is visible in the
390 * current search path. Visible means "would be found by searching
391 * for the unqualified relation name".
394 RelationIsVisible(Oid relid)
397 Form_pg_class relform;
401 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
402 if (!HeapTupleIsValid(reltup))
403 elog(ERROR, "cache lookup failed for relation %u", relid);
404 relform = (Form_pg_class) GETSTRUCT(reltup);
406 recomputeNamespacePath();
409 * Quick check: if it ain't in the path at all, it ain't visible. Items in
410 * the system namespace are surely in the path and so we needn't even do
411 * list_member_oid() for them.
413 relnamespace = relform->relnamespace;
414 if (relnamespace != PG_CATALOG_NAMESPACE &&
415 !list_member_oid(activeSearchPath, relnamespace))
420 * If it is in the path, it might still not be visible; it could be
421 * hidden by another relation of the same name earlier in the path. So
422 * we must do a slow check for conflicting relations.
424 char *relname = NameStr(relform->relname);
428 foreach(l, activeSearchPath)
430 Oid namespaceId = lfirst_oid(l);
432 if (namespaceId == relnamespace)
434 /* Found it first in path */
438 if (OidIsValid(get_relname_relid(relname, namespaceId)))
440 /* Found something else first in path */
446 ReleaseSysCache(reltup);
454 * Try to resolve an unqualified datatype name.
455 * Returns OID if type found in search path, else InvalidOid.
457 * This is essentially the same as RelnameGetRelid.
460 TypenameGetTypid(const char *typname)
465 recomputeNamespacePath();
467 foreach(l, activeSearchPath)
469 Oid namespaceId = lfirst_oid(l);
471 typid = GetSysCacheOid2(TYPENAMENSP,
472 PointerGetDatum(typname),
473 ObjectIdGetDatum(namespaceId));
474 if (OidIsValid(typid))
478 /* Not found in path */
484 * Determine whether a type (identified by OID) is visible in the
485 * current search path. Visible means "would be found by searching
486 * for the unqualified type name".
489 TypeIsVisible(Oid typid)
492 Form_pg_type typform;
496 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
497 if (!HeapTupleIsValid(typtup))
498 elog(ERROR, "cache lookup failed for type %u", typid);
499 typform = (Form_pg_type) GETSTRUCT(typtup);
501 recomputeNamespacePath();
504 * Quick check: if it ain't in the path at all, it ain't visible. Items in
505 * the system namespace are surely in the path and so we needn't even do
506 * list_member_oid() for them.
508 typnamespace = typform->typnamespace;
509 if (typnamespace != PG_CATALOG_NAMESPACE &&
510 !list_member_oid(activeSearchPath, typnamespace))
515 * If it is in the path, it might still not be visible; it could be
516 * hidden by another type of the same name earlier in the path. So we
517 * must do a slow check for conflicting types.
519 char *typname = NameStr(typform->typname);
523 foreach(l, activeSearchPath)
525 Oid namespaceId = lfirst_oid(l);
527 if (namespaceId == typnamespace)
529 /* Found it first in path */
533 if (SearchSysCacheExists2(TYPENAMENSP,
534 PointerGetDatum(typname),
535 ObjectIdGetDatum(namespaceId)))
537 /* Found something else first in path */
543 ReleaseSysCache(typtup);
550 * FuncnameGetCandidates
551 * Given a possibly-qualified function name and argument count,
552 * retrieve a list of the possible matches.
554 * If nargs is -1, we return all functions matching the given name,
555 * regardless of argument count. (argnames must be NIL, and expand_variadic
556 * and expand_defaults must be false, in this case.)
558 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
559 * and only functions having all the listed argument names will be returned.
560 * (We assume that length(argnames) <= nargs and all the passed-in names are
561 * distinct.) The returned structs will include an argnumbers array showing
562 * the actual argument index for each logical argument position.
564 * If expand_variadic is true, then variadic functions having the same number
565 * or fewer arguments will be retrieved, with the variadic argument and any
566 * additional argument positions filled with the variadic element type.
567 * nvargs in the returned struct is set to the number of such arguments.
568 * If expand_variadic is false, variadic arguments are not treated specially,
569 * and the returned nvargs will always be zero.
571 * If expand_defaults is true, functions that could match after insertion of
572 * default argument values will also be retrieved. In this case the returned
573 * structs could have nargs > passed-in nargs, and ndargs is set to the number
574 * of additional args (which can be retrieved from the function's
575 * proargdefaults entry).
577 * It is not possible for nvargs and ndargs to both be nonzero in the same
578 * list entry, since default insertion allows matches to functions with more
579 * than nargs arguments while the variadic transformation requires the same
582 * When argnames isn't NIL, the returned args[] type arrays are not ordered
583 * according to the functions' declarations, but rather according to the call:
584 * first any positional arguments, then the named arguments, then defaulted
585 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
586 * array can be used to map this back to the catalog information.
587 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
589 * We search a single namespace if the function name is qualified, else
590 * all namespaces in the search path. In the multiple-namespace case,
591 * we arrange for entries in earlier namespaces to mask identical entries in
594 * When expanding variadics, we arrange for non-variadic functions to mask
595 * variadic ones if the expanded argument list is the same. It is still
596 * possible for there to be conflicts between different variadic functions,
599 * It is guaranteed that the return list will never contain multiple entries
600 * with identical argument lists. When expand_defaults is true, the entries
601 * could have more than nargs positions, but we still guarantee that they are
602 * distinct in the first nargs positions. However, if argnames isn't NIL or
603 * either expand_variadic or expand_defaults is true, there might be multiple
604 * candidate functions that expand to identical argument lists. Rather than
605 * throw error here, we report such situations by returning a single entry
606 * with oid = 0 that represents a set of such conflicting candidates.
607 * The caller might end up discarding such an entry anyway, but if it selects
608 * such an entry it should react as though the call were ambiguous.
611 FuncnameGetCandidates(List *names, int nargs, List *argnames,
612 bool expand_variadic, bool expand_defaults)
614 FuncCandidateList resultList = NULL;
615 bool any_special = false;
622 /* check for caller error */
623 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
625 /* deconstruct the name list */
626 DeconstructQualifiedName(names, &schemaname, &funcname);
630 /* use exact schema given */
631 namespaceId = LookupExplicitNamespace(schemaname);
635 /* flag to indicate we need namespace search */
636 namespaceId = InvalidOid;
637 recomputeNamespacePath();
640 /* Search syscache by name only */
641 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
643 for (i = 0; i < catlist->n_members; i++)
645 HeapTuple proctup = &catlist->members[i]->tuple;
646 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
647 int pronargs = procform->pronargs;
653 int *argnumbers = NULL;
654 FuncCandidateList newResult;
656 if (OidIsValid(namespaceId))
658 /* Consider only procs in specified namespace */
659 if (procform->pronamespace != namespaceId)
665 * Consider only procs that are in the search path and are not in
666 * the temp namespace.
670 foreach(nsp, activeSearchPath)
672 if (procform->pronamespace == lfirst_oid(nsp) &&
673 procform->pronamespace != myTempNamespace)
678 continue; /* proc is not in search path */
684 * Call uses named or mixed notation
686 * Named or mixed notation can match a variadic function only if
687 * expand_variadic is off; otherwise there is no way to match the
688 * presumed-nameless parameters expanded from the variadic array.
690 if (OidIsValid(procform->provariadic) && expand_variadic)
692 va_elem_type = InvalidOid;
696 * Check argument count.
698 Assert(nargs >= 0); /* -1 not supported with argnames */
700 if (pronargs > nargs && expand_defaults)
702 /* Ignore if not enough default expressions */
703 if (nargs + procform->pronargdefaults < pronargs)
708 use_defaults = false;
710 /* Ignore if it doesn't match requested argument count */
711 if (pronargs != nargs && !use_defaults)
714 /* Check for argument name match, generate positional mapping */
715 if (!MatchNamedCall(proctup, nargs, argnames,
719 /* Named argument matching is always "special" */
725 * Call uses positional notation
727 * Check if function is variadic, and get variadic element type if
728 * so. If expand_variadic is false, we should just ignore
731 if (pronargs <= nargs && expand_variadic)
733 va_elem_type = procform->provariadic;
734 variadic = OidIsValid(va_elem_type);
735 any_special |= variadic;
739 va_elem_type = InvalidOid;
744 * Check if function can match by using parameter defaults.
746 if (pronargs > nargs && expand_defaults)
748 /* Ignore if not enough default expressions */
749 if (nargs + procform->pronargdefaults < pronargs)
755 use_defaults = false;
757 /* Ignore if it doesn't match requested argument count */
758 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
763 * We must compute the effective argument list so that we can easily
764 * compare it to earlier results. We waste a palloc cycle if it gets
765 * masked by an earlier result, but really that's a pretty infrequent
766 * case so it's not worth worrying about.
768 effective_nargs = Max(pronargs, nargs);
769 newResult = (FuncCandidateList)
770 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
771 + effective_nargs * sizeof(Oid));
772 newResult->pathpos = pathpos;
773 newResult->oid = HeapTupleGetOid(proctup);
774 newResult->nargs = effective_nargs;
775 newResult->argnumbers = argnumbers;
778 /* Re-order the argument types into call's logical order */
779 Oid *proargtypes = procform->proargtypes.values;
782 for (i = 0; i < pronargs; i++)
783 newResult->args[i] = proargtypes[argnumbers[i]];
787 /* Simple positional case, just copy proargtypes as-is */
788 memcpy(newResult->args, procform->proargtypes.values,
789 pronargs * sizeof(Oid));
795 newResult->nvargs = effective_nargs - pronargs + 1;
796 /* Expand variadic argument into N copies of element type */
797 for (i = pronargs - 1; i < effective_nargs; i++)
798 newResult->args[i] = va_elem_type;
801 newResult->nvargs = 0;
802 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
805 * Does it have the same arguments as something we already accepted?
806 * If so, decide what to do to avoid returning duplicate argument
807 * lists. We can skip this check for the single-namespace case if no
808 * special (named, variadic or defaults) match has been made, since
809 * then the unique index on pg_proc guarantees all the matches have
810 * different argument lists.
812 if (resultList != NULL &&
813 (any_special || !OidIsValid(namespaceId)))
816 * If we have an ordered list from SearchSysCacheList (the normal
817 * case), then any conflicting proc must immediately adjoin this
818 * one in the list, so we only need to look at the newest result
819 * item. If we have an unordered list, we have to scan the whole
820 * result list. Also, if either the current candidate or any
821 * previous candidate is a special match, we can't assume that
822 * conflicts are adjacent.
824 * We ignore defaulted arguments in deciding what is a match.
826 FuncCandidateList prevResult;
828 if (catlist->ordered && !any_special)
830 /* ndargs must be 0 if !any_special */
831 if (effective_nargs == resultList->nargs &&
832 memcmp(newResult->args,
834 effective_nargs * sizeof(Oid)) == 0)
835 prevResult = resultList;
841 int cmp_nargs = newResult->nargs - newResult->ndargs;
843 for (prevResult = resultList;
845 prevResult = prevResult->next)
847 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
848 memcmp(newResult->args,
850 cmp_nargs * sizeof(Oid)) == 0)
858 * We have a match with a previous result. Decide which one
859 * to keep, or mark it ambiguous if we can't decide. The
860 * logic here is preference > 0 means prefer the old result,
861 * preference < 0 means prefer the new, preference = 0 means
866 if (pathpos != prevResult->pathpos)
869 * Prefer the one that's earlier in the search path.
871 preference = pathpos - prevResult->pathpos;
873 else if (variadic && prevResult->nvargs == 0)
876 * With variadic functions we could have, for example,
877 * both foo(numeric) and foo(variadic numeric[]) in the
878 * same namespace; if so we prefer the non-variadic match
879 * on efficiency grounds.
883 else if (!variadic && prevResult->nvargs > 0)
890 * We can't decide. This can happen with, for example,
891 * both foo(numeric, variadic numeric[]) and
892 * foo(variadic numeric[]) in the same namespace, or
893 * both foo(int) and foo (int, int default something)
894 * in the same namespace, or both foo(a int, b text)
895 * and foo(b text, a int) in the same namespace.
903 /* keep previous result */
907 else if (preference < 0)
909 /* remove previous result from the list */
910 if (prevResult == resultList)
911 resultList = prevResult->next;
914 FuncCandidateList prevPrevResult;
916 for (prevPrevResult = resultList;
918 prevPrevResult = prevPrevResult->next)
920 if (prevResult == prevPrevResult->next)
922 prevPrevResult->next = prevResult->next;
926 Assert(prevPrevResult); /* assert we found it */
929 /* fall through to add newResult to list */
933 /* mark old result as ambiguous, discard new */
934 prevResult->oid = InvalidOid;
942 * Okay to add it to result list
944 newResult->next = resultList;
945 resultList = newResult;
948 ReleaseSysCacheList(catlist);
955 * Given a pg_proc heap tuple and a call's list of argument names,
956 * check whether the function could match the call.
958 * The call could match if all supplied argument names are accepted by
959 * the function, in positions after the last positional argument, and there
960 * are defaults for all unsupplied arguments.
962 * The number of positional arguments is nargs - list_length(argnames).
963 * Note caller has already done basic checks on argument count.
965 * On match, return true and fill *argnumbers with a palloc'd array showing
966 * the mapping from call argument positions to actual function argument
967 * numbers. Defaulted arguments are included in this map, at positions
968 * after the last supplied argument.
971 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
974 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
975 int pronargs = procform->pronargs;
976 int numposargs = nargs - list_length(argnames);
981 bool arggiven[FUNC_MAX_ARGS];
983 int ap; /* call args position */
984 int pp; /* proargs position */
987 Assert(argnames != NIL);
988 Assert(numposargs >= 0);
989 Assert(nargs <= pronargs);
991 /* Ignore this function if its proargnames is null */
992 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
997 /* OK, let's extract the argument names and types */
998 pronallargs = get_func_arg_info(proctup,
999 &p_argtypes, &p_argnames, &p_argmodes);
1000 Assert(p_argnames != NULL);
1002 /* initialize state for matching */
1003 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1004 memset(arggiven, false, pronargs * sizeof(bool));
1006 /* there are numposargs positional args before the named args */
1007 for (ap = 0; ap < numposargs; ap++)
1009 (*argnumbers)[ap] = ap;
1010 arggiven[ap] = true;
1013 /* now examine the named args */
1014 foreach(lc, argnames)
1016 char *argname = (char *) lfirst(lc);
1022 for (i = 0; i < pronallargs; i++)
1024 /* consider only input parameters */
1026 (p_argmodes[i] != FUNC_PARAM_IN &&
1027 p_argmodes[i] != FUNC_PARAM_INOUT &&
1028 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1030 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1032 /* fail if argname matches a positional argument */
1035 arggiven[pp] = true;
1036 (*argnumbers)[ap] = pp;
1040 /* increase pp only for input parameters */
1043 /* if name isn't in proargnames, fail */
1049 Assert(ap == nargs); /* processed all actual parameters */
1051 /* Check for default arguments */
1052 if (nargs < pronargs)
1054 int first_arg_with_default = pronargs - procform->pronargdefaults;
1056 for (pp = numposargs; pp < pronargs; pp++)
1060 /* fail if arg not given and no default available */
1061 if (pp < first_arg_with_default)
1063 (*argnumbers)[ap++] = pp;
1067 Assert(ap == pronargs); /* processed all function parameters */
1074 * Determine whether a function (identified by OID) is visible in the
1075 * current search path. Visible means "would be found by searching
1076 * for the unqualified function name with exact argument matches".
1079 FunctionIsVisible(Oid funcid)
1082 Form_pg_proc procform;
1086 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1087 if (!HeapTupleIsValid(proctup))
1088 elog(ERROR, "cache lookup failed for function %u", funcid);
1089 procform = (Form_pg_proc) GETSTRUCT(proctup);
1091 recomputeNamespacePath();
1094 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1095 * the system namespace are surely in the path and so we needn't even do
1096 * list_member_oid() for them.
1098 pronamespace = procform->pronamespace;
1099 if (pronamespace != PG_CATALOG_NAMESPACE &&
1100 !list_member_oid(activeSearchPath, pronamespace))
1105 * If it is in the path, it might still not be visible; it could be
1106 * hidden by another proc of the same name and arguments earlier in
1107 * the path. So we must do a slow check to see if this is the same
1108 * proc that would be found by FuncnameGetCandidates.
1110 char *proname = NameStr(procform->proname);
1111 int nargs = procform->pronargs;
1112 FuncCandidateList clist;
1116 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1117 nargs, NIL, false, false);
1119 for (; clist; clist = clist->next)
1121 if (memcmp(clist->args, procform->proargtypes.values,
1122 nargs * sizeof(Oid)) == 0)
1124 /* Found the expected entry; is it the right proc? */
1125 visible = (clist->oid == funcid);
1131 ReleaseSysCache(proctup);
1139 * Given a possibly-qualified operator name and exact input datatypes,
1140 * look up the operator. Returns InvalidOid if not found.
1142 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1145 * If the operator name is not schema-qualified, it is sought in the current
1146 * namespace search path.
1149 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1156 /* deconstruct the name list */
1157 DeconstructQualifiedName(names, &schemaname, &opername);
1161 /* search only in exact schema given */
1165 namespaceId = LookupExplicitNamespace(schemaname);
1166 opertup = SearchSysCache4(OPERNAMENSP,
1167 CStringGetDatum(opername),
1168 ObjectIdGetDatum(oprleft),
1169 ObjectIdGetDatum(oprright),
1170 ObjectIdGetDatum(namespaceId));
1171 if (HeapTupleIsValid(opertup))
1173 Oid result = HeapTupleGetOid(opertup);
1175 ReleaseSysCache(opertup);
1181 /* Search syscache by name and argument types */
1182 catlist = SearchSysCacheList3(OPERNAMENSP,
1183 CStringGetDatum(opername),
1184 ObjectIdGetDatum(oprleft),
1185 ObjectIdGetDatum(oprright));
1187 if (catlist->n_members == 0)
1189 /* no hope, fall out early */
1190 ReleaseSysCacheList(catlist);
1195 * We have to find the list member that is first in the search path, if
1196 * there's more than one. This doubly-nested loop looks ugly, but in
1197 * practice there should usually be few catlist members.
1199 recomputeNamespacePath();
1201 foreach(l, activeSearchPath)
1203 Oid namespaceId = lfirst_oid(l);
1206 if (namespaceId == myTempNamespace)
1207 continue; /* do not look in temp namespace */
1209 for (i = 0; i < catlist->n_members; i++)
1211 HeapTuple opertup = &catlist->members[i]->tuple;
1212 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1214 if (operform->oprnamespace == namespaceId)
1216 Oid result = HeapTupleGetOid(opertup);
1218 ReleaseSysCacheList(catlist);
1224 ReleaseSysCacheList(catlist);
1229 * OpernameGetCandidates
1230 * Given a possibly-qualified operator name and operator kind,
1231 * retrieve a list of the possible matches.
1233 * If oprkind is '\0', we return all operators matching the given name,
1234 * regardless of arguments.
1236 * We search a single namespace if the operator name is qualified, else
1237 * all namespaces in the search path. The return list will never contain
1238 * multiple entries with identical argument lists --- in the multiple-
1239 * namespace case, we arrange for entries in earlier namespaces to mask
1240 * identical entries in later namespaces.
1242 * The returned items always have two args[] entries --- one or the other
1243 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1246 OpernameGetCandidates(List *names, char oprkind)
1248 FuncCandidateList resultList = NULL;
1249 char *resultSpace = NULL;
1257 /* deconstruct the name list */
1258 DeconstructQualifiedName(names, &schemaname, &opername);
1262 /* use exact schema given */
1263 namespaceId = LookupExplicitNamespace(schemaname);
1267 /* flag to indicate we need namespace search */
1268 namespaceId = InvalidOid;
1269 recomputeNamespacePath();
1272 /* Search syscache by name only */
1273 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1276 * In typical scenarios, most if not all of the operators found by the
1277 * catcache search will end up getting returned; and there can be quite a
1278 * few, for common operator names such as '=' or '+'. To reduce the time
1279 * spent in palloc, we allocate the result space as an array large enough
1280 * to hold all the operators. The original coding of this routine did a
1281 * separate palloc for each operator, but profiling revealed that the
1282 * pallocs used an unreasonably large fraction of parsing time.
1284 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1286 if (catlist->n_members > 0)
1287 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1289 for (i = 0; i < catlist->n_members; i++)
1291 HeapTuple opertup = &catlist->members[i]->tuple;
1292 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1294 FuncCandidateList newResult;
1296 /* Ignore operators of wrong kind, if specific kind requested */
1297 if (oprkind && operform->oprkind != oprkind)
1300 if (OidIsValid(namespaceId))
1302 /* Consider only opers in specified namespace */
1303 if (operform->oprnamespace != namespaceId)
1305 /* No need to check args, they must all be different */
1310 * Consider only opers that are in the search path and are not in
1311 * the temp namespace.
1315 foreach(nsp, activeSearchPath)
1317 if (operform->oprnamespace == lfirst_oid(nsp) &&
1318 operform->oprnamespace != myTempNamespace)
1323 continue; /* oper is not in search path */
1326 * Okay, it's in the search path, but does it have the same
1327 * arguments as something we already accepted? If so, keep only
1328 * the one that appears earlier in the search path.
1330 * If we have an ordered list from SearchSysCacheList (the normal
1331 * case), then any conflicting oper must immediately adjoin this
1332 * one in the list, so we only need to look at the newest result
1333 * item. If we have an unordered list, we have to scan the whole
1338 FuncCandidateList prevResult;
1340 if (catlist->ordered)
1342 if (operform->oprleft == resultList->args[0] &&
1343 operform->oprright == resultList->args[1])
1344 prevResult = resultList;
1350 for (prevResult = resultList;
1352 prevResult = prevResult->next)
1354 if (operform->oprleft == prevResult->args[0] &&
1355 operform->oprright == prevResult->args[1])
1361 /* We have a match with a previous result */
1362 Assert(pathpos != prevResult->pathpos);
1363 if (pathpos > prevResult->pathpos)
1364 continue; /* keep previous result */
1365 /* replace previous result */
1366 prevResult->pathpos = pathpos;
1367 prevResult->oid = HeapTupleGetOid(opertup);
1368 continue; /* args are same, of course */
1374 * Okay to add it to result list
1376 newResult = (FuncCandidateList) (resultSpace + nextResult);
1377 nextResult += SPACE_PER_OP;
1379 newResult->pathpos = pathpos;
1380 newResult->oid = HeapTupleGetOid(opertup);
1381 newResult->nargs = 2;
1382 newResult->nvargs = 0;
1383 newResult->ndargs = 0;
1384 newResult->argnumbers = NULL;
1385 newResult->args[0] = operform->oprleft;
1386 newResult->args[1] = operform->oprright;
1387 newResult->next = resultList;
1388 resultList = newResult;
1391 ReleaseSysCacheList(catlist);
1398 * Determine whether an operator (identified by OID) is visible in the
1399 * current search path. Visible means "would be found by searching
1400 * for the unqualified operator name with exact argument matches".
1403 OperatorIsVisible(Oid oprid)
1406 Form_pg_operator oprform;
1410 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1411 if (!HeapTupleIsValid(oprtup))
1412 elog(ERROR, "cache lookup failed for operator %u", oprid);
1413 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1415 recomputeNamespacePath();
1418 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1419 * the system namespace are surely in the path and so we needn't even do
1420 * list_member_oid() for them.
1422 oprnamespace = oprform->oprnamespace;
1423 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1424 !list_member_oid(activeSearchPath, oprnamespace))
1429 * If it is in the path, it might still not be visible; it could be
1430 * hidden by another operator of the same name and arguments earlier
1431 * in the path. So we must do a slow check to see if this is the same
1432 * operator that would be found by OpernameGetOprId.
1434 char *oprname = NameStr(oprform->oprname);
1436 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1437 oprform->oprleft, oprform->oprright)
1441 ReleaseSysCache(oprtup);
1448 * OpclassnameGetOpcid
1449 * Try to resolve an unqualified index opclass name.
1450 * Returns OID if opclass found in search path, else InvalidOid.
1452 * This is essentially the same as TypenameGetTypid, but we have to have
1453 * an extra argument for the index AM OID.
1456 OpclassnameGetOpcid(Oid amid, const char *opcname)
1461 recomputeNamespacePath();
1463 foreach(l, activeSearchPath)
1465 Oid namespaceId = lfirst_oid(l);
1467 if (namespaceId == myTempNamespace)
1468 continue; /* do not look in temp namespace */
1470 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1471 ObjectIdGetDatum(amid),
1472 PointerGetDatum(opcname),
1473 ObjectIdGetDatum(namespaceId));
1474 if (OidIsValid(opcid))
1478 /* Not found in path */
1484 * Determine whether an opclass (identified by OID) is visible in the
1485 * current search path. Visible means "would be found by searching
1486 * for the unqualified opclass name".
1489 OpclassIsVisible(Oid opcid)
1492 Form_pg_opclass opcform;
1496 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1497 if (!HeapTupleIsValid(opctup))
1498 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1499 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1501 recomputeNamespacePath();
1504 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1505 * the system namespace are surely in the path and so we needn't even do
1506 * list_member_oid() for them.
1508 opcnamespace = opcform->opcnamespace;
1509 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1510 !list_member_oid(activeSearchPath, opcnamespace))
1515 * If it is in the path, it might still not be visible; it could be
1516 * hidden by another opclass of the same name earlier in the path. So
1517 * we must do a slow check to see if this opclass would be found by
1518 * OpclassnameGetOpcid.
1520 char *opcname = NameStr(opcform->opcname);
1522 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1525 ReleaseSysCache(opctup);
1531 * OpfamilynameGetOpfid
1532 * Try to resolve an unqualified index opfamily name.
1533 * Returns OID if opfamily found in search path, else InvalidOid.
1535 * This is essentially the same as TypenameGetTypid, but we have to have
1536 * an extra argument for the index AM OID.
1539 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1544 recomputeNamespacePath();
1546 foreach(l, activeSearchPath)
1548 Oid namespaceId = lfirst_oid(l);
1550 if (namespaceId == myTempNamespace)
1551 continue; /* do not look in temp namespace */
1553 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1554 ObjectIdGetDatum(amid),
1555 PointerGetDatum(opfname),
1556 ObjectIdGetDatum(namespaceId));
1557 if (OidIsValid(opfid))
1561 /* Not found in path */
1567 * Determine whether an opfamily (identified by OID) is visible in the
1568 * current search path. Visible means "would be found by searching
1569 * for the unqualified opfamily name".
1572 OpfamilyIsVisible(Oid opfid)
1575 Form_pg_opfamily opfform;
1579 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1580 if (!HeapTupleIsValid(opftup))
1581 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1582 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1584 recomputeNamespacePath();
1587 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1588 * the system namespace are surely in the path and so we needn't even do
1589 * list_member_oid() for them.
1591 opfnamespace = opfform->opfnamespace;
1592 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1593 !list_member_oid(activeSearchPath, opfnamespace))
1598 * If it is in the path, it might still not be visible; it could be
1599 * hidden by another opfamily of the same name earlier in the path. So
1600 * we must do a slow check to see if this opfamily would be found by
1601 * OpfamilynameGetOpfid.
1603 char *opfname = NameStr(opfform->opfname);
1605 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1608 ReleaseSysCache(opftup);
1614 * ConversionGetConid
1615 * Try to resolve an unqualified conversion name.
1616 * Returns OID if conversion found in search path, else InvalidOid.
1618 * This is essentially the same as RelnameGetRelid.
1621 ConversionGetConid(const char *conname)
1626 recomputeNamespacePath();
1628 foreach(l, activeSearchPath)
1630 Oid namespaceId = lfirst_oid(l);
1632 if (namespaceId == myTempNamespace)
1633 continue; /* do not look in temp namespace */
1635 conid = GetSysCacheOid2(CONNAMENSP,
1636 PointerGetDatum(conname),
1637 ObjectIdGetDatum(namespaceId));
1638 if (OidIsValid(conid))
1642 /* Not found in path */
1647 * ConversionIsVisible
1648 * Determine whether a conversion (identified by OID) is visible in the
1649 * current search path. Visible means "would be found by searching
1650 * for the unqualified conversion name".
1653 ConversionIsVisible(Oid conid)
1656 Form_pg_conversion conform;
1660 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1661 if (!HeapTupleIsValid(contup))
1662 elog(ERROR, "cache lookup failed for conversion %u", conid);
1663 conform = (Form_pg_conversion) GETSTRUCT(contup);
1665 recomputeNamespacePath();
1668 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1669 * the system namespace are surely in the path and so we needn't even do
1670 * list_member_oid() for them.
1672 connamespace = conform->connamespace;
1673 if (connamespace != PG_CATALOG_NAMESPACE &&
1674 !list_member_oid(activeSearchPath, connamespace))
1679 * If it is in the path, it might still not be visible; it could be
1680 * hidden by another conversion of the same name earlier in the path.
1681 * So we must do a slow check to see if this conversion would be found
1682 * by ConversionGetConid.
1684 char *conname = NameStr(conform->conname);
1686 visible = (ConversionGetConid(conname) == conid);
1689 ReleaseSysCache(contup);
1695 * get_ts_parser_oid - find a TS parser by possibly qualified name
1697 * If not found, returns InvalidOid if missing_ok, else throws error
1700 get_ts_parser_oid(List *names, bool missing_ok)
1705 Oid prsoid = InvalidOid;
1708 /* deconstruct the name list */
1709 DeconstructQualifiedName(names, &schemaname, &parser_name);
1713 /* use exact schema given */
1714 namespaceId = LookupExplicitNamespace(schemaname);
1715 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1716 PointerGetDatum(parser_name),
1717 ObjectIdGetDatum(namespaceId));
1721 /* search for it in search path */
1722 recomputeNamespacePath();
1724 foreach(l, activeSearchPath)
1726 namespaceId = lfirst_oid(l);
1728 if (namespaceId == myTempNamespace)
1729 continue; /* do not look in temp namespace */
1731 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1732 PointerGetDatum(parser_name),
1733 ObjectIdGetDatum(namespaceId));
1734 if (OidIsValid(prsoid))
1739 if (!OidIsValid(prsoid) && !missing_ok)
1741 (errcode(ERRCODE_UNDEFINED_OBJECT),
1742 errmsg("text search parser \"%s\" does not exist",
1743 NameListToString(names))));
1750 * Determine whether a parser (identified by OID) is visible in the
1751 * current search path. Visible means "would be found by searching
1752 * for the unqualified parser name".
1755 TSParserIsVisible(Oid prsId)
1758 Form_pg_ts_parser form;
1762 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1763 if (!HeapTupleIsValid(tup))
1764 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1765 form = (Form_pg_ts_parser) GETSTRUCT(tup);
1767 recomputeNamespacePath();
1770 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1771 * the system namespace are surely in the path and so we needn't even do
1772 * list_member_oid() for them.
1774 namespace = form->prsnamespace;
1775 if (namespace != PG_CATALOG_NAMESPACE &&
1776 !list_member_oid(activeSearchPath, namespace))
1781 * If it is in the path, it might still not be visible; it could be
1782 * hidden by another parser of the same name earlier in the path. So
1783 * we must do a slow check for conflicting parsers.
1785 char *name = NameStr(form->prsname);
1789 foreach(l, activeSearchPath)
1791 Oid namespaceId = lfirst_oid(l);
1793 if (namespaceId == myTempNamespace)
1794 continue; /* do not look in temp namespace */
1796 if (namespaceId == namespace)
1798 /* Found it first in path */
1802 if (SearchSysCacheExists2(TSPARSERNAMENSP,
1803 PointerGetDatum(name),
1804 ObjectIdGetDatum(namespaceId)))
1806 /* Found something else first in path */
1812 ReleaseSysCache(tup);
1818 * get_ts_dict_oid - find a TS dictionary by possibly qualified name
1820 * If not found, returns InvalidOid if failOK, else throws error
1823 get_ts_dict_oid(List *names, bool missing_ok)
1828 Oid dictoid = InvalidOid;
1831 /* deconstruct the name list */
1832 DeconstructQualifiedName(names, &schemaname, &dict_name);
1836 /* use exact schema given */
1837 namespaceId = LookupExplicitNamespace(schemaname);
1838 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1839 PointerGetDatum(dict_name),
1840 ObjectIdGetDatum(namespaceId));
1844 /* search for it in search path */
1845 recomputeNamespacePath();
1847 foreach(l, activeSearchPath)
1849 namespaceId = lfirst_oid(l);
1851 if (namespaceId == myTempNamespace)
1852 continue; /* do not look in temp namespace */
1854 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1855 PointerGetDatum(dict_name),
1856 ObjectIdGetDatum(namespaceId));
1857 if (OidIsValid(dictoid))
1862 if (!OidIsValid(dictoid) && !missing_ok)
1864 (errcode(ERRCODE_UNDEFINED_OBJECT),
1865 errmsg("text search dictionary \"%s\" does not exist",
1866 NameListToString(names))));
1872 * TSDictionaryIsVisible
1873 * Determine whether a dictionary (identified by OID) is visible in the
1874 * current search path. Visible means "would be found by searching
1875 * for the unqualified dictionary name".
1878 TSDictionaryIsVisible(Oid dictId)
1881 Form_pg_ts_dict form;
1885 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
1886 if (!HeapTupleIsValid(tup))
1887 elog(ERROR, "cache lookup failed for text search dictionary %u",
1889 form = (Form_pg_ts_dict) GETSTRUCT(tup);
1891 recomputeNamespacePath();
1894 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1895 * the system namespace are surely in the path and so we needn't even do
1896 * list_member_oid() for them.
1898 namespace = form->dictnamespace;
1899 if (namespace != PG_CATALOG_NAMESPACE &&
1900 !list_member_oid(activeSearchPath, namespace))
1905 * If it is in the path, it might still not be visible; it could be
1906 * hidden by another dictionary of the same name earlier in the path.
1907 * So we must do a slow check for conflicting dictionaries.
1909 char *name = NameStr(form->dictname);
1913 foreach(l, activeSearchPath)
1915 Oid namespaceId = lfirst_oid(l);
1917 if (namespaceId == myTempNamespace)
1918 continue; /* do not look in temp namespace */
1920 if (namespaceId == namespace)
1922 /* Found it first in path */
1926 if (SearchSysCacheExists2(TSDICTNAMENSP,
1927 PointerGetDatum(name),
1928 ObjectIdGetDatum(namespaceId)))
1930 /* Found something else first in path */
1936 ReleaseSysCache(tup);
1942 * get_ts_template_oid - find a TS template by possibly qualified name
1944 * If not found, returns InvalidOid if missing_ok, else throws error
1947 get_ts_template_oid(List *names, bool missing_ok)
1950 char *template_name;
1952 Oid tmploid = InvalidOid;
1955 /* deconstruct the name list */
1956 DeconstructQualifiedName(names, &schemaname, &template_name);
1960 /* use exact schema given */
1961 namespaceId = LookupExplicitNamespace(schemaname);
1962 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1963 PointerGetDatum(template_name),
1964 ObjectIdGetDatum(namespaceId));
1968 /* search for it in search path */
1969 recomputeNamespacePath();
1971 foreach(l, activeSearchPath)
1973 namespaceId = lfirst_oid(l);
1975 if (namespaceId == myTempNamespace)
1976 continue; /* do not look in temp namespace */
1978 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1979 PointerGetDatum(template_name),
1980 ObjectIdGetDatum(namespaceId));
1981 if (OidIsValid(tmploid))
1986 if (!OidIsValid(tmploid) && !missing_ok)
1988 (errcode(ERRCODE_UNDEFINED_OBJECT),
1989 errmsg("text search template \"%s\" does not exist",
1990 NameListToString(names))));
1996 * TSTemplateIsVisible
1997 * Determine whether a template (identified by OID) is visible in the
1998 * current search path. Visible means "would be found by searching
1999 * for the unqualified template name".
2002 TSTemplateIsVisible(Oid tmplId)
2005 Form_pg_ts_template form;
2009 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2010 if (!HeapTupleIsValid(tup))
2011 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2012 form = (Form_pg_ts_template) GETSTRUCT(tup);
2014 recomputeNamespacePath();
2017 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2018 * the system namespace are surely in the path and so we needn't even do
2019 * list_member_oid() for them.
2021 namespace = form->tmplnamespace;
2022 if (namespace != PG_CATALOG_NAMESPACE &&
2023 !list_member_oid(activeSearchPath, namespace))
2028 * If it is in the path, it might still not be visible; it could be
2029 * hidden by another template of the same name earlier in the path. So
2030 * we must do a slow check for conflicting templates.
2032 char *name = NameStr(form->tmplname);
2036 foreach(l, activeSearchPath)
2038 Oid namespaceId = lfirst_oid(l);
2040 if (namespaceId == myTempNamespace)
2041 continue; /* do not look in temp namespace */
2043 if (namespaceId == namespace)
2045 /* Found it first in path */
2049 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2050 PointerGetDatum(name),
2051 ObjectIdGetDatum(namespaceId)))
2053 /* Found something else first in path */
2059 ReleaseSysCache(tup);
2065 * get_ts_config_oid - find a TS config by possibly qualified name
2067 * If not found, returns InvalidOid if missing_ok, else throws error
2070 get_ts_config_oid(List *names, bool missing_ok)
2075 Oid cfgoid = InvalidOid;
2078 /* deconstruct the name list */
2079 DeconstructQualifiedName(names, &schemaname, &config_name);
2083 /* use exact schema given */
2084 namespaceId = LookupExplicitNamespace(schemaname);
2085 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2086 PointerGetDatum(config_name),
2087 ObjectIdGetDatum(namespaceId));
2091 /* search for it in search path */
2092 recomputeNamespacePath();
2094 foreach(l, activeSearchPath)
2096 namespaceId = lfirst_oid(l);
2098 if (namespaceId == myTempNamespace)
2099 continue; /* do not look in temp namespace */
2101 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2102 PointerGetDatum(config_name),
2103 ObjectIdGetDatum(namespaceId));
2104 if (OidIsValid(cfgoid))
2109 if (!OidIsValid(cfgoid) && !missing_ok)
2111 (errcode(ERRCODE_UNDEFINED_OBJECT),
2112 errmsg("text search configuration \"%s\" does not exist",
2113 NameListToString(names))));
2120 * Determine whether a text search configuration (identified by OID)
2121 * is visible in the current search path. Visible means "would be found
2122 * by searching for the unqualified text search configuration name".
2125 TSConfigIsVisible(Oid cfgid)
2128 Form_pg_ts_config form;
2132 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2133 if (!HeapTupleIsValid(tup))
2134 elog(ERROR, "cache lookup failed for text search configuration %u",
2136 form = (Form_pg_ts_config) GETSTRUCT(tup);
2138 recomputeNamespacePath();
2141 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2142 * the system namespace are surely in the path and so we needn't even do
2143 * list_member_oid() for them.
2145 namespace = form->cfgnamespace;
2146 if (namespace != PG_CATALOG_NAMESPACE &&
2147 !list_member_oid(activeSearchPath, namespace))
2152 * If it is in the path, it might still not be visible; it could be
2153 * hidden by another configuration of the same name earlier in the
2154 * path. So we must do a slow check for conflicting configurations.
2156 char *name = NameStr(form->cfgname);
2160 foreach(l, activeSearchPath)
2162 Oid namespaceId = lfirst_oid(l);
2164 if (namespaceId == myTempNamespace)
2165 continue; /* do not look in temp namespace */
2167 if (namespaceId == namespace)
2169 /* Found it first in path */
2173 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2174 PointerGetDatum(name),
2175 ObjectIdGetDatum(namespaceId)))
2177 /* Found something else first in path */
2183 ReleaseSysCache(tup);
2190 * DeconstructQualifiedName
2191 * Given a possibly-qualified name expressed as a list of String nodes,
2192 * extract the schema name and object name.
2194 * *nspname_p is set to NULL if there is no explicit schema name.
2197 DeconstructQualifiedName(List *names,
2202 char *schemaname = NULL;
2203 char *objname = NULL;
2205 switch (list_length(names))
2208 objname = strVal(linitial(names));
2211 schemaname = strVal(linitial(names));
2212 objname = strVal(lsecond(names));
2215 catalogname = strVal(linitial(names));
2216 schemaname = strVal(lsecond(names));
2217 objname = strVal(lthird(names));
2220 * We check the catalog name and then ignore it.
2222 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2224 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2225 errmsg("cross-database references are not implemented: %s",
2226 NameListToString(names))));
2230 (errcode(ERRCODE_SYNTAX_ERROR),
2231 errmsg("improper qualified name (too many dotted names): %s",
2232 NameListToString(names))));
2236 *nspname_p = schemaname;
2237 *objname_p = objname;
2241 * LookupNamespaceNoError
2242 * Look up a schema name.
2244 * Returns the namespace OID, or InvalidOid if not found.
2246 * Note this does NOT perform any permissions check --- callers are
2247 * responsible for being sure that an appropriate check is made.
2248 * In the majority of cases LookupExplicitNamespace is preferable.
2251 LookupNamespaceNoError(const char *nspname)
2253 /* check for pg_temp alias */
2254 if (strcmp(nspname, "pg_temp") == 0)
2256 if (OidIsValid(myTempNamespace))
2257 return myTempNamespace;
2260 * Since this is used only for looking up existing objects, there is
2261 * no point in trying to initialize the temp namespace here; and doing
2262 * so might create problems for some callers. Just report "not found".
2267 return get_namespace_oid(nspname, true);
2271 * LookupExplicitNamespace
2272 * Process an explicitly-specified schema name: look up the schema
2273 * and verify we have USAGE (lookup) rights in it.
2275 * Returns the namespace OID. Raises ereport if any problem.
2278 LookupExplicitNamespace(const char *nspname)
2281 AclResult aclresult;
2283 /* check for pg_temp alias */
2284 if (strcmp(nspname, "pg_temp") == 0)
2286 if (OidIsValid(myTempNamespace))
2287 return myTempNamespace;
2290 * Since this is used only for looking up existing objects, there is
2291 * no point in trying to initialize the temp namespace here; and doing
2292 * so might create problems for some callers. Just fall through and
2293 * give the "does not exist" error.
2297 namespaceId = get_namespace_oid(nspname, false);
2299 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2300 if (aclresult != ACLCHECK_OK)
2301 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2308 * LookupCreationNamespace
2309 * Look up the schema and verify we have CREATE rights on it.
2311 * This is just like LookupExplicitNamespace except for the different
2312 * permission check, and that we are willing to create pg_temp if needed.
2314 * Note: calling this may result in a CommandCounterIncrement operation,
2315 * if we have to create or clean out the temp namespace.
2318 LookupCreationNamespace(const char *nspname)
2321 AclResult aclresult;
2323 /* check for pg_temp alias */
2324 if (strcmp(nspname, "pg_temp") == 0)
2326 /* Initialize temp namespace if first time through */
2327 if (!OidIsValid(myTempNamespace))
2328 InitTempTableNamespace();
2329 return myTempNamespace;
2332 namespaceId = get_namespace_oid(nspname, false);
2334 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2335 if (aclresult != ACLCHECK_OK)
2336 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2343 * QualifiedNameGetCreationNamespace
2344 * Given a possibly-qualified name for an object (in List-of-Values
2345 * format), determine what namespace the object should be created in.
2346 * Also extract and return the object name (last component of list).
2348 * Note: this does not apply any permissions check. Callers must check
2349 * for CREATE rights on the selected namespace when appropriate.
2351 * Note: calling this may result in a CommandCounterIncrement operation,
2352 * if we have to create or clean out the temp namespace.
2355 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2360 /* deconstruct the name list */
2361 DeconstructQualifiedName(names, &schemaname, objname_p);
2365 /* check for pg_temp alias */
2366 if (strcmp(schemaname, "pg_temp") == 0)
2368 /* Initialize temp namespace if first time through */
2369 if (!OidIsValid(myTempNamespace))
2370 InitTempTableNamespace();
2371 return myTempNamespace;
2373 /* use exact schema given */
2374 namespaceId = get_namespace_oid(schemaname, false);
2375 /* we do not check for USAGE rights here! */
2379 /* use the default creation namespace */
2380 recomputeNamespacePath();
2381 if (activeTempCreationPending)
2383 /* Need to initialize temp namespace */
2384 InitTempTableNamespace();
2385 return myTempNamespace;
2387 namespaceId = activeCreationNamespace;
2388 if (!OidIsValid(namespaceId))
2390 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2391 errmsg("no schema has been selected to create in")));
2398 * get_namespace_oid - given a namespace name, look up the OID
2400 * If missing_ok is false, throw an error if namespace name not found. If
2401 * true, just return InvalidOid.
2404 get_namespace_oid(const char *nspname, bool missing_ok)
2408 oid = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2409 if (!OidIsValid(oid) && !missing_ok)
2411 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2412 errmsg("schema \"%s\" does not exist", nspname)));
2418 * makeRangeVarFromNameList
2419 * Utility routine to convert a qualified-name list into RangeVar form.
2422 makeRangeVarFromNameList(List *names)
2424 RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2426 switch (list_length(names))
2429 rel->relname = strVal(linitial(names));
2432 rel->schemaname = strVal(linitial(names));
2433 rel->relname = strVal(lsecond(names));
2436 rel->catalogname = strVal(linitial(names));
2437 rel->schemaname = strVal(lsecond(names));
2438 rel->relname = strVal(lthird(names));
2442 (errcode(ERRCODE_SYNTAX_ERROR),
2443 errmsg("improper relation name (too many dotted names): %s",
2444 NameListToString(names))));
2453 * Utility routine to convert a qualified-name list into a string.
2455 * This is used primarily to form error messages, and so we do not quote
2456 * the list elements, for the sake of legibility.
2458 * In most scenarios the list elements should always be Value strings,
2459 * but we also allow A_Star for the convenience of ColumnRef processing.
2462 NameListToString(List *names)
2464 StringInfoData string;
2467 initStringInfo(&string);
2471 Node *name = (Node *) lfirst(l);
2473 if (l != list_head(names))
2474 appendStringInfoChar(&string, '.');
2476 if (IsA(name, String))
2477 appendStringInfoString(&string, strVal(name));
2478 else if (IsA(name, A_Star))
2479 appendStringInfoString(&string, "*");
2481 elog(ERROR, "unexpected node type in name list: %d",
2482 (int) nodeTag(name));
2489 * NameListToQuotedString
2490 * Utility routine to convert a qualified-name list into a string.
2492 * Same as above except that names will be double-quoted where necessary,
2493 * so the string could be re-parsed (eg, by textToQualifiedNameList).
2496 NameListToQuotedString(List *names)
2498 StringInfoData string;
2501 initStringInfo(&string);
2505 if (l != list_head(names))
2506 appendStringInfoChar(&string, '.');
2507 appendStringInfoString(&string, quote_identifier(strVal(lfirst(l))));
2514 * isTempNamespace - is the given namespace my temporary-table namespace?
2517 isTempNamespace(Oid namespaceId)
2519 if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2525 * isTempToastNamespace - is the given namespace my temporary-toast-table
2529 isTempToastNamespace(Oid namespaceId)
2531 if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2537 * isTempOrToastNamespace - is the given namespace my temporary-table
2538 * namespace or my temporary-toast-table namespace?
2541 isTempOrToastNamespace(Oid namespaceId)
2543 if (OidIsValid(myTempNamespace) &&
2544 (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2550 * isAnyTempNamespace - is the given namespace a temporary-table namespace
2551 * (either my own, or another backend's)? Temporary-toast-table namespaces
2552 * are included, too.
2555 isAnyTempNamespace(Oid namespaceId)
2560 /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2561 nspname = get_namespace_name(namespaceId);
2563 return false; /* no such namespace? */
2564 result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
2565 (strncmp(nspname, "pg_toast_temp_", 14) == 0);
2571 * isOtherTempNamespace - is the given namespace some other backend's
2572 * temporary-table namespace (including temporary-toast-table namespaces)?
2574 * Note: for most purposes in the C code, this function is obsolete. Use
2575 * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
2578 isOtherTempNamespace(Oid namespaceId)
2580 /* If it's my own temp namespace, say "false" */
2581 if (isTempOrToastNamespace(namespaceId))
2583 /* Else, if it's any temp namespace, say "true" */
2584 return isAnyTempNamespace(namespaceId);
2588 * GetTempNamespaceBackendId - if the given namespace is a temporary-table
2589 * namespace (either my own, or another backend's), return the BackendId
2590 * that owns it. Temporary-toast-table namespaces are included, too.
2591 * If it isn't a temp namespace, return InvalidBackendId.
2594 GetTempNamespaceBackendId(Oid namespaceId)
2599 /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
2600 nspname = get_namespace_name(namespaceId);
2602 return InvalidBackendId; /* no such namespace? */
2603 if (strncmp(nspname, "pg_temp_", 8) == 0)
2604 result = atoi(nspname + 8);
2605 else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
2606 result = atoi(nspname + 14);
2608 result = InvalidBackendId;
2614 * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
2615 * which must already be assigned. (This is only used when creating a toast
2616 * table for a temp table, so we must have already done InitTempTableNamespace)
2619 GetTempToastNamespace(void)
2621 Assert(OidIsValid(myTempToastNamespace));
2622 return myTempToastNamespace;
2627 * GetOverrideSearchPath - fetch current search path definition in form
2628 * used by PushOverrideSearchPath.
2630 * The result structure is allocated in the specified memory context
2631 * (which might or might not be equal to CurrentMemoryContext); but any
2632 * junk created by revalidation calculations will be in CurrentMemoryContext.
2634 OverrideSearchPath *
2635 GetOverrideSearchPath(MemoryContext context)
2637 OverrideSearchPath *result;
2639 MemoryContext oldcxt;
2641 recomputeNamespacePath();
2643 oldcxt = MemoryContextSwitchTo(context);
2645 result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
2646 schemas = list_copy(activeSearchPath);
2647 while (schemas && linitial_oid(schemas) != activeCreationNamespace)
2649 if (linitial_oid(schemas) == myTempNamespace)
2650 result->addTemp = true;
2653 Assert(linitial_oid(schemas) == PG_CATALOG_NAMESPACE);
2654 result->addCatalog = true;
2656 schemas = list_delete_first(schemas);
2658 result->schemas = schemas;
2660 MemoryContextSwitchTo(oldcxt);
2666 * PushOverrideSearchPath - temporarily override the search path
2668 * We allow nested overrides, hence the push/pop terminology. The GUC
2669 * search_path variable is ignored while an override is active.
2671 * It's possible that newpath->useTemp is set but there is no longer any
2672 * active temp namespace, if the path was saved during a transaction that
2673 * created a temp namespace and was later rolled back. In that case we just
2674 * ignore useTemp. A plausible alternative would be to create a new temp
2675 * namespace, but for existing callers that's not necessary because an empty
2676 * temp namespace wouldn't affect their results anyway.
2678 * It's also worth noting that other schemas listed in newpath might not
2679 * exist anymore either. We don't worry about this because OIDs that match
2680 * no existing namespace will simply not produce any hits during searches.
2683 PushOverrideSearchPath(OverrideSearchPath *newpath)
2685 OverrideStackEntry *entry;
2688 MemoryContext oldcxt;
2691 * Copy the list for safekeeping, and insert implicitly-searched
2692 * namespaces as needed. This code should track recomputeNamespacePath.
2694 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2696 oidlist = list_copy(newpath->schemas);
2699 * Remember the first member of the explicit list.
2702 firstNS = InvalidOid;
2704 firstNS = linitial_oid(oidlist);
2707 * Add any implicitly-searched namespaces to the list. Note these go on
2708 * the front, not the back; also notice that we do not check USAGE
2709 * permissions for these.
2711 if (newpath->addCatalog)
2712 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2714 if (newpath->addTemp && OidIsValid(myTempNamespace))
2715 oidlist = lcons_oid(myTempNamespace, oidlist);
2718 * Build the new stack entry, then insert it at the head of the list.
2720 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
2721 entry->searchPath = oidlist;
2722 entry->creationNamespace = firstNS;
2723 entry->nestLevel = GetCurrentTransactionNestLevel();
2725 overrideStack = lcons(entry, overrideStack);
2727 /* And make it active. */
2728 activeSearchPath = entry->searchPath;
2729 activeCreationNamespace = entry->creationNamespace;
2730 activeTempCreationPending = false; /* XXX is this OK? */
2732 MemoryContextSwitchTo(oldcxt);
2736 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
2738 * Any push during a (sub)transaction will be popped automatically at abort.
2739 * But it's caller error if a push isn't popped in normal control flow.
2742 PopOverrideSearchPath(void)
2744 OverrideStackEntry *entry;
2746 /* Sanity checks. */
2747 if (overrideStack == NIL)
2748 elog(ERROR, "bogus PopOverrideSearchPath call");
2749 entry = (OverrideStackEntry *) linitial(overrideStack);
2750 if (entry->nestLevel != GetCurrentTransactionNestLevel())
2751 elog(ERROR, "bogus PopOverrideSearchPath call");
2753 /* Pop the stack and free storage. */
2754 overrideStack = list_delete_first(overrideStack);
2755 list_free(entry->searchPath);
2758 /* Activate the next level down. */
2761 entry = (OverrideStackEntry *) linitial(overrideStack);
2762 activeSearchPath = entry->searchPath;
2763 activeCreationNamespace = entry->creationNamespace;
2764 activeTempCreationPending = false; /* XXX is this OK? */
2768 /* If not baseSearchPathValid, this is useless but harmless */
2769 activeSearchPath = baseSearchPath;
2770 activeCreationNamespace = baseCreationNamespace;
2771 activeTempCreationPending = baseTempCreationPending;
2777 * get_conversion_oid - find a conversion by possibly qualified name
2780 get_conversion_oid(List *name, bool missing_ok)
2783 char *conversion_name;
2785 Oid conoid = InvalidOid;
2788 /* deconstruct the name list */
2789 DeconstructQualifiedName(name, &schemaname, &conversion_name);
2793 /* use exact schema given */
2794 namespaceId = LookupExplicitNamespace(schemaname);
2795 conoid = GetSysCacheOid2(CONNAMENSP,
2796 PointerGetDatum(conversion_name),
2797 ObjectIdGetDatum(namespaceId));
2801 /* search for it in search path */
2802 recomputeNamespacePath();
2804 foreach(l, activeSearchPath)
2806 namespaceId = lfirst_oid(l);
2808 if (namespaceId == myTempNamespace)
2809 continue; /* do not look in temp namespace */
2811 conoid = GetSysCacheOid2(CONNAMENSP,
2812 PointerGetDatum(conversion_name),
2813 ObjectIdGetDatum(namespaceId));
2814 if (OidIsValid(conoid))
2819 /* Not found in path */
2820 if (!OidIsValid(conoid) && !missing_ok)
2822 (errcode(ERRCODE_UNDEFINED_OBJECT),
2823 errmsg("conversion \"%s\" does not exist",
2824 NameListToString(name))));
2829 * FindDefaultConversionProc - find default encoding conversion proc
2832 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
2837 recomputeNamespacePath();
2839 foreach(l, activeSearchPath)
2841 Oid namespaceId = lfirst_oid(l);
2843 if (namespaceId == myTempNamespace)
2844 continue; /* do not look in temp namespace */
2846 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
2847 if (OidIsValid(proc))
2851 /* Not found in path */
2856 * recomputeNamespacePath - recompute path derived variables if needed.
2859 recomputeNamespacePath(void)
2861 Oid roleid = GetUserId();
2869 MemoryContext oldcxt;
2871 /* Do nothing if an override search spec is active. */
2875 /* Do nothing if path is already valid. */
2876 if (baseSearchPathValid && namespaceUser == roleid)
2879 /* Need a modifiable copy of namespace_search_path string */
2880 rawname = pstrdup(namespace_search_path);
2882 /* Parse string into list of identifiers */
2883 if (!SplitIdentifierString(rawname, ',', &namelist))
2885 /* syntax error in name list */
2886 /* this should not happen if GUC checked check_search_path */
2887 elog(ERROR, "invalid list syntax");
2891 * Convert the list of names to a list of OIDs. If any names are not
2892 * recognizable or we don't have read access, just leave them out of the
2893 * list. (We can't raise an error, since the search_path setting has
2894 * already been accepted.) Don't make duplicate entries, either.
2897 temp_missing = false;
2898 foreach(l, namelist)
2900 char *curname = (char *) lfirst(l);
2903 if (strcmp(curname, "$user") == 0)
2905 /* $user --- substitute namespace matching user name, if any */
2908 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2909 if (HeapTupleIsValid(tuple))
2913 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
2914 namespaceId = get_namespace_oid(rname, true);
2915 ReleaseSysCache(tuple);
2916 if (OidIsValid(namespaceId) &&
2917 !list_member_oid(oidlist, namespaceId) &&
2918 pg_namespace_aclcheck(namespaceId, roleid,
2919 ACL_USAGE) == ACLCHECK_OK)
2920 oidlist = lappend_oid(oidlist, namespaceId);
2923 else if (strcmp(curname, "pg_temp") == 0)
2925 /* pg_temp --- substitute temp namespace, if any */
2926 if (OidIsValid(myTempNamespace))
2928 if (!list_member_oid(oidlist, myTempNamespace))
2929 oidlist = lappend_oid(oidlist, myTempNamespace);
2933 /* If it ought to be the creation namespace, set flag */
2935 temp_missing = true;
2940 /* normal namespace reference */
2941 namespaceId = get_namespace_oid(curname, true);
2942 if (OidIsValid(namespaceId) &&
2943 !list_member_oid(oidlist, namespaceId) &&
2944 pg_namespace_aclcheck(namespaceId, roleid,
2945 ACL_USAGE) == ACLCHECK_OK)
2946 oidlist = lappend_oid(oidlist, namespaceId);
2951 * Remember the first member of the explicit list. (Note: this is
2952 * nominally wrong if temp_missing, but we need it anyway to distinguish
2953 * explicit from implicit mention of pg_catalog.)
2956 firstNS = InvalidOid;
2958 firstNS = linitial_oid(oidlist);
2961 * Add any implicitly-searched namespaces to the list. Note these go on
2962 * the front, not the back; also notice that we do not check USAGE
2963 * permissions for these.
2965 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
2966 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2968 if (OidIsValid(myTempNamespace) &&
2969 !list_member_oid(oidlist, myTempNamespace))
2970 oidlist = lcons_oid(myTempNamespace, oidlist);
2973 * Now that we've successfully built the new list of namespace OIDs, save
2974 * it in permanent storage.
2976 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2977 newpath = list_copy(oidlist);
2978 MemoryContextSwitchTo(oldcxt);
2980 /* Now safe to assign to state variables. */
2981 list_free(baseSearchPath);
2982 baseSearchPath = newpath;
2983 baseCreationNamespace = firstNS;
2984 baseTempCreationPending = temp_missing;
2986 /* Mark the path valid. */
2987 baseSearchPathValid = true;
2988 namespaceUser = roleid;
2990 /* And make it active. */
2991 activeSearchPath = baseSearchPath;
2992 activeCreationNamespace = baseCreationNamespace;
2993 activeTempCreationPending = baseTempCreationPending;
2997 list_free(namelist);
3002 * InitTempTableNamespace
3003 * Initialize temp table namespace on first use in a particular backend
3006 InitTempTableNamespace(void)
3008 char namespaceName[NAMEDATALEN];
3012 Assert(!OidIsValid(myTempNamespace));
3015 * First, do permission check to see if we are authorized to make temp
3016 * tables. We use a nonstandard error message here since "databasename:
3017 * permission denied" might be a tad cryptic.
3019 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3020 * that's necessary since current user ID could change during the session.
3021 * But there's no need to make the namespace in the first place until a
3022 * temp table creation request is made by someone with appropriate rights.
3024 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3025 ACL_CREATE_TEMP) != ACLCHECK_OK)
3027 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3028 errmsg("permission denied to create temporary tables in database \"%s\"",
3029 get_database_name(MyDatabaseId))));
3032 * Do not allow a Hot Standby slave session to make temp tables. Aside
3033 * from problems with modifying the system catalogs, there is a naming
3034 * conflict: pg_temp_N belongs to the session with BackendId N on the
3035 * master, not to a slave session with the same BackendId. We should not
3036 * be able to get here anyway due to XactReadOnly checks, but let's just
3037 * make real sure. Note that this also backstops various operations that
3038 * allow XactReadOnly transactions to modify temp tables; they'd need
3039 * RecoveryInProgress checks if not for this.
3041 if (RecoveryInProgress())
3043 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3044 errmsg("cannot create temporary tables during recovery")));
3046 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3048 namespaceId = get_namespace_oid(namespaceName, true);
3049 if (!OidIsValid(namespaceId))
3052 * First use of this temp namespace in this database; create it. The
3053 * temp namespaces are always owned by the superuser. We leave their
3054 * permissions at default --- i.e., no access except to superuser ---
3055 * to ensure that unprivileged users can't peek at other backends'
3056 * temp tables. This works because the places that access the temp
3057 * namespace for my own backend skip permissions checks on it.
3059 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3060 /* Advance command counter to make namespace visible */
3061 CommandCounterIncrement();
3066 * If the namespace already exists, clean it out (in case the former
3067 * owner crashed without doing so).
3069 RemoveTempRelations(namespaceId);
3073 * If the corresponding toast-table namespace doesn't exist yet, create
3074 * it. (We assume there is no need to clean it out if it does exist, since
3075 * dropping a parent table should make its toast table go away.)
3077 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3080 toastspaceId = get_namespace_oid(namespaceName, true);
3081 if (!OidIsValid(toastspaceId))
3083 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3084 /* Advance command counter to make namespace visible */
3085 CommandCounterIncrement();
3089 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3090 * so all our work could be undone by transaction rollback. Set flag for
3091 * AtEOXact_Namespace to know what to do.
3093 myTempNamespace = namespaceId;
3094 myTempToastNamespace = toastspaceId;
3096 /* It should not be done already. */
3097 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3098 myTempNamespaceSubID = GetCurrentSubTransactionId();
3100 baseSearchPathValid = false; /* need to rebuild list */
3104 * End-of-transaction cleanup for namespaces.
3107 AtEOXact_Namespace(bool isCommit)
3110 * If we abort the transaction in which a temp namespace was selected,
3111 * we'll have to do any creation or cleanout work over again. So, just
3112 * forget the namespace entirely until next time. On the other hand, if
3113 * we commit then register an exit callback to clean out the temp tables
3114 * at backend shutdown. (We only want to register the callback once per
3115 * session, so this is a good place to do it.)
3117 if (myTempNamespaceSubID != InvalidSubTransactionId)
3120 on_shmem_exit(RemoveTempRelationsCallback, 0);
3123 myTempNamespace = InvalidOid;
3124 myTempToastNamespace = InvalidOid;
3125 baseSearchPathValid = false; /* need to rebuild list */
3127 myTempNamespaceSubID = InvalidSubTransactionId;
3131 * Clean up if someone failed to do PopOverrideSearchPath
3136 elog(WARNING, "leaked override search path");
3137 while (overrideStack)
3139 OverrideStackEntry *entry;
3141 entry = (OverrideStackEntry *) linitial(overrideStack);
3142 overrideStack = list_delete_first(overrideStack);
3143 list_free(entry->searchPath);
3146 /* If not baseSearchPathValid, this is useless but harmless */
3147 activeSearchPath = baseSearchPath;
3148 activeCreationNamespace = baseCreationNamespace;
3149 activeTempCreationPending = baseTempCreationPending;
3154 * AtEOSubXact_Namespace
3156 * At subtransaction commit, propagate the temp-namespace-creation
3157 * flag to the parent subtransaction.
3159 * At subtransaction abort, forget the flag if we set it up.
3162 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3163 SubTransactionId parentSubid)
3165 OverrideStackEntry *entry;
3167 if (myTempNamespaceSubID == mySubid)
3170 myTempNamespaceSubID = parentSubid;
3173 myTempNamespaceSubID = InvalidSubTransactionId;
3174 /* TEMP namespace creation failed, so reset state */
3175 myTempNamespace = InvalidOid;
3176 myTempToastNamespace = InvalidOid;
3177 baseSearchPathValid = false; /* need to rebuild list */
3182 * Clean up if someone failed to do PopOverrideSearchPath
3184 while (overrideStack)
3186 entry = (OverrideStackEntry *) linitial(overrideStack);
3187 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3190 elog(WARNING, "leaked override search path");
3191 overrideStack = list_delete_first(overrideStack);
3192 list_free(entry->searchPath);
3196 /* Activate the next level down. */
3199 entry = (OverrideStackEntry *) linitial(overrideStack);
3200 activeSearchPath = entry->searchPath;
3201 activeCreationNamespace = entry->creationNamespace;
3202 activeTempCreationPending = false; /* XXX is this OK? */
3206 /* If not baseSearchPathValid, this is useless but harmless */
3207 activeSearchPath = baseSearchPath;
3208 activeCreationNamespace = baseCreationNamespace;
3209 activeTempCreationPending = baseTempCreationPending;
3214 * Remove all relations in the specified temp namespace.
3216 * This is called at backend shutdown (if we made any temp relations).
3217 * It is also called when we begin using a pre-existing temp namespace,
3218 * in order to clean out any relations that might have been created by
3219 * a crashed backend.
3222 RemoveTempRelations(Oid tempNamespaceId)
3224 ObjectAddress object;
3227 * We want to get rid of everything in the target namespace, but not the
3228 * namespace itself (deleting it only to recreate it later would be a
3229 * waste of cycles). We do this by finding everything that has a
3230 * dependency on the namespace.
3232 object.classId = NamespaceRelationId;
3233 object.objectId = tempNamespaceId;
3234 object.objectSubId = 0;
3236 deleteWhatDependsOn(&object, false);
3240 * Callback to remove temp relations at backend exit.
3243 RemoveTempRelationsCallback(int code, Datum arg)
3245 if (OidIsValid(myTempNamespace)) /* should always be true */
3247 /* Need to ensure we have a usable transaction. */
3248 AbortOutOfAnyTransaction();
3249 StartTransactionCommand();
3251 RemoveTempRelations(myTempNamespace);
3253 CommitTransactionCommand();
3258 * Remove all temp tables from the temporary namespace.
3261 ResetTempTableNamespace(void)
3263 if (OidIsValid(myTempNamespace))
3264 RemoveTempRelations(myTempNamespace);
3269 * Routines for handling the GUC variable 'search_path'.
3272 /* assign_hook: validate new search_path, do extra actions as needed */
3274 assign_search_path(const char *newval, bool doit, GucSource source)
3280 /* Need a modifiable copy of string */
3281 rawname = pstrdup(newval);
3283 /* Parse string into list of identifiers */
3284 if (!SplitIdentifierString(rawname, ',', &namelist))
3286 /* syntax error in name list */
3288 list_free(namelist);
3293 * If we aren't inside a transaction, we cannot do database access so
3294 * cannot verify the individual names. Must accept the list on faith.
3296 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3299 * Verify that all the names are either valid namespace names or
3300 * "$user" or "pg_temp". We do not require $user to correspond to a
3301 * valid namespace, and pg_temp might not exist yet. We do not check
3302 * for USAGE rights, either; should we?
3304 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3305 * DATABASE SET or ALTER USER SET command. It could be that the
3306 * intended use of the search path is for some other database, so we
3307 * should not error out if it mentions schemas not present in the
3308 * current database. We reduce the message to NOTICE instead.
3310 foreach(l, namelist)
3312 char *curname = (char *) lfirst(l);
3314 if (strcmp(curname, "$user") == 0)
3316 if (strcmp(curname, "pg_temp") == 0)
3318 if (!SearchSysCacheExists1(NAMESPACENAME,
3319 CStringGetDatum(curname)))
3320 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3321 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3322 errmsg("schema \"%s\" does not exist", curname)));
3327 list_free(namelist);
3330 * We mark the path as needing recomputation, but don't do anything until
3331 * it's needed. This avoids trying to do database access during GUC
3335 baseSearchPathValid = false;
3341 * InitializeSearchPath: initialize module during InitPostgres.
3343 * This is called after we are up enough to be able to do catalog lookups.
3346 InitializeSearchPath(void)
3348 if (IsBootstrapProcessingMode())
3351 * In bootstrap mode, the search path must be 'pg_catalog' so that
3352 * tables are created in the proper namespace; ignore the GUC setting.
3354 MemoryContext oldcxt;
3356 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3357 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3358 MemoryContextSwitchTo(oldcxt);
3359 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3360 baseTempCreationPending = false;
3361 baseSearchPathValid = true;
3362 namespaceUser = GetUserId();
3363 activeSearchPath = baseSearchPath;
3364 activeCreationNamespace = baseCreationNamespace;
3365 activeTempCreationPending = baseTempCreationPending;
3370 * In normal mode, arrange for a callback on any syscache invalidation
3371 * of pg_namespace rows.
3373 CacheRegisterSyscacheCallback(NAMESPACEOID,
3376 /* Force search path to be recomputed on next use */
3377 baseSearchPathValid = false;
3383 * Syscache inval callback function
3386 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3388 /* Force search path to be recomputed on next use */
3389 baseSearchPathValid = false;
3393 * Fetch the active search path. The return value is a palloc'ed list
3394 * of OIDs; the caller is responsible for freeing this storage as
3397 * The returned list includes the implicitly-prepended namespaces only if
3398 * includeImplicit is true.
3400 * Note: calling this may result in a CommandCounterIncrement operation,
3401 * if we have to create or clean out the temp namespace.
3404 fetch_search_path(bool includeImplicit)
3408 recomputeNamespacePath();
3411 * If the temp namespace should be first, force it to exist. This is so
3412 * that callers can trust the result to reflect the actual default
3413 * creation namespace. It's a bit bogus to do this here, since
3414 * current_schema() is supposedly a stable function without side-effects,
3415 * but the alternatives seem worse.
3417 if (activeTempCreationPending)
3419 InitTempTableNamespace();
3420 recomputeNamespacePath();
3423 result = list_copy(activeSearchPath);
3424 if (!includeImplicit)
3426 while (result && linitial_oid(result) != activeCreationNamespace)
3427 result = list_delete_first(result);
3434 * Fetch the active search path into a caller-allocated array of OIDs.
3435 * Returns the number of path entries. (If this is more than sarray_len,
3436 * then the data didn't fit and is not all stored.)
3438 * The returned list always includes the implicitly-prepended namespaces,
3439 * but never includes the temp namespace. (This is suitable for existing
3440 * users, which would want to ignore the temp namespace anyway.) This
3441 * definition allows us to not worry about initializing the temp namespace.
3444 fetch_search_path_array(Oid *sarray, int sarray_len)
3449 recomputeNamespacePath();
3451 foreach(l, activeSearchPath)
3453 Oid namespaceId = lfirst_oid(l);
3455 if (namespaceId == myTempNamespace)
3456 continue; /* do not include temp namespace */
3458 if (count < sarray_len)
3459 sarray[count] = namespaceId;
3468 * Export the FooIsVisible functions as SQL-callable functions.
3470 * Note: as of Postgres 8.4, these will silently return NULL if called on
3471 * a nonexistent object OID, rather than failing. This is to avoid race
3472 * condition errors when a query that's scanning a catalog using an MVCC
3473 * snapshot uses one of these functions. The underlying IsVisible functions
3474 * operate on SnapshotNow semantics and so might see the object as already
3475 * gone when it's still visible to the MVCC snapshot. (There is no race
3476 * condition in the current coding because we don't accept sinval messages
3477 * between the SearchSysCacheExists test and the subsequent lookup.)
3481 pg_table_is_visible(PG_FUNCTION_ARGS)
3483 Oid oid = PG_GETARG_OID(0);
3485 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3488 PG_RETURN_BOOL(RelationIsVisible(oid));
3492 pg_type_is_visible(PG_FUNCTION_ARGS)
3494 Oid oid = PG_GETARG_OID(0);
3496 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3499 PG_RETURN_BOOL(TypeIsVisible(oid));
3503 pg_function_is_visible(PG_FUNCTION_ARGS)
3505 Oid oid = PG_GETARG_OID(0);
3507 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3510 PG_RETURN_BOOL(FunctionIsVisible(oid));
3514 pg_operator_is_visible(PG_FUNCTION_ARGS)
3516 Oid oid = PG_GETARG_OID(0);
3518 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3521 PG_RETURN_BOOL(OperatorIsVisible(oid));
3525 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3527 Oid oid = PG_GETARG_OID(0);
3529 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3532 PG_RETURN_BOOL(OpclassIsVisible(oid));
3536 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3538 Oid oid = PG_GETARG_OID(0);
3540 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3543 PG_RETURN_BOOL(ConversionIsVisible(oid));
3547 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3549 Oid oid = PG_GETARG_OID(0);
3551 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3554 PG_RETURN_BOOL(TSParserIsVisible(oid));
3558 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3560 Oid oid = PG_GETARG_OID(0);
3562 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3565 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3569 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3571 Oid oid = PG_GETARG_OID(0);
3573 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3576 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3580 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3582 Oid oid = PG_GETARG_OID(0);
3584 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3587 PG_RETURN_BOOL(TSConfigIsVisible(oid));
3591 pg_my_temp_schema(PG_FUNCTION_ARGS)
3593 PG_RETURN_OID(myTempNamespace);
3597 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3599 Oid oid = PG_GETARG_OID(0);
3601 PG_RETURN_BOOL(isOtherTempNamespace(oid));