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 * $PostgreSQL: pgsql/src/backend/catalog/namespace.c,v 1.123 2010/02/14 18:42:13 rhaas Exp $
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 = GetSysCacheOid1(NAMESPACENAME,
336 CStringGetDatum(newRelation->schemaname));
337 if (!OidIsValid(namespaceId))
339 (errcode(ERRCODE_UNDEFINED_SCHEMA),
340 errmsg("schema \"%s\" does not exist",
341 newRelation->schemaname)));
342 /* we do not check for USAGE rights here! */
346 /* use the default creation namespace */
347 recomputeNamespacePath();
348 if (activeTempCreationPending)
350 /* Need to initialize temp namespace */
351 InitTempTableNamespace();
352 return myTempNamespace;
354 namespaceId = activeCreationNamespace;
355 if (!OidIsValid(namespaceId))
357 (errcode(ERRCODE_UNDEFINED_SCHEMA),
358 errmsg("no schema has been selected to create in")));
361 /* Note: callers will check for CREATE rights when appropriate */
368 * Try to resolve an unqualified relation name.
369 * Returns OID if relation found in search path, else InvalidOid.
372 RelnameGetRelid(const char *relname)
377 recomputeNamespacePath();
379 foreach(l, activeSearchPath)
381 Oid namespaceId = lfirst_oid(l);
383 relid = get_relname_relid(relname, namespaceId);
384 if (OidIsValid(relid))
388 /* Not found in path */
395 * Determine whether a relation (identified by OID) is visible in the
396 * current search path. Visible means "would be found by searching
397 * for the unqualified relation name".
400 RelationIsVisible(Oid relid)
403 Form_pg_class relform;
407 reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
408 if (!HeapTupleIsValid(reltup))
409 elog(ERROR, "cache lookup failed for relation %u", relid);
410 relform = (Form_pg_class) GETSTRUCT(reltup);
412 recomputeNamespacePath();
415 * Quick check: if it ain't in the path at all, it ain't visible. Items in
416 * the system namespace are surely in the path and so we needn't even do
417 * list_member_oid() for them.
419 relnamespace = relform->relnamespace;
420 if (relnamespace != PG_CATALOG_NAMESPACE &&
421 !list_member_oid(activeSearchPath, relnamespace))
426 * If it is in the path, it might still not be visible; it could be
427 * hidden by another relation of the same name earlier in the path. So
428 * we must do a slow check for conflicting relations.
430 char *relname = NameStr(relform->relname);
434 foreach(l, activeSearchPath)
436 Oid namespaceId = lfirst_oid(l);
438 if (namespaceId == relnamespace)
440 /* Found it first in path */
444 if (OidIsValid(get_relname_relid(relname, namespaceId)))
446 /* Found something else first in path */
452 ReleaseSysCache(reltup);
460 * Try to resolve an unqualified datatype name.
461 * Returns OID if type found in search path, else InvalidOid.
463 * This is essentially the same as RelnameGetRelid.
466 TypenameGetTypid(const char *typname)
471 recomputeNamespacePath();
473 foreach(l, activeSearchPath)
475 Oid namespaceId = lfirst_oid(l);
477 typid = GetSysCacheOid2(TYPENAMENSP,
478 PointerGetDatum(typname),
479 ObjectIdGetDatum(namespaceId));
480 if (OidIsValid(typid))
484 /* Not found in path */
490 * Determine whether a type (identified by OID) is visible in the
491 * current search path. Visible means "would be found by searching
492 * for the unqualified type name".
495 TypeIsVisible(Oid typid)
498 Form_pg_type typform;
502 typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
503 if (!HeapTupleIsValid(typtup))
504 elog(ERROR, "cache lookup failed for type %u", typid);
505 typform = (Form_pg_type) GETSTRUCT(typtup);
507 recomputeNamespacePath();
510 * Quick check: if it ain't in the path at all, it ain't visible. Items in
511 * the system namespace are surely in the path and so we needn't even do
512 * list_member_oid() for them.
514 typnamespace = typform->typnamespace;
515 if (typnamespace != PG_CATALOG_NAMESPACE &&
516 !list_member_oid(activeSearchPath, typnamespace))
521 * If it is in the path, it might still not be visible; it could be
522 * hidden by another type of the same name earlier in the path. So we
523 * must do a slow check for conflicting types.
525 char *typname = NameStr(typform->typname);
529 foreach(l, activeSearchPath)
531 Oid namespaceId = lfirst_oid(l);
533 if (namespaceId == typnamespace)
535 /* Found it first in path */
539 if (SearchSysCacheExists2(TYPENAMENSP,
540 PointerGetDatum(typname),
541 ObjectIdGetDatum(namespaceId)))
543 /* Found something else first in path */
549 ReleaseSysCache(typtup);
556 * FuncnameGetCandidates
557 * Given a possibly-qualified function name and argument count,
558 * retrieve a list of the possible matches.
560 * If nargs is -1, we return all functions matching the given name,
561 * regardless of argument count. (argnames must be NIL, and expand_variadic
562 * and expand_defaults must be false, in this case.)
564 * If argnames isn't NIL, we are considering a named- or mixed-notation call,
565 * and only functions having all the listed argument names will be returned.
566 * (We assume that length(argnames) <= nargs and all the passed-in names are
567 * distinct.) The returned structs will include an argnumbers array showing
568 * the actual argument index for each logical argument position.
570 * If expand_variadic is true, then variadic functions having the same number
571 * or fewer arguments will be retrieved, with the variadic argument and any
572 * additional argument positions filled with the variadic element type.
573 * nvargs in the returned struct is set to the number of such arguments.
574 * If expand_variadic is false, variadic arguments are not treated specially,
575 * and the returned nvargs will always be zero.
577 * If expand_defaults is true, functions that could match after insertion of
578 * default argument values will also be retrieved. In this case the returned
579 * structs could have nargs > passed-in nargs, and ndargs is set to the number
580 * of additional args (which can be retrieved from the function's
581 * proargdefaults entry).
583 * It is not possible for nvargs and ndargs to both be nonzero in the same
584 * list entry, since default insertion allows matches to functions with more
585 * than nargs arguments while the variadic transformation requires the same
588 * When argnames isn't NIL, the returned args[] type arrays are not ordered
589 * according to the functions' declarations, but rather according to the call:
590 * first any positional arguments, then the named arguments, then defaulted
591 * arguments (if needed and allowed by expand_defaults). The argnumbers[]
592 * array can be used to map this back to the catalog information.
593 * argnumbers[k] is set to the proargtypes index of the k'th call argument.
595 * We search a single namespace if the function name is qualified, else
596 * all namespaces in the search path. In the multiple-namespace case,
597 * we arrange for entries in earlier namespaces to mask identical entries in
600 * When expanding variadics, we arrange for non-variadic functions to mask
601 * variadic ones if the expanded argument list is the same. It is still
602 * possible for there to be conflicts between different variadic functions,
605 * It is guaranteed that the return list will never contain multiple entries
606 * with identical argument lists. When expand_defaults is true, the entries
607 * could have more than nargs positions, but we still guarantee that they are
608 * distinct in the first nargs positions. However, if argnames isn't NIL or
609 * either expand_variadic or expand_defaults is true, there might be multiple
610 * candidate functions that expand to identical argument lists. Rather than
611 * throw error here, we report such situations by returning a single entry
612 * with oid = 0 that represents a set of such conflicting candidates.
613 * The caller might end up discarding such an entry anyway, but if it selects
614 * such an entry it should react as though the call were ambiguous.
617 FuncnameGetCandidates(List *names, int nargs, List *argnames,
618 bool expand_variadic, bool expand_defaults)
620 FuncCandidateList resultList = NULL;
621 bool any_special = false;
628 /* check for caller error */
629 Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
631 /* deconstruct the name list */
632 DeconstructQualifiedName(names, &schemaname, &funcname);
636 /* use exact schema given */
637 namespaceId = LookupExplicitNamespace(schemaname);
641 /* flag to indicate we need namespace search */
642 namespaceId = InvalidOid;
643 recomputeNamespacePath();
646 /* Search syscache by name only */
647 catlist = SearchSysCacheList1(PROCNAMEARGSNSP, CStringGetDatum(funcname));
649 for (i = 0; i < catlist->n_members; i++)
651 HeapTuple proctup = &catlist->members[i]->tuple;
652 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
653 int pronargs = procform->pronargs;
659 int *argnumbers = NULL;
660 FuncCandidateList newResult;
662 if (OidIsValid(namespaceId))
664 /* Consider only procs in specified namespace */
665 if (procform->pronamespace != namespaceId)
671 * Consider only procs that are in the search path and are not in
672 * the temp namespace.
676 foreach(nsp, activeSearchPath)
678 if (procform->pronamespace == lfirst_oid(nsp) &&
679 procform->pronamespace != myTempNamespace)
684 continue; /* proc is not in search path */
690 * Call uses named or mixed notation
692 * Named or mixed notation can match a variadic function only
693 * if expand_variadic is off; otherwise there is no way to match
694 * the presumed-nameless parameters expanded from the variadic
697 if (OidIsValid(procform->provariadic) && expand_variadic)
699 va_elem_type = InvalidOid;
703 * Check argument count.
705 Assert(nargs >= 0); /* -1 not supported with argnames */
707 if (pronargs > nargs && expand_defaults)
709 /* Ignore if not enough default expressions */
710 if (nargs + procform->pronargdefaults < pronargs)
715 use_defaults = false;
717 /* Ignore if it doesn't match requested argument count */
718 if (pronargs != nargs && !use_defaults)
721 /* Check for argument name match, generate positional mapping */
722 if (!MatchNamedCall(proctup, nargs, argnames,
726 /* Named argument matching is always "special" */
732 * Call uses positional notation
734 * Check if function is variadic, and get variadic element type if
735 * so. If expand_variadic is false, we should just ignore
738 if (pronargs <= nargs && expand_variadic)
740 va_elem_type = procform->provariadic;
741 variadic = OidIsValid(va_elem_type);
742 any_special |= variadic;
746 va_elem_type = InvalidOid;
751 * Check if function can match by using parameter defaults.
753 if (pronargs > nargs && expand_defaults)
755 /* Ignore if not enough default expressions */
756 if (nargs + procform->pronargdefaults < pronargs)
762 use_defaults = false;
764 /* Ignore if it doesn't match requested argument count */
765 if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
770 * We must compute the effective argument list so that we can easily
771 * compare it to earlier results. We waste a palloc cycle if it gets
772 * masked by an earlier result, but really that's a pretty infrequent
773 * case so it's not worth worrying about.
775 effective_nargs = Max(pronargs, nargs);
776 newResult = (FuncCandidateList)
777 palloc(sizeof(struct _FuncCandidateList) - sizeof(Oid)
778 + effective_nargs * sizeof(Oid));
779 newResult->pathpos = pathpos;
780 newResult->oid = HeapTupleGetOid(proctup);
781 newResult->nargs = effective_nargs;
782 newResult->argnumbers = argnumbers;
785 /* Re-order the argument types into call's logical order */
786 Oid *proargtypes = procform->proargtypes.values;
789 for (i = 0; i < pronargs; i++)
790 newResult->args[i] = proargtypes[argnumbers[i]];
794 /* Simple positional case, just copy proargtypes as-is */
795 memcpy(newResult->args, procform->proargtypes.values,
796 pronargs * sizeof(Oid));
802 newResult->nvargs = effective_nargs - pronargs + 1;
803 /* Expand variadic argument into N copies of element type */
804 for (i = pronargs - 1; i < effective_nargs; i++)
805 newResult->args[i] = va_elem_type;
808 newResult->nvargs = 0;
809 newResult->ndargs = use_defaults ? pronargs - nargs : 0;
812 * Does it have the same arguments as something we already accepted?
813 * If so, decide what to do to avoid returning duplicate argument
814 * lists. We can skip this check for the single-namespace case if no
815 * special (named, variadic or defaults) match has been made, since
816 * then the unique index on pg_proc guarantees all the matches have
817 * different argument lists.
819 if (resultList != NULL &&
820 (any_special || !OidIsValid(namespaceId)))
823 * If we have an ordered list from SearchSysCacheList (the normal
824 * case), then any conflicting proc must immediately adjoin this
825 * one in the list, so we only need to look at the newest result
826 * item. If we have an unordered list, we have to scan the whole
827 * result list. Also, if either the current candidate or any
828 * previous candidate is a special match, we can't assume that
829 * conflicts are adjacent.
831 * We ignore defaulted arguments in deciding what is a match.
833 FuncCandidateList prevResult;
835 if (catlist->ordered && !any_special)
837 /* ndargs must be 0 if !any_special */
838 if (effective_nargs == resultList->nargs &&
839 memcmp(newResult->args,
841 effective_nargs * sizeof(Oid)) == 0)
842 prevResult = resultList;
848 int cmp_nargs = newResult->nargs - newResult->ndargs;
850 for (prevResult = resultList;
852 prevResult = prevResult->next)
854 if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
855 memcmp(newResult->args,
857 cmp_nargs * sizeof(Oid)) == 0)
865 * We have a match with a previous result. Decide which one
866 * to keep, or mark it ambiguous if we can't decide. The
867 * logic here is preference > 0 means prefer the old result,
868 * preference < 0 means prefer the new, preference = 0 means
873 if (pathpos != prevResult->pathpos)
876 * Prefer the one that's earlier in the search path.
878 preference = pathpos - prevResult->pathpos;
880 else if (variadic && prevResult->nvargs == 0)
883 * With variadic functions we could have, for example,
884 * both foo(numeric) and foo(variadic numeric[]) in the
885 * same namespace; if so we prefer the non-variadic match
886 * on efficiency grounds.
890 else if (!variadic && prevResult->nvargs > 0)
897 * We can't decide. This can happen with, for example,
898 * both foo(numeric, variadic numeric[]) and
899 * foo(variadic numeric[]) in the same namespace, or
900 * both foo(int) and foo (int, int default something)
901 * in the same namespace, or both foo(a int, b text)
902 * and foo(b text, a int) in the same namespace.
910 /* keep previous result */
914 else if (preference < 0)
916 /* remove previous result from the list */
917 if (prevResult == resultList)
918 resultList = prevResult->next;
921 FuncCandidateList prevPrevResult;
923 for (prevPrevResult = resultList;
925 prevPrevResult = prevPrevResult->next)
927 if (prevResult == prevPrevResult->next)
929 prevPrevResult->next = prevResult->next;
933 Assert(prevPrevResult); /* assert we found it */
936 /* fall through to add newResult to list */
940 /* mark old result as ambiguous, discard new */
941 prevResult->oid = InvalidOid;
949 * Okay to add it to result list
951 newResult->next = resultList;
952 resultList = newResult;
955 ReleaseSysCacheList(catlist);
962 * Given a pg_proc heap tuple and a call's list of argument names,
963 * check whether the function could match the call.
965 * The call could match if all supplied argument names are accepted by
966 * the function, in positions after the last positional argument, and there
967 * are defaults for all unsupplied arguments.
969 * The number of positional arguments is nargs - list_length(argnames).
970 * Note caller has already done basic checks on argument count.
972 * On match, return true and fill *argnumbers with a palloc'd array showing
973 * the mapping from call argument positions to actual function argument
974 * numbers. Defaulted arguments are included in this map, at positions
975 * after the last supplied argument.
978 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
981 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
982 int pronargs = procform->pronargs;
983 int numposargs = nargs - list_length(argnames);
988 bool arggiven[FUNC_MAX_ARGS];
990 int ap; /* call args position */
991 int pp; /* proargs position */
994 Assert(argnames != NIL);
995 Assert(numposargs >= 0);
996 Assert(nargs <= pronargs);
998 /* Ignore this function if its proargnames is null */
999 (void) SysCacheGetAttr(PROCOID, proctup, Anum_pg_proc_proargnames,
1004 /* OK, let's extract the argument names and types */
1005 pronallargs = get_func_arg_info(proctup,
1006 &p_argtypes, &p_argnames, &p_argmodes);
1007 Assert(p_argnames != NULL);
1009 /* initialize state for matching */
1010 *argnumbers = (int *) palloc(pronargs * sizeof(int));
1011 memset(arggiven, false, pronargs * sizeof(bool));
1013 /* there are numposargs positional args before the named args */
1014 for (ap = 0; ap < numposargs; ap++)
1016 (*argnumbers)[ap] = ap;
1017 arggiven[ap] = true;
1020 /* now examine the named args */
1021 foreach(lc, argnames)
1023 char *argname = (char *) lfirst(lc);
1029 for (i = 0; i < pronallargs; i++)
1031 /* consider only input parameters */
1033 (p_argmodes[i] != FUNC_PARAM_IN &&
1034 p_argmodes[i] != FUNC_PARAM_INOUT &&
1035 p_argmodes[i] != FUNC_PARAM_VARIADIC))
1037 if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1039 /* fail if argname matches a positional argument */
1042 arggiven[pp] = true;
1043 (*argnumbers)[ap] = pp;
1047 /* increase pp only for input parameters */
1050 /* if name isn't in proargnames, fail */
1056 Assert(ap == nargs); /* processed all actual parameters */
1058 /* Check for default arguments */
1059 if (nargs < pronargs)
1061 int first_arg_with_default = pronargs - procform->pronargdefaults;
1063 for (pp = numposargs; pp < pronargs; pp++)
1067 /* fail if arg not given and no default available */
1068 if (pp < first_arg_with_default)
1070 (*argnumbers)[ap++] = pp;
1074 Assert(ap == pronargs); /* processed all function parameters */
1081 * Determine whether a function (identified by OID) is visible in the
1082 * current search path. Visible means "would be found by searching
1083 * for the unqualified function name with exact argument matches".
1086 FunctionIsVisible(Oid funcid)
1089 Form_pg_proc procform;
1093 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1094 if (!HeapTupleIsValid(proctup))
1095 elog(ERROR, "cache lookup failed for function %u", funcid);
1096 procform = (Form_pg_proc) GETSTRUCT(proctup);
1098 recomputeNamespacePath();
1101 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1102 * the system namespace are surely in the path and so we needn't even do
1103 * list_member_oid() for them.
1105 pronamespace = procform->pronamespace;
1106 if (pronamespace != PG_CATALOG_NAMESPACE &&
1107 !list_member_oid(activeSearchPath, pronamespace))
1112 * If it is in the path, it might still not be visible; it could be
1113 * hidden by another proc of the same name and arguments earlier in
1114 * the path. So we must do a slow check to see if this is the same
1115 * proc that would be found by FuncnameGetCandidates.
1117 char *proname = NameStr(procform->proname);
1118 int nargs = procform->pronargs;
1119 FuncCandidateList clist;
1123 clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1124 nargs, NIL, false, false);
1126 for (; clist; clist = clist->next)
1128 if (memcmp(clist->args, procform->proargtypes.values,
1129 nargs * sizeof(Oid)) == 0)
1131 /* Found the expected entry; is it the right proc? */
1132 visible = (clist->oid == funcid);
1138 ReleaseSysCache(proctup);
1146 * Given a possibly-qualified operator name and exact input datatypes,
1147 * look up the operator. Returns InvalidOid if not found.
1149 * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1152 * If the operator name is not schema-qualified, it is sought in the current
1153 * namespace search path.
1156 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1163 /* deconstruct the name list */
1164 DeconstructQualifiedName(names, &schemaname, &opername);
1168 /* search only in exact schema given */
1172 namespaceId = LookupExplicitNamespace(schemaname);
1173 opertup = SearchSysCache4(OPERNAMENSP,
1174 CStringGetDatum(opername),
1175 ObjectIdGetDatum(oprleft),
1176 ObjectIdGetDatum(oprright),
1177 ObjectIdGetDatum(namespaceId));
1178 if (HeapTupleIsValid(opertup))
1180 Oid result = HeapTupleGetOid(opertup);
1182 ReleaseSysCache(opertup);
1188 /* Search syscache by name and argument types */
1189 catlist = SearchSysCacheList3(OPERNAMENSP,
1190 CStringGetDatum(opername),
1191 ObjectIdGetDatum(oprleft),
1192 ObjectIdGetDatum(oprright));
1194 if (catlist->n_members == 0)
1196 /* no hope, fall out early */
1197 ReleaseSysCacheList(catlist);
1202 * We have to find the list member that is first in the search path, if
1203 * there's more than one. This doubly-nested loop looks ugly, but in
1204 * practice there should usually be few catlist members.
1206 recomputeNamespacePath();
1208 foreach(l, activeSearchPath)
1210 Oid namespaceId = lfirst_oid(l);
1213 if (namespaceId == myTempNamespace)
1214 continue; /* do not look in temp namespace */
1216 for (i = 0; i < catlist->n_members; i++)
1218 HeapTuple opertup = &catlist->members[i]->tuple;
1219 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1221 if (operform->oprnamespace == namespaceId)
1223 Oid result = HeapTupleGetOid(opertup);
1225 ReleaseSysCacheList(catlist);
1231 ReleaseSysCacheList(catlist);
1236 * OpernameGetCandidates
1237 * Given a possibly-qualified operator name and operator kind,
1238 * retrieve a list of the possible matches.
1240 * If oprkind is '\0', we return all operators matching the given name,
1241 * regardless of arguments.
1243 * We search a single namespace if the operator name is qualified, else
1244 * all namespaces in the search path. The return list will never contain
1245 * multiple entries with identical argument lists --- in the multiple-
1246 * namespace case, we arrange for entries in earlier namespaces to mask
1247 * identical entries in later namespaces.
1249 * The returned items always have two args[] entries --- one or the other
1250 * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1253 OpernameGetCandidates(List *names, char oprkind)
1255 FuncCandidateList resultList = NULL;
1256 char *resultSpace = NULL;
1264 /* deconstruct the name list */
1265 DeconstructQualifiedName(names, &schemaname, &opername);
1269 /* use exact schema given */
1270 namespaceId = LookupExplicitNamespace(schemaname);
1274 /* flag to indicate we need namespace search */
1275 namespaceId = InvalidOid;
1276 recomputeNamespacePath();
1279 /* Search syscache by name only */
1280 catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1283 * In typical scenarios, most if not all of the operators found by the
1284 * catcache search will end up getting returned; and there can be quite a
1285 * few, for common operator names such as '=' or '+'. To reduce the time
1286 * spent in palloc, we allocate the result space as an array large enough
1287 * to hold all the operators. The original coding of this routine did a
1288 * separate palloc for each operator, but profiling revealed that the
1289 * pallocs used an unreasonably large fraction of parsing time.
1291 #define SPACE_PER_OP MAXALIGN(sizeof(struct _FuncCandidateList) + sizeof(Oid))
1293 if (catlist->n_members > 0)
1294 resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1296 for (i = 0; i < catlist->n_members; i++)
1298 HeapTuple opertup = &catlist->members[i]->tuple;
1299 Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1301 FuncCandidateList newResult;
1303 /* Ignore operators of wrong kind, if specific kind requested */
1304 if (oprkind && operform->oprkind != oprkind)
1307 if (OidIsValid(namespaceId))
1309 /* Consider only opers in specified namespace */
1310 if (operform->oprnamespace != namespaceId)
1312 /* No need to check args, they must all be different */
1317 * Consider only opers that are in the search path and are not in
1318 * the temp namespace.
1322 foreach(nsp, activeSearchPath)
1324 if (operform->oprnamespace == lfirst_oid(nsp) &&
1325 operform->oprnamespace != myTempNamespace)
1330 continue; /* oper is not in search path */
1333 * Okay, it's in the search path, but does it have the same
1334 * arguments as something we already accepted? If so, keep only
1335 * the one that appears earlier in the search path.
1337 * If we have an ordered list from SearchSysCacheList (the normal
1338 * case), then any conflicting oper must immediately adjoin this
1339 * one in the list, so we only need to look at the newest result
1340 * item. If we have an unordered list, we have to scan the whole
1345 FuncCandidateList prevResult;
1347 if (catlist->ordered)
1349 if (operform->oprleft == resultList->args[0] &&
1350 operform->oprright == resultList->args[1])
1351 prevResult = resultList;
1357 for (prevResult = resultList;
1359 prevResult = prevResult->next)
1361 if (operform->oprleft == prevResult->args[0] &&
1362 operform->oprright == prevResult->args[1])
1368 /* We have a match with a previous result */
1369 Assert(pathpos != prevResult->pathpos);
1370 if (pathpos > prevResult->pathpos)
1371 continue; /* keep previous result */
1372 /* replace previous result */
1373 prevResult->pathpos = pathpos;
1374 prevResult->oid = HeapTupleGetOid(opertup);
1375 continue; /* args are same, of course */
1381 * Okay to add it to result list
1383 newResult = (FuncCandidateList) (resultSpace + nextResult);
1384 nextResult += SPACE_PER_OP;
1386 newResult->pathpos = pathpos;
1387 newResult->oid = HeapTupleGetOid(opertup);
1388 newResult->nargs = 2;
1389 newResult->nvargs = 0;
1390 newResult->ndargs = 0;
1391 newResult->argnumbers = NULL;
1392 newResult->args[0] = operform->oprleft;
1393 newResult->args[1] = operform->oprright;
1394 newResult->next = resultList;
1395 resultList = newResult;
1398 ReleaseSysCacheList(catlist);
1405 * Determine whether an operator (identified by OID) is visible in the
1406 * current search path. Visible means "would be found by searching
1407 * for the unqualified operator name with exact argument matches".
1410 OperatorIsVisible(Oid oprid)
1413 Form_pg_operator oprform;
1417 oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1418 if (!HeapTupleIsValid(oprtup))
1419 elog(ERROR, "cache lookup failed for operator %u", oprid);
1420 oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1422 recomputeNamespacePath();
1425 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1426 * the system namespace are surely in the path and so we needn't even do
1427 * list_member_oid() for them.
1429 oprnamespace = oprform->oprnamespace;
1430 if (oprnamespace != PG_CATALOG_NAMESPACE &&
1431 !list_member_oid(activeSearchPath, oprnamespace))
1436 * If it is in the path, it might still not be visible; it could be
1437 * hidden by another operator of the same name and arguments earlier
1438 * in the path. So we must do a slow check to see if this is the same
1439 * operator that would be found by OpernameGetOprId.
1441 char *oprname = NameStr(oprform->oprname);
1443 visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1444 oprform->oprleft, oprform->oprright)
1448 ReleaseSysCache(oprtup);
1455 * OpclassnameGetOpcid
1456 * Try to resolve an unqualified index opclass name.
1457 * Returns OID if opclass found in search path, else InvalidOid.
1459 * This is essentially the same as TypenameGetTypid, but we have to have
1460 * an extra argument for the index AM OID.
1463 OpclassnameGetOpcid(Oid amid, const char *opcname)
1468 recomputeNamespacePath();
1470 foreach(l, activeSearchPath)
1472 Oid namespaceId = lfirst_oid(l);
1474 if (namespaceId == myTempNamespace)
1475 continue; /* do not look in temp namespace */
1477 opcid = GetSysCacheOid3(CLAAMNAMENSP,
1478 ObjectIdGetDatum(amid),
1479 PointerGetDatum(opcname),
1480 ObjectIdGetDatum(namespaceId));
1481 if (OidIsValid(opcid))
1485 /* Not found in path */
1491 * Determine whether an opclass (identified by OID) is visible in the
1492 * current search path. Visible means "would be found by searching
1493 * for the unqualified opclass name".
1496 OpclassIsVisible(Oid opcid)
1499 Form_pg_opclass opcform;
1503 opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1504 if (!HeapTupleIsValid(opctup))
1505 elog(ERROR, "cache lookup failed for opclass %u", opcid);
1506 opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1508 recomputeNamespacePath();
1511 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1512 * the system namespace are surely in the path and so we needn't even do
1513 * list_member_oid() for them.
1515 opcnamespace = opcform->opcnamespace;
1516 if (opcnamespace != PG_CATALOG_NAMESPACE &&
1517 !list_member_oid(activeSearchPath, opcnamespace))
1522 * If it is in the path, it might still not be visible; it could be
1523 * hidden by another opclass of the same name earlier in the path. So
1524 * we must do a slow check to see if this opclass would be found by
1525 * OpclassnameGetOpcid.
1527 char *opcname = NameStr(opcform->opcname);
1529 visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1532 ReleaseSysCache(opctup);
1538 * OpfamilynameGetOpfid
1539 * Try to resolve an unqualified index opfamily name.
1540 * Returns OID if opfamily found in search path, else InvalidOid.
1542 * This is essentially the same as TypenameGetTypid, but we have to have
1543 * an extra argument for the index AM OID.
1546 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1551 recomputeNamespacePath();
1553 foreach(l, activeSearchPath)
1555 Oid namespaceId = lfirst_oid(l);
1557 if (namespaceId == myTempNamespace)
1558 continue; /* do not look in temp namespace */
1560 opfid = GetSysCacheOid3(OPFAMILYAMNAMENSP,
1561 ObjectIdGetDatum(amid),
1562 PointerGetDatum(opfname),
1563 ObjectIdGetDatum(namespaceId));
1564 if (OidIsValid(opfid))
1568 /* Not found in path */
1574 * Determine whether an opfamily (identified by OID) is visible in the
1575 * current search path. Visible means "would be found by searching
1576 * for the unqualified opfamily name".
1579 OpfamilyIsVisible(Oid opfid)
1582 Form_pg_opfamily opfform;
1586 opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1587 if (!HeapTupleIsValid(opftup))
1588 elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1589 opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1591 recomputeNamespacePath();
1594 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1595 * the system namespace are surely in the path and so we needn't even do
1596 * list_member_oid() for them.
1598 opfnamespace = opfform->opfnamespace;
1599 if (opfnamespace != PG_CATALOG_NAMESPACE &&
1600 !list_member_oid(activeSearchPath, opfnamespace))
1605 * If it is in the path, it might still not be visible; it could be
1606 * hidden by another opfamily of the same name earlier in the path. So
1607 * we must do a slow check to see if this opfamily would be found by
1608 * OpfamilynameGetOpfid.
1610 char *opfname = NameStr(opfform->opfname);
1612 visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1615 ReleaseSysCache(opftup);
1621 * ConversionGetConid
1622 * Try to resolve an unqualified conversion name.
1623 * Returns OID if conversion found in search path, else InvalidOid.
1625 * This is essentially the same as RelnameGetRelid.
1628 ConversionGetConid(const char *conname)
1633 recomputeNamespacePath();
1635 foreach(l, activeSearchPath)
1637 Oid namespaceId = lfirst_oid(l);
1639 if (namespaceId == myTempNamespace)
1640 continue; /* do not look in temp namespace */
1642 conid = GetSysCacheOid2(CONNAMENSP,
1643 PointerGetDatum(conname),
1644 ObjectIdGetDatum(namespaceId));
1645 if (OidIsValid(conid))
1649 /* Not found in path */
1654 * ConversionIsVisible
1655 * Determine whether a conversion (identified by OID) is visible in the
1656 * current search path. Visible means "would be found by searching
1657 * for the unqualified conversion name".
1660 ConversionIsVisible(Oid conid)
1663 Form_pg_conversion conform;
1667 contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
1668 if (!HeapTupleIsValid(contup))
1669 elog(ERROR, "cache lookup failed for conversion %u", conid);
1670 conform = (Form_pg_conversion) GETSTRUCT(contup);
1672 recomputeNamespacePath();
1675 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1676 * the system namespace are surely in the path and so we needn't even do
1677 * list_member_oid() for them.
1679 connamespace = conform->connamespace;
1680 if (connamespace != PG_CATALOG_NAMESPACE &&
1681 !list_member_oid(activeSearchPath, connamespace))
1686 * If it is in the path, it might still not be visible; it could be
1687 * hidden by another conversion of the same name earlier in the path.
1688 * So we must do a slow check to see if this conversion would be found
1689 * by ConversionGetConid.
1691 char *conname = NameStr(conform->conname);
1693 visible = (ConversionGetConid(conname) == conid);
1696 ReleaseSysCache(contup);
1702 * TSParserGetPrsid - find a TS parser by possibly qualified name
1704 * If not found, returns InvalidOid if failOK, else throws error
1707 TSParserGetPrsid(List *names, bool failOK)
1712 Oid prsoid = InvalidOid;
1715 /* deconstruct the name list */
1716 DeconstructQualifiedName(names, &schemaname, &parser_name);
1720 /* use exact schema given */
1721 namespaceId = LookupExplicitNamespace(schemaname);
1722 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1723 PointerGetDatum(parser_name),
1724 ObjectIdGetDatum(namespaceId));
1728 /* search for it in search path */
1729 recomputeNamespacePath();
1731 foreach(l, activeSearchPath)
1733 namespaceId = lfirst_oid(l);
1735 if (namespaceId == myTempNamespace)
1736 continue; /* do not look in temp namespace */
1738 prsoid = GetSysCacheOid2(TSPARSERNAMENSP,
1739 PointerGetDatum(parser_name),
1740 ObjectIdGetDatum(namespaceId));
1741 if (OidIsValid(prsoid))
1746 if (!OidIsValid(prsoid) && !failOK)
1748 (errcode(ERRCODE_UNDEFINED_OBJECT),
1749 errmsg("text search parser \"%s\" does not exist",
1750 NameListToString(names))));
1757 * Determine whether a parser (identified by OID) is visible in the
1758 * current search path. Visible means "would be found by searching
1759 * for the unqualified parser name".
1762 TSParserIsVisible(Oid prsId)
1765 Form_pg_ts_parser form;
1769 tup = SearchSysCache1(TSPARSEROID, ObjectIdGetDatum(prsId));
1770 if (!HeapTupleIsValid(tup))
1771 elog(ERROR, "cache lookup failed for text search parser %u", prsId);
1772 form = (Form_pg_ts_parser) GETSTRUCT(tup);
1774 recomputeNamespacePath();
1777 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1778 * the system namespace are surely in the path and so we needn't even do
1779 * list_member_oid() for them.
1781 namespace = form->prsnamespace;
1782 if (namespace != PG_CATALOG_NAMESPACE &&
1783 !list_member_oid(activeSearchPath, namespace))
1788 * If it is in the path, it might still not be visible; it could be
1789 * hidden by another parser of the same name earlier in the path. So
1790 * we must do a slow check for conflicting parsers.
1792 char *name = NameStr(form->prsname);
1796 foreach(l, activeSearchPath)
1798 Oid namespaceId = lfirst_oid(l);
1800 if (namespaceId == myTempNamespace)
1801 continue; /* do not look in temp namespace */
1803 if (namespaceId == namespace)
1805 /* Found it first in path */
1809 if (SearchSysCacheExists2(TSPARSERNAMENSP,
1810 PointerGetDatum(name),
1811 ObjectIdGetDatum(namespaceId)))
1813 /* Found something else first in path */
1819 ReleaseSysCache(tup);
1825 * TSDictionaryGetDictid - find a TS dictionary by possibly qualified name
1827 * If not found, returns InvalidOid if failOK, else throws error
1830 TSDictionaryGetDictid(List *names, bool failOK)
1835 Oid dictoid = InvalidOid;
1838 /* deconstruct the name list */
1839 DeconstructQualifiedName(names, &schemaname, &dict_name);
1843 /* use exact schema given */
1844 namespaceId = LookupExplicitNamespace(schemaname);
1845 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1846 PointerGetDatum(dict_name),
1847 ObjectIdGetDatum(namespaceId));
1851 /* search for it in search path */
1852 recomputeNamespacePath();
1854 foreach(l, activeSearchPath)
1856 namespaceId = lfirst_oid(l);
1858 if (namespaceId == myTempNamespace)
1859 continue; /* do not look in temp namespace */
1861 dictoid = GetSysCacheOid2(TSDICTNAMENSP,
1862 PointerGetDatum(dict_name),
1863 ObjectIdGetDatum(namespaceId));
1864 if (OidIsValid(dictoid))
1869 if (!OidIsValid(dictoid) && !failOK)
1871 (errcode(ERRCODE_UNDEFINED_OBJECT),
1872 errmsg("text search dictionary \"%s\" does not exist",
1873 NameListToString(names))));
1879 * TSDictionaryIsVisible
1880 * Determine whether a dictionary (identified by OID) is visible in the
1881 * current search path. Visible means "would be found by searching
1882 * for the unqualified dictionary name".
1885 TSDictionaryIsVisible(Oid dictId)
1888 Form_pg_ts_dict form;
1892 tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
1893 if (!HeapTupleIsValid(tup))
1894 elog(ERROR, "cache lookup failed for text search dictionary %u",
1896 form = (Form_pg_ts_dict) GETSTRUCT(tup);
1898 recomputeNamespacePath();
1901 * Quick check: if it ain't in the path at all, it ain't visible. Items in
1902 * the system namespace are surely in the path and so we needn't even do
1903 * list_member_oid() for them.
1905 namespace = form->dictnamespace;
1906 if (namespace != PG_CATALOG_NAMESPACE &&
1907 !list_member_oid(activeSearchPath, namespace))
1912 * If it is in the path, it might still not be visible; it could be
1913 * hidden by another dictionary of the same name earlier in the path.
1914 * So we must do a slow check for conflicting dictionaries.
1916 char *name = NameStr(form->dictname);
1920 foreach(l, activeSearchPath)
1922 Oid namespaceId = lfirst_oid(l);
1924 if (namespaceId == myTempNamespace)
1925 continue; /* do not look in temp namespace */
1927 if (namespaceId == namespace)
1929 /* Found it first in path */
1933 if (SearchSysCacheExists2(TSDICTNAMENSP,
1934 PointerGetDatum(name),
1935 ObjectIdGetDatum(namespaceId)))
1937 /* Found something else first in path */
1943 ReleaseSysCache(tup);
1949 * TSTemplateGetTmplid - find a TS template by possibly qualified name
1951 * If not found, returns InvalidOid if failOK, else throws error
1954 TSTemplateGetTmplid(List *names, bool failOK)
1957 char *template_name;
1959 Oid tmploid = InvalidOid;
1962 /* deconstruct the name list */
1963 DeconstructQualifiedName(names, &schemaname, &template_name);
1967 /* use exact schema given */
1968 namespaceId = LookupExplicitNamespace(schemaname);
1969 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1970 PointerGetDatum(template_name),
1971 ObjectIdGetDatum(namespaceId));
1975 /* search for it in search path */
1976 recomputeNamespacePath();
1978 foreach(l, activeSearchPath)
1980 namespaceId = lfirst_oid(l);
1982 if (namespaceId == myTempNamespace)
1983 continue; /* do not look in temp namespace */
1985 tmploid = GetSysCacheOid2(TSTEMPLATENAMENSP,
1986 PointerGetDatum(template_name),
1987 ObjectIdGetDatum(namespaceId));
1988 if (OidIsValid(tmploid))
1993 if (!OidIsValid(tmploid) && !failOK)
1995 (errcode(ERRCODE_UNDEFINED_OBJECT),
1996 errmsg("text search template \"%s\" does not exist",
1997 NameListToString(names))));
2003 * TSTemplateIsVisible
2004 * Determine whether a template (identified by OID) is visible in the
2005 * current search path. Visible means "would be found by searching
2006 * for the unqualified template name".
2009 TSTemplateIsVisible(Oid tmplId)
2012 Form_pg_ts_template form;
2016 tup = SearchSysCache1(TSTEMPLATEOID, ObjectIdGetDatum(tmplId));
2017 if (!HeapTupleIsValid(tup))
2018 elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2019 form = (Form_pg_ts_template) GETSTRUCT(tup);
2021 recomputeNamespacePath();
2024 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2025 * the system namespace are surely in the path and so we needn't even do
2026 * list_member_oid() for them.
2028 namespace = form->tmplnamespace;
2029 if (namespace != PG_CATALOG_NAMESPACE &&
2030 !list_member_oid(activeSearchPath, namespace))
2035 * If it is in the path, it might still not be visible; it could be
2036 * hidden by another template of the same name earlier in the path. So
2037 * we must do a slow check for conflicting templates.
2039 char *name = NameStr(form->tmplname);
2043 foreach(l, activeSearchPath)
2045 Oid namespaceId = lfirst_oid(l);
2047 if (namespaceId == myTempNamespace)
2048 continue; /* do not look in temp namespace */
2050 if (namespaceId == namespace)
2052 /* Found it first in path */
2056 if (SearchSysCacheExists2(TSTEMPLATENAMENSP,
2057 PointerGetDatum(name),
2058 ObjectIdGetDatum(namespaceId)))
2060 /* Found something else first in path */
2066 ReleaseSysCache(tup);
2072 * TSConfigGetCfgid - find a TS config by possibly qualified name
2074 * If not found, returns InvalidOid if failOK, else throws error
2077 TSConfigGetCfgid(List *names, bool failOK)
2082 Oid cfgoid = InvalidOid;
2085 /* deconstruct the name list */
2086 DeconstructQualifiedName(names, &schemaname, &config_name);
2090 /* use exact schema given */
2091 namespaceId = LookupExplicitNamespace(schemaname);
2092 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2093 PointerGetDatum(config_name),
2094 ObjectIdGetDatum(namespaceId));
2098 /* search for it in search path */
2099 recomputeNamespacePath();
2101 foreach(l, activeSearchPath)
2103 namespaceId = lfirst_oid(l);
2105 if (namespaceId == myTempNamespace)
2106 continue; /* do not look in temp namespace */
2108 cfgoid = GetSysCacheOid2(TSCONFIGNAMENSP,
2109 PointerGetDatum(config_name),
2110 ObjectIdGetDatum(namespaceId));
2111 if (OidIsValid(cfgoid))
2116 if (!OidIsValid(cfgoid) && !failOK)
2118 (errcode(ERRCODE_UNDEFINED_OBJECT),
2119 errmsg("text search configuration \"%s\" does not exist",
2120 NameListToString(names))));
2127 * Determine whether a text search configuration (identified by OID)
2128 * is visible in the current search path. Visible means "would be found
2129 * by searching for the unqualified text search configuration name".
2132 TSConfigIsVisible(Oid cfgid)
2135 Form_pg_ts_config form;
2139 tup = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfgid));
2140 if (!HeapTupleIsValid(tup))
2141 elog(ERROR, "cache lookup failed for text search configuration %u",
2143 form = (Form_pg_ts_config) GETSTRUCT(tup);
2145 recomputeNamespacePath();
2148 * Quick check: if it ain't in the path at all, it ain't visible. Items in
2149 * the system namespace are surely in the path and so we needn't even do
2150 * list_member_oid() for them.
2152 namespace = form->cfgnamespace;
2153 if (namespace != PG_CATALOG_NAMESPACE &&
2154 !list_member_oid(activeSearchPath, namespace))
2159 * If it is in the path, it might still not be visible; it could be
2160 * hidden by another configuration of the same name earlier in the
2161 * path. So we must do a slow check for conflicting configurations.
2163 char *name = NameStr(form->cfgname);
2167 foreach(l, activeSearchPath)
2169 Oid namespaceId = lfirst_oid(l);
2171 if (namespaceId == myTempNamespace)
2172 continue; /* do not look in temp namespace */
2174 if (namespaceId == namespace)
2176 /* Found it first in path */
2180 if (SearchSysCacheExists2(TSCONFIGNAMENSP,
2181 PointerGetDatum(name),
2182 ObjectIdGetDatum(namespaceId)))
2184 /* Found something else first in path */
2190 ReleaseSysCache(tup);
2197 * DeconstructQualifiedName
2198 * Given a possibly-qualified name expressed as a list of String nodes,
2199 * extract the schema name and object name.
2201 * *nspname_p is set to NULL if there is no explicit schema name.
2204 DeconstructQualifiedName(List *names,
2209 char *schemaname = NULL;
2210 char *objname = NULL;
2212 switch (list_length(names))
2215 objname = strVal(linitial(names));
2218 schemaname = strVal(linitial(names));
2219 objname = strVal(lsecond(names));
2222 catalogname = strVal(linitial(names));
2223 schemaname = strVal(lsecond(names));
2224 objname = strVal(lthird(names));
2227 * We check the catalog name and then ignore it.
2229 if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2231 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2232 errmsg("cross-database references are not implemented: %s",
2233 NameListToString(names))));
2237 (errcode(ERRCODE_SYNTAX_ERROR),
2238 errmsg("improper qualified name (too many dotted names): %s",
2239 NameListToString(names))));
2243 *nspname_p = schemaname;
2244 *objname_p = objname;
2248 * LookupNamespaceNoError
2249 * Look up a schema name.
2251 * Returns the namespace OID, or InvalidOid if not found.
2253 * Note this does NOT perform any permissions check --- callers are
2254 * responsible for being sure that an appropriate check is made.
2255 * In the majority of cases LookupExplicitNamespace is preferable.
2258 LookupNamespaceNoError(const char *nspname)
2260 /* check for pg_temp alias */
2261 if (strcmp(nspname, "pg_temp") == 0)
2263 if (OidIsValid(myTempNamespace))
2264 return myTempNamespace;
2267 * Since this is used only for looking up existing objects, there is
2268 * no point in trying to initialize the temp namespace here; and doing
2269 * so might create problems for some callers. Just report "not found".
2274 return GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2278 * LookupExplicitNamespace
2279 * Process an explicitly-specified schema name: look up the schema
2280 * and verify we have USAGE (lookup) rights in it.
2282 * Returns the namespace OID. Raises ereport if any problem.
2285 LookupExplicitNamespace(const char *nspname)
2288 AclResult aclresult;
2290 /* check for pg_temp alias */
2291 if (strcmp(nspname, "pg_temp") == 0)
2293 if (OidIsValid(myTempNamespace))
2294 return myTempNamespace;
2297 * Since this is used only for looking up existing objects, there is
2298 * no point in trying to initialize the temp namespace here; and doing
2299 * so might create problems for some callers. Just fall through and
2300 * give the "does not exist" error.
2304 namespaceId = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2305 if (!OidIsValid(namespaceId))
2307 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2308 errmsg("schema \"%s\" does not exist", nspname)));
2310 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2311 if (aclresult != ACLCHECK_OK)
2312 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2319 * LookupCreationNamespace
2320 * Look up the schema and verify we have CREATE rights on it.
2322 * This is just like LookupExplicitNamespace except for the different
2323 * permission check, and that we are willing to create pg_temp if needed.
2325 * Note: calling this may result in a CommandCounterIncrement operation,
2326 * if we have to create or clean out the temp namespace.
2329 LookupCreationNamespace(const char *nspname)
2332 AclResult aclresult;
2334 /* check for pg_temp alias */
2335 if (strcmp(nspname, "pg_temp") == 0)
2337 /* Initialize temp namespace if first time through */
2338 if (!OidIsValid(myTempNamespace))
2339 InitTempTableNamespace();
2340 return myTempNamespace;
2343 namespaceId = GetSysCacheOid1(NAMESPACENAME, CStringGetDatum(nspname));
2344 if (!OidIsValid(namespaceId))
2346 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2347 errmsg("schema \"%s\" does not exist", nspname)));
2349 aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2350 if (aclresult != ACLCHECK_OK)
2351 aclcheck_error(aclresult, ACL_KIND_NAMESPACE,
2358 * QualifiedNameGetCreationNamespace
2359 * Given a possibly-qualified name for an object (in List-of-Values
2360 * format), determine what namespace the object should be created in.
2361 * Also extract and return the object name (last component of list).
2363 * Note: this does not apply any permissions check. Callers must check
2364 * for CREATE rights on the selected namespace when appropriate.
2366 * Note: calling this may result in a CommandCounterIncrement operation,
2367 * if we have to create or clean out the temp namespace.
2370 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2375 /* deconstruct the name list */
2376 DeconstructQualifiedName(names, &schemaname, objname_p);
2380 /* check for pg_temp alias */
2381 if (strcmp(schemaname, "pg_temp") == 0)
2383 /* Initialize temp namespace if first time through */
2384 if (!OidIsValid(myTempNamespace))
2385 InitTempTableNamespace();
2386 return myTempNamespace;
2388 /* use exact schema given */
2389 namespaceId = GetSysCacheOid1(NAMESPACENAME,
2390 CStringGetDatum(schemaname));
2391 if (!OidIsValid(namespaceId))
2393 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2394 errmsg("schema \"%s\" does not exist", schemaname)));
2395 /* we do not check for USAGE rights here! */
2399 /* use the default creation namespace */
2400 recomputeNamespacePath();
2401 if (activeTempCreationPending)
2403 /* Need to initialize temp namespace */
2404 InitTempTableNamespace();
2405 return myTempNamespace;
2407 namespaceId = activeCreationNamespace;
2408 if (!OidIsValid(namespaceId))
2410 (errcode(ERRCODE_UNDEFINED_SCHEMA),
2411 errmsg("no schema has been selected to create in")));
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 -1.
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 -1; /* 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);
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.
2672 PushOverrideSearchPath(OverrideSearchPath *newpath)
2674 OverrideStackEntry *entry;
2677 MemoryContext oldcxt;
2680 * Copy the list for safekeeping, and insert implicitly-searched
2681 * namespaces as needed. This code should track recomputeNamespacePath.
2683 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2685 oidlist = list_copy(newpath->schemas);
2688 * Remember the first member of the explicit list.
2691 firstNS = InvalidOid;
2693 firstNS = linitial_oid(oidlist);
2696 * Add any implicitly-searched namespaces to the list. Note these go on
2697 * the front, not the back; also notice that we do not check USAGE
2698 * permissions for these.
2700 if (newpath->addCatalog)
2701 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2703 if (newpath->addTemp)
2705 Assert(OidIsValid(myTempNamespace));
2706 oidlist = lcons_oid(myTempNamespace, oidlist);
2710 * Build the new stack entry, then insert it at the head of the list.
2712 entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
2713 entry->searchPath = oidlist;
2714 entry->creationNamespace = firstNS;
2715 entry->nestLevel = GetCurrentTransactionNestLevel();
2717 overrideStack = lcons(entry, overrideStack);
2719 /* And make it active. */
2720 activeSearchPath = entry->searchPath;
2721 activeCreationNamespace = entry->creationNamespace;
2722 activeTempCreationPending = false; /* XXX is this OK? */
2724 MemoryContextSwitchTo(oldcxt);
2728 * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
2730 * Any push during a (sub)transaction will be popped automatically at abort.
2731 * But it's caller error if a push isn't popped in normal control flow.
2734 PopOverrideSearchPath(void)
2736 OverrideStackEntry *entry;
2738 /* Sanity checks. */
2739 if (overrideStack == NIL)
2740 elog(ERROR, "bogus PopOverrideSearchPath call");
2741 entry = (OverrideStackEntry *) linitial(overrideStack);
2742 if (entry->nestLevel != GetCurrentTransactionNestLevel())
2743 elog(ERROR, "bogus PopOverrideSearchPath call");
2745 /* Pop the stack and free storage. */
2746 overrideStack = list_delete_first(overrideStack);
2747 list_free(entry->searchPath);
2750 /* Activate the next level down. */
2753 entry = (OverrideStackEntry *) linitial(overrideStack);
2754 activeSearchPath = entry->searchPath;
2755 activeCreationNamespace = entry->creationNamespace;
2756 activeTempCreationPending = false; /* XXX is this OK? */
2760 /* If not baseSearchPathValid, this is useless but harmless */
2761 activeSearchPath = baseSearchPath;
2762 activeCreationNamespace = baseCreationNamespace;
2763 activeTempCreationPending = baseTempCreationPending;
2769 * FindConversionByName - find a conversion by possibly qualified name
2772 FindConversionByName(List *name)
2775 char *conversion_name;
2780 /* deconstruct the name list */
2781 DeconstructQualifiedName(name, &schemaname, &conversion_name);
2785 /* use exact schema given */
2786 namespaceId = LookupExplicitNamespace(schemaname);
2787 return GetSysCacheOid2(CONNAMENSP,
2788 PointerGetDatum(conversion_name),
2789 ObjectIdGetDatum(namespaceId));
2793 /* search for it in search path */
2794 recomputeNamespacePath();
2796 foreach(l, activeSearchPath)
2798 namespaceId = lfirst_oid(l);
2800 if (namespaceId == myTempNamespace)
2801 continue; /* do not look in temp namespace */
2803 conoid = GetSysCacheOid2(CONNAMENSP,
2804 PointerGetDatum(conversion_name),
2805 ObjectIdGetDatum(namespaceId));
2806 if (OidIsValid(conoid))
2811 /* Not found in path */
2816 * FindDefaultConversionProc - find default encoding conversion proc
2819 FindDefaultConversionProc(int4 for_encoding, int4 to_encoding)
2824 recomputeNamespacePath();
2826 foreach(l, activeSearchPath)
2828 Oid namespaceId = lfirst_oid(l);
2830 if (namespaceId == myTempNamespace)
2831 continue; /* do not look in temp namespace */
2833 proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
2834 if (OidIsValid(proc))
2838 /* Not found in path */
2843 * recomputeNamespacePath - recompute path derived variables if needed.
2846 recomputeNamespacePath(void)
2848 Oid roleid = GetUserId();
2856 MemoryContext oldcxt;
2858 /* Do nothing if an override search spec is active. */
2862 /* Do nothing if path is already valid. */
2863 if (baseSearchPathValid && namespaceUser == roleid)
2866 /* Need a modifiable copy of namespace_search_path string */
2867 rawname = pstrdup(namespace_search_path);
2869 /* Parse string into list of identifiers */
2870 if (!SplitIdentifierString(rawname, ',', &namelist))
2872 /* syntax error in name list */
2873 /* this should not happen if GUC checked check_search_path */
2874 elog(ERROR, "invalid list syntax");
2878 * Convert the list of names to a list of OIDs. If any names are not
2879 * recognizable or we don't have read access, just leave them out of the
2880 * list. (We can't raise an error, since the search_path setting has
2881 * already been accepted.) Don't make duplicate entries, either.
2884 temp_missing = false;
2885 foreach(l, namelist)
2887 char *curname = (char *) lfirst(l);
2890 if (strcmp(curname, "$user") == 0)
2892 /* $user --- substitute namespace matching user name, if any */
2895 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
2896 if (HeapTupleIsValid(tuple))
2900 rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
2901 namespaceId = GetSysCacheOid1(NAMESPACENAME,
2902 CStringGetDatum(rname));
2903 ReleaseSysCache(tuple);
2904 if (OidIsValid(namespaceId) &&
2905 !list_member_oid(oidlist, namespaceId) &&
2906 pg_namespace_aclcheck(namespaceId, roleid,
2907 ACL_USAGE) == ACLCHECK_OK)
2908 oidlist = lappend_oid(oidlist, namespaceId);
2911 else if (strcmp(curname, "pg_temp") == 0)
2913 /* pg_temp --- substitute temp namespace, if any */
2914 if (OidIsValid(myTempNamespace))
2916 if (!list_member_oid(oidlist, myTempNamespace))
2917 oidlist = lappend_oid(oidlist, myTempNamespace);
2921 /* If it ought to be the creation namespace, set flag */
2923 temp_missing = true;
2928 /* normal namespace reference */
2929 namespaceId = GetSysCacheOid1(NAMESPACENAME,
2930 CStringGetDatum(curname));
2931 if (OidIsValid(namespaceId) &&
2932 !list_member_oid(oidlist, namespaceId) &&
2933 pg_namespace_aclcheck(namespaceId, roleid,
2934 ACL_USAGE) == ACLCHECK_OK)
2935 oidlist = lappend_oid(oidlist, namespaceId);
2940 * Remember the first member of the explicit list. (Note: this is
2941 * nominally wrong if temp_missing, but we need it anyway to distinguish
2942 * explicit from implicit mention of pg_catalog.)
2945 firstNS = InvalidOid;
2947 firstNS = linitial_oid(oidlist);
2950 * Add any implicitly-searched namespaces to the list. Note these go on
2951 * the front, not the back; also notice that we do not check USAGE
2952 * permissions for these.
2954 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
2955 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2957 if (OidIsValid(myTempNamespace) &&
2958 !list_member_oid(oidlist, myTempNamespace))
2959 oidlist = lcons_oid(myTempNamespace, oidlist);
2962 * Now that we've successfully built the new list of namespace OIDs, save
2963 * it in permanent storage.
2965 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2966 newpath = list_copy(oidlist);
2967 MemoryContextSwitchTo(oldcxt);
2969 /* Now safe to assign to state variables. */
2970 list_free(baseSearchPath);
2971 baseSearchPath = newpath;
2972 baseCreationNamespace = firstNS;
2973 baseTempCreationPending = temp_missing;
2975 /* Mark the path valid. */
2976 baseSearchPathValid = true;
2977 namespaceUser = roleid;
2979 /* And make it active. */
2980 activeSearchPath = baseSearchPath;
2981 activeCreationNamespace = baseCreationNamespace;
2982 activeTempCreationPending = baseTempCreationPending;
2986 list_free(namelist);
2991 * InitTempTableNamespace
2992 * Initialize temp table namespace on first use in a particular backend
2995 InitTempTableNamespace(void)
2997 char namespaceName[NAMEDATALEN];
3001 Assert(!OidIsValid(myTempNamespace));
3004 * First, do permission check to see if we are authorized to make temp
3005 * tables. We use a nonstandard error message here since "databasename:
3006 * permission denied" might be a tad cryptic.
3008 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3009 * that's necessary since current user ID could change during the session.
3010 * But there's no need to make the namespace in the first place until a
3011 * temp table creation request is made by someone with appropriate rights.
3013 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3014 ACL_CREATE_TEMP) != ACLCHECK_OK)
3016 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3017 errmsg("permission denied to create temporary tables in database \"%s\"",
3018 get_database_name(MyDatabaseId))));
3020 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3022 namespaceId = GetSysCacheOid1(NAMESPACENAME,
3023 CStringGetDatum(namespaceName));
3024 if (!OidIsValid(namespaceId))
3027 * First use of this temp namespace in this database; create it. The
3028 * temp namespaces are always owned by the superuser. We leave their
3029 * permissions at default --- i.e., no access except to superuser ---
3030 * to ensure that unprivileged users can't peek at other backends'
3031 * temp tables. This works because the places that access the temp
3032 * namespace for my own backend skip permissions checks on it.
3034 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3035 /* Advance command counter to make namespace visible */
3036 CommandCounterIncrement();
3041 * If the namespace already exists, clean it out (in case the former
3042 * owner crashed without doing so).
3044 RemoveTempRelations(namespaceId);
3048 * If the corresponding toast-table namespace doesn't exist yet, create
3049 * it. (We assume there is no need to clean it out if it does exist, since
3050 * dropping a parent table should make its toast table go away.)
3052 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3055 toastspaceId = GetSysCacheOid1(NAMESPACENAME,
3056 CStringGetDatum(namespaceName));
3057 if (!OidIsValid(toastspaceId))
3059 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3060 /* Advance command counter to make namespace visible */
3061 CommandCounterIncrement();
3065 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3066 * so all our work could be undone by transaction rollback. Set flag for
3067 * AtEOXact_Namespace to know what to do.
3069 myTempNamespace = namespaceId;
3070 myTempToastNamespace = toastspaceId;
3072 /* It should not be done already. */
3073 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3074 myTempNamespaceSubID = GetCurrentSubTransactionId();
3076 baseSearchPathValid = false; /* need to rebuild list */
3080 * End-of-transaction cleanup for namespaces.
3083 AtEOXact_Namespace(bool isCommit)
3086 * If we abort the transaction in which a temp namespace was selected,
3087 * we'll have to do any creation or cleanout work over again. So, just
3088 * forget the namespace entirely until next time. On the other hand, if
3089 * we commit then register an exit callback to clean out the temp tables
3090 * at backend shutdown. (We only want to register the callback once per
3091 * session, so this is a good place to do it.)
3093 if (myTempNamespaceSubID != InvalidSubTransactionId)
3096 on_shmem_exit(RemoveTempRelationsCallback, 0);
3099 myTempNamespace = InvalidOid;
3100 myTempToastNamespace = InvalidOid;
3101 baseSearchPathValid = false; /* need to rebuild list */
3103 myTempNamespaceSubID = InvalidSubTransactionId;
3107 * Clean up if someone failed to do PopOverrideSearchPath
3112 elog(WARNING, "leaked override search path");
3113 while (overrideStack)
3115 OverrideStackEntry *entry;
3117 entry = (OverrideStackEntry *) linitial(overrideStack);
3118 overrideStack = list_delete_first(overrideStack);
3119 list_free(entry->searchPath);
3122 /* If not baseSearchPathValid, this is useless but harmless */
3123 activeSearchPath = baseSearchPath;
3124 activeCreationNamespace = baseCreationNamespace;
3125 activeTempCreationPending = baseTempCreationPending;
3130 * AtEOSubXact_Namespace
3132 * At subtransaction commit, propagate the temp-namespace-creation
3133 * flag to the parent subtransaction.
3135 * At subtransaction abort, forget the flag if we set it up.
3138 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3139 SubTransactionId parentSubid)
3141 OverrideStackEntry *entry;
3143 if (myTempNamespaceSubID == mySubid)
3146 myTempNamespaceSubID = parentSubid;
3149 myTempNamespaceSubID = InvalidSubTransactionId;
3150 /* TEMP namespace creation failed, so reset state */
3151 myTempNamespace = InvalidOid;
3152 myTempToastNamespace = InvalidOid;
3153 baseSearchPathValid = false; /* need to rebuild list */
3158 * Clean up if someone failed to do PopOverrideSearchPath
3160 while (overrideStack)
3162 entry = (OverrideStackEntry *) linitial(overrideStack);
3163 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3166 elog(WARNING, "leaked override search path");
3167 overrideStack = list_delete_first(overrideStack);
3168 list_free(entry->searchPath);
3172 /* Activate the next level down. */
3175 entry = (OverrideStackEntry *) linitial(overrideStack);
3176 activeSearchPath = entry->searchPath;
3177 activeCreationNamespace = entry->creationNamespace;
3178 activeTempCreationPending = false; /* XXX is this OK? */
3182 /* If not baseSearchPathValid, this is useless but harmless */
3183 activeSearchPath = baseSearchPath;
3184 activeCreationNamespace = baseCreationNamespace;
3185 activeTempCreationPending = baseTempCreationPending;
3190 * Remove all relations in the specified temp namespace.
3192 * This is called at backend shutdown (if we made any temp relations).
3193 * It is also called when we begin using a pre-existing temp namespace,
3194 * in order to clean out any relations that might have been created by
3195 * a crashed backend.
3198 RemoveTempRelations(Oid tempNamespaceId)
3200 ObjectAddress object;
3203 * We want to get rid of everything in the target namespace, but not the
3204 * namespace itself (deleting it only to recreate it later would be a
3205 * waste of cycles). We do this by finding everything that has a
3206 * dependency on the namespace.
3208 object.classId = NamespaceRelationId;
3209 object.objectId = tempNamespaceId;
3210 object.objectSubId = 0;
3212 deleteWhatDependsOn(&object, false);
3216 * Callback to remove temp relations at backend exit.
3219 RemoveTempRelationsCallback(int code, Datum arg)
3221 if (OidIsValid(myTempNamespace)) /* should always be true */
3223 /* Need to ensure we have a usable transaction. */
3224 AbortOutOfAnyTransaction();
3225 StartTransactionCommand();
3227 RemoveTempRelations(myTempNamespace);
3229 CommitTransactionCommand();
3234 * Remove all temp tables from the temporary namespace.
3237 ResetTempTableNamespace(void)
3239 if (OidIsValid(myTempNamespace))
3240 RemoveTempRelations(myTempNamespace);
3245 * Routines for handling the GUC variable 'search_path'.
3248 /* assign_hook: validate new search_path, do extra actions as needed */
3250 assign_search_path(const char *newval, bool doit, GucSource source)
3256 /* Need a modifiable copy of string */
3257 rawname = pstrdup(newval);
3259 /* Parse string into list of identifiers */
3260 if (!SplitIdentifierString(rawname, ',', &namelist))
3262 /* syntax error in name list */
3264 list_free(namelist);
3269 * If we aren't inside a transaction, we cannot do database access so
3270 * cannot verify the individual names. Must accept the list on faith.
3272 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3275 * Verify that all the names are either valid namespace names or
3276 * "$user" or "pg_temp". We do not require $user to correspond to a
3277 * valid namespace, and pg_temp might not exist yet. We do not check
3278 * for USAGE rights, either; should we?
3280 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3281 * DATABASE SET or ALTER USER SET command. It could be that the
3282 * intended use of the search path is for some other database, so we
3283 * should not error out if it mentions schemas not present in the
3284 * current database. We reduce the message to NOTICE instead.
3286 foreach(l, namelist)
3288 char *curname = (char *) lfirst(l);
3290 if (strcmp(curname, "$user") == 0)
3292 if (strcmp(curname, "pg_temp") == 0)
3294 if (!SearchSysCacheExists1(NAMESPACENAME,
3295 CStringGetDatum(curname)))
3296 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3297 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3298 errmsg("schema \"%s\" does not exist", curname)));
3303 list_free(namelist);
3306 * We mark the path as needing recomputation, but don't do anything until
3307 * it's needed. This avoids trying to do database access during GUC
3311 baseSearchPathValid = false;
3317 * InitializeSearchPath: initialize module during InitPostgres.
3319 * This is called after we are up enough to be able to do catalog lookups.
3322 InitializeSearchPath(void)
3324 if (IsBootstrapProcessingMode())
3327 * In bootstrap mode, the search path must be 'pg_catalog' so that
3328 * tables are created in the proper namespace; ignore the GUC setting.
3330 MemoryContext oldcxt;
3332 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3333 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3334 MemoryContextSwitchTo(oldcxt);
3335 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3336 baseTempCreationPending = false;
3337 baseSearchPathValid = true;
3338 namespaceUser = GetUserId();
3339 activeSearchPath = baseSearchPath;
3340 activeCreationNamespace = baseCreationNamespace;
3341 activeTempCreationPending = baseTempCreationPending;
3346 * In normal mode, arrange for a callback on any syscache invalidation
3347 * of pg_namespace rows.
3349 CacheRegisterSyscacheCallback(NAMESPACEOID,
3352 /* Force search path to be recomputed on next use */
3353 baseSearchPathValid = false;
3359 * Syscache inval callback function
3362 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3364 /* Force search path to be recomputed on next use */
3365 baseSearchPathValid = false;
3369 * Fetch the active search path. The return value is a palloc'ed list
3370 * of OIDs; the caller is responsible for freeing this storage as
3373 * The returned list includes the implicitly-prepended namespaces only if
3374 * includeImplicit is true.
3376 * Note: calling this may result in a CommandCounterIncrement operation,
3377 * if we have to create or clean out the temp namespace.
3380 fetch_search_path(bool includeImplicit)
3384 recomputeNamespacePath();
3387 * If the temp namespace should be first, force it to exist. This is so
3388 * that callers can trust the result to reflect the actual default
3389 * creation namespace. It's a bit bogus to do this here, since
3390 * current_schema() is supposedly a stable function without side-effects,
3391 * but the alternatives seem worse.
3393 if (activeTempCreationPending)
3395 InitTempTableNamespace();
3396 recomputeNamespacePath();
3399 result = list_copy(activeSearchPath);
3400 if (!includeImplicit)
3402 while (result && linitial_oid(result) != activeCreationNamespace)
3403 result = list_delete_first(result);
3410 * Fetch the active search path into a caller-allocated array of OIDs.
3411 * Returns the number of path entries. (If this is more than sarray_len,
3412 * then the data didn't fit and is not all stored.)
3414 * The returned list always includes the implicitly-prepended namespaces,
3415 * but never includes the temp namespace. (This is suitable for existing
3416 * users, which would want to ignore the temp namespace anyway.) This
3417 * definition allows us to not worry about initializing the temp namespace.
3420 fetch_search_path_array(Oid *sarray, int sarray_len)
3425 recomputeNamespacePath();
3427 foreach(l, activeSearchPath)
3429 Oid namespaceId = lfirst_oid(l);
3431 if (namespaceId == myTempNamespace)
3432 continue; /* do not include temp namespace */
3434 if (count < sarray_len)
3435 sarray[count] = namespaceId;
3444 * Export the FooIsVisible functions as SQL-callable functions.
3446 * Note: as of Postgres 8.4, these will silently return NULL if called on
3447 * a nonexistent object OID, rather than failing. This is to avoid race
3448 * condition errors when a query that's scanning a catalog using an MVCC
3449 * snapshot uses one of these functions. The underlying IsVisible functions
3450 * operate on SnapshotNow semantics and so might see the object as already
3451 * gone when it's still visible to the MVCC snapshot. (There is no race
3452 * condition in the current coding because we don't accept sinval messages
3453 * between the SearchSysCacheExists test and the subsequent lookup.)
3457 pg_table_is_visible(PG_FUNCTION_ARGS)
3459 Oid oid = PG_GETARG_OID(0);
3461 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3464 PG_RETURN_BOOL(RelationIsVisible(oid));
3468 pg_type_is_visible(PG_FUNCTION_ARGS)
3470 Oid oid = PG_GETARG_OID(0);
3472 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3475 PG_RETURN_BOOL(TypeIsVisible(oid));
3479 pg_function_is_visible(PG_FUNCTION_ARGS)
3481 Oid oid = PG_GETARG_OID(0);
3483 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3486 PG_RETURN_BOOL(FunctionIsVisible(oid));
3490 pg_operator_is_visible(PG_FUNCTION_ARGS)
3492 Oid oid = PG_GETARG_OID(0);
3494 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3497 PG_RETURN_BOOL(OperatorIsVisible(oid));
3501 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3503 Oid oid = PG_GETARG_OID(0);
3505 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3508 PG_RETURN_BOOL(OpclassIsVisible(oid));
3512 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3514 Oid oid = PG_GETARG_OID(0);
3516 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3519 PG_RETURN_BOOL(ConversionIsVisible(oid));
3523 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3525 Oid oid = PG_GETARG_OID(0);
3527 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3530 PG_RETURN_BOOL(TSParserIsVisible(oid));
3534 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3536 Oid oid = PG_GETARG_OID(0);
3538 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3541 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3545 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3547 Oid oid = PG_GETARG_OID(0);
3549 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3552 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3556 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3558 Oid oid = PG_GETARG_OID(0);
3560 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3563 PG_RETURN_BOOL(TSConfigIsVisible(oid));
3567 pg_my_temp_schema(PG_FUNCTION_ARGS)
3569 PG_RETURN_OID(myTempNamespace);
3573 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3575 Oid oid = PG_GETARG_OID(0);
3577 PG_RETURN_BOOL(isOtherTempNamespace(oid));