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.126 2010/08/05 14:44:58 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 = 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 * TSParserGetPrsid - find a TS parser by possibly qualified name
1697 * If not found, returns InvalidOid if failOK, else throws error
1700 TSParserGetPrsid(List *names, bool failOK)
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) && !failOK)
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 * TSDictionaryGetDictid - find a TS dictionary by possibly qualified name
1820 * If not found, returns InvalidOid if failOK, else throws error
1823 TSDictionaryGetDictid(List *names, bool failOK)
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) && !failOK)
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 * TSTemplateGetTmplid - find a TS template by possibly qualified name
1944 * If not found, returns InvalidOid if failOK, else throws error
1947 TSTemplateGetTmplid(List *names, bool failOK)
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) && !failOK)
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 * TSConfigGetCfgid - find a TS config by possibly qualified name
2067 * If not found, returns InvalidOid if failOK, else throws error
2070 TSConfigGetCfgid(List *names, bool failOK)
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) && !failOK)
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 -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 = get_namespace_oid(rname, true);
2902 ReleaseSysCache(tuple);
2903 if (OidIsValid(namespaceId) &&
2904 !list_member_oid(oidlist, namespaceId) &&
2905 pg_namespace_aclcheck(namespaceId, roleid,
2906 ACL_USAGE) == ACLCHECK_OK)
2907 oidlist = lappend_oid(oidlist, namespaceId);
2910 else if (strcmp(curname, "pg_temp") == 0)
2912 /* pg_temp --- substitute temp namespace, if any */
2913 if (OidIsValid(myTempNamespace))
2915 if (!list_member_oid(oidlist, myTempNamespace))
2916 oidlist = lappend_oid(oidlist, myTempNamespace);
2920 /* If it ought to be the creation namespace, set flag */
2922 temp_missing = true;
2927 /* normal namespace reference */
2928 namespaceId = get_namespace_oid(curname, true);
2929 if (OidIsValid(namespaceId) &&
2930 !list_member_oid(oidlist, namespaceId) &&
2931 pg_namespace_aclcheck(namespaceId, roleid,
2932 ACL_USAGE) == ACLCHECK_OK)
2933 oidlist = lappend_oid(oidlist, namespaceId);
2938 * Remember the first member of the explicit list. (Note: this is
2939 * nominally wrong if temp_missing, but we need it anyway to distinguish
2940 * explicit from implicit mention of pg_catalog.)
2943 firstNS = InvalidOid;
2945 firstNS = linitial_oid(oidlist);
2948 * Add any implicitly-searched namespaces to the list. Note these go on
2949 * the front, not the back; also notice that we do not check USAGE
2950 * permissions for these.
2952 if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
2953 oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
2955 if (OidIsValid(myTempNamespace) &&
2956 !list_member_oid(oidlist, myTempNamespace))
2957 oidlist = lcons_oid(myTempNamespace, oidlist);
2960 * Now that we've successfully built the new list of namespace OIDs, save
2961 * it in permanent storage.
2963 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
2964 newpath = list_copy(oidlist);
2965 MemoryContextSwitchTo(oldcxt);
2967 /* Now safe to assign to state variables. */
2968 list_free(baseSearchPath);
2969 baseSearchPath = newpath;
2970 baseCreationNamespace = firstNS;
2971 baseTempCreationPending = temp_missing;
2973 /* Mark the path valid. */
2974 baseSearchPathValid = true;
2975 namespaceUser = roleid;
2977 /* And make it active. */
2978 activeSearchPath = baseSearchPath;
2979 activeCreationNamespace = baseCreationNamespace;
2980 activeTempCreationPending = baseTempCreationPending;
2984 list_free(namelist);
2989 * InitTempTableNamespace
2990 * Initialize temp table namespace on first use in a particular backend
2993 InitTempTableNamespace(void)
2995 char namespaceName[NAMEDATALEN];
2999 Assert(!OidIsValid(myTempNamespace));
3002 * First, do permission check to see if we are authorized to make temp
3003 * tables. We use a nonstandard error message here since "databasename:
3004 * permission denied" might be a tad cryptic.
3006 * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3007 * that's necessary since current user ID could change during the session.
3008 * But there's no need to make the namespace in the first place until a
3009 * temp table creation request is made by someone with appropriate rights.
3011 if (pg_database_aclcheck(MyDatabaseId, GetUserId(),
3012 ACL_CREATE_TEMP) != ACLCHECK_OK)
3014 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3015 errmsg("permission denied to create temporary tables in database \"%s\"",
3016 get_database_name(MyDatabaseId))));
3019 * Do not allow a Hot Standby slave session to make temp tables. Aside
3020 * from problems with modifying the system catalogs, there is a naming
3021 * conflict: pg_temp_N belongs to the session with BackendId N on the
3022 * master, not to a slave session with the same BackendId. We should not
3023 * be able to get here anyway due to XactReadOnly checks, but let's just
3024 * make real sure. Note that this also backstops various operations that
3025 * allow XactReadOnly transactions to modify temp tables; they'd need
3026 * RecoveryInProgress checks if not for this.
3028 if (RecoveryInProgress())
3030 (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3031 errmsg("cannot create temporary tables during recovery")));
3033 snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3035 namespaceId = get_namespace_oid(namespaceName, true);
3036 if (!OidIsValid(namespaceId))
3039 * First use of this temp namespace in this database; create it. The
3040 * temp namespaces are always owned by the superuser. We leave their
3041 * permissions at default --- i.e., no access except to superuser ---
3042 * to ensure that unprivileged users can't peek at other backends'
3043 * temp tables. This works because the places that access the temp
3044 * namespace for my own backend skip permissions checks on it.
3046 namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3047 /* Advance command counter to make namespace visible */
3048 CommandCounterIncrement();
3053 * If the namespace already exists, clean it out (in case the former
3054 * owner crashed without doing so).
3056 RemoveTempRelations(namespaceId);
3060 * If the corresponding toast-table namespace doesn't exist yet, create
3061 * it. (We assume there is no need to clean it out if it does exist, since
3062 * dropping a parent table should make its toast table go away.)
3064 snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3067 toastspaceId = get_namespace_oid(namespaceName, true);
3068 if (!OidIsValid(toastspaceId))
3070 toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID);
3071 /* Advance command counter to make namespace visible */
3072 CommandCounterIncrement();
3076 * Okay, we've prepared the temp namespace ... but it's not committed yet,
3077 * so all our work could be undone by transaction rollback. Set flag for
3078 * AtEOXact_Namespace to know what to do.
3080 myTempNamespace = namespaceId;
3081 myTempToastNamespace = toastspaceId;
3083 /* It should not be done already. */
3084 AssertState(myTempNamespaceSubID == InvalidSubTransactionId);
3085 myTempNamespaceSubID = GetCurrentSubTransactionId();
3087 baseSearchPathValid = false; /* need to rebuild list */
3091 * End-of-transaction cleanup for namespaces.
3094 AtEOXact_Namespace(bool isCommit)
3097 * If we abort the transaction in which a temp namespace was selected,
3098 * we'll have to do any creation or cleanout work over again. So, just
3099 * forget the namespace entirely until next time. On the other hand, if
3100 * we commit then register an exit callback to clean out the temp tables
3101 * at backend shutdown. (We only want to register the callback once per
3102 * session, so this is a good place to do it.)
3104 if (myTempNamespaceSubID != InvalidSubTransactionId)
3107 on_shmem_exit(RemoveTempRelationsCallback, 0);
3110 myTempNamespace = InvalidOid;
3111 myTempToastNamespace = InvalidOid;
3112 baseSearchPathValid = false; /* need to rebuild list */
3114 myTempNamespaceSubID = InvalidSubTransactionId;
3118 * Clean up if someone failed to do PopOverrideSearchPath
3123 elog(WARNING, "leaked override search path");
3124 while (overrideStack)
3126 OverrideStackEntry *entry;
3128 entry = (OverrideStackEntry *) linitial(overrideStack);
3129 overrideStack = list_delete_first(overrideStack);
3130 list_free(entry->searchPath);
3133 /* If not baseSearchPathValid, this is useless but harmless */
3134 activeSearchPath = baseSearchPath;
3135 activeCreationNamespace = baseCreationNamespace;
3136 activeTempCreationPending = baseTempCreationPending;
3141 * AtEOSubXact_Namespace
3143 * At subtransaction commit, propagate the temp-namespace-creation
3144 * flag to the parent subtransaction.
3146 * At subtransaction abort, forget the flag if we set it up.
3149 AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid,
3150 SubTransactionId parentSubid)
3152 OverrideStackEntry *entry;
3154 if (myTempNamespaceSubID == mySubid)
3157 myTempNamespaceSubID = parentSubid;
3160 myTempNamespaceSubID = InvalidSubTransactionId;
3161 /* TEMP namespace creation failed, so reset state */
3162 myTempNamespace = InvalidOid;
3163 myTempToastNamespace = InvalidOid;
3164 baseSearchPathValid = false; /* need to rebuild list */
3169 * Clean up if someone failed to do PopOverrideSearchPath
3171 while (overrideStack)
3173 entry = (OverrideStackEntry *) linitial(overrideStack);
3174 if (entry->nestLevel < GetCurrentTransactionNestLevel())
3177 elog(WARNING, "leaked override search path");
3178 overrideStack = list_delete_first(overrideStack);
3179 list_free(entry->searchPath);
3183 /* Activate the next level down. */
3186 entry = (OverrideStackEntry *) linitial(overrideStack);
3187 activeSearchPath = entry->searchPath;
3188 activeCreationNamespace = entry->creationNamespace;
3189 activeTempCreationPending = false; /* XXX is this OK? */
3193 /* If not baseSearchPathValid, this is useless but harmless */
3194 activeSearchPath = baseSearchPath;
3195 activeCreationNamespace = baseCreationNamespace;
3196 activeTempCreationPending = baseTempCreationPending;
3201 * Remove all relations in the specified temp namespace.
3203 * This is called at backend shutdown (if we made any temp relations).
3204 * It is also called when we begin using a pre-existing temp namespace,
3205 * in order to clean out any relations that might have been created by
3206 * a crashed backend.
3209 RemoveTempRelations(Oid tempNamespaceId)
3211 ObjectAddress object;
3214 * We want to get rid of everything in the target namespace, but not the
3215 * namespace itself (deleting it only to recreate it later would be a
3216 * waste of cycles). We do this by finding everything that has a
3217 * dependency on the namespace.
3219 object.classId = NamespaceRelationId;
3220 object.objectId = tempNamespaceId;
3221 object.objectSubId = 0;
3223 deleteWhatDependsOn(&object, false);
3227 * Callback to remove temp relations at backend exit.
3230 RemoveTempRelationsCallback(int code, Datum arg)
3232 if (OidIsValid(myTempNamespace)) /* should always be true */
3234 /* Need to ensure we have a usable transaction. */
3235 AbortOutOfAnyTransaction();
3236 StartTransactionCommand();
3238 RemoveTempRelations(myTempNamespace);
3240 CommitTransactionCommand();
3245 * Remove all temp tables from the temporary namespace.
3248 ResetTempTableNamespace(void)
3250 if (OidIsValid(myTempNamespace))
3251 RemoveTempRelations(myTempNamespace);
3256 * Routines for handling the GUC variable 'search_path'.
3259 /* assign_hook: validate new search_path, do extra actions as needed */
3261 assign_search_path(const char *newval, bool doit, GucSource source)
3267 /* Need a modifiable copy of string */
3268 rawname = pstrdup(newval);
3270 /* Parse string into list of identifiers */
3271 if (!SplitIdentifierString(rawname, ',', &namelist))
3273 /* syntax error in name list */
3275 list_free(namelist);
3280 * If we aren't inside a transaction, we cannot do database access so
3281 * cannot verify the individual names. Must accept the list on faith.
3283 if (source >= PGC_S_INTERACTIVE && IsTransactionState())
3286 * Verify that all the names are either valid namespace names or
3287 * "$user" or "pg_temp". We do not require $user to correspond to a
3288 * valid namespace, and pg_temp might not exist yet. We do not check
3289 * for USAGE rights, either; should we?
3291 * When source == PGC_S_TEST, we are checking the argument of an ALTER
3292 * DATABASE SET or ALTER USER SET command. It could be that the
3293 * intended use of the search path is for some other database, so we
3294 * should not error out if it mentions schemas not present in the
3295 * current database. We reduce the message to NOTICE instead.
3297 foreach(l, namelist)
3299 char *curname = (char *) lfirst(l);
3301 if (strcmp(curname, "$user") == 0)
3303 if (strcmp(curname, "pg_temp") == 0)
3305 if (!SearchSysCacheExists1(NAMESPACENAME,
3306 CStringGetDatum(curname)))
3307 ereport((source == PGC_S_TEST) ? NOTICE : ERROR,
3308 (errcode(ERRCODE_UNDEFINED_SCHEMA),
3309 errmsg("schema \"%s\" does not exist", curname)));
3314 list_free(namelist);
3317 * We mark the path as needing recomputation, but don't do anything until
3318 * it's needed. This avoids trying to do database access during GUC
3322 baseSearchPathValid = false;
3328 * InitializeSearchPath: initialize module during InitPostgres.
3330 * This is called after we are up enough to be able to do catalog lookups.
3333 InitializeSearchPath(void)
3335 if (IsBootstrapProcessingMode())
3338 * In bootstrap mode, the search path must be 'pg_catalog' so that
3339 * tables are created in the proper namespace; ignore the GUC setting.
3341 MemoryContext oldcxt;
3343 oldcxt = MemoryContextSwitchTo(TopMemoryContext);
3344 baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3345 MemoryContextSwitchTo(oldcxt);
3346 baseCreationNamespace = PG_CATALOG_NAMESPACE;
3347 baseTempCreationPending = false;
3348 baseSearchPathValid = true;
3349 namespaceUser = GetUserId();
3350 activeSearchPath = baseSearchPath;
3351 activeCreationNamespace = baseCreationNamespace;
3352 activeTempCreationPending = baseTempCreationPending;
3357 * In normal mode, arrange for a callback on any syscache invalidation
3358 * of pg_namespace rows.
3360 CacheRegisterSyscacheCallback(NAMESPACEOID,
3363 /* Force search path to be recomputed on next use */
3364 baseSearchPathValid = false;
3370 * Syscache inval callback function
3373 NamespaceCallback(Datum arg, int cacheid, ItemPointer tuplePtr)
3375 /* Force search path to be recomputed on next use */
3376 baseSearchPathValid = false;
3380 * Fetch the active search path. The return value is a palloc'ed list
3381 * of OIDs; the caller is responsible for freeing this storage as
3384 * The returned list includes the implicitly-prepended namespaces only if
3385 * includeImplicit is true.
3387 * Note: calling this may result in a CommandCounterIncrement operation,
3388 * if we have to create or clean out the temp namespace.
3391 fetch_search_path(bool includeImplicit)
3395 recomputeNamespacePath();
3398 * If the temp namespace should be first, force it to exist. This is so
3399 * that callers can trust the result to reflect the actual default
3400 * creation namespace. It's a bit bogus to do this here, since
3401 * current_schema() is supposedly a stable function without side-effects,
3402 * but the alternatives seem worse.
3404 if (activeTempCreationPending)
3406 InitTempTableNamespace();
3407 recomputeNamespacePath();
3410 result = list_copy(activeSearchPath);
3411 if (!includeImplicit)
3413 while (result && linitial_oid(result) != activeCreationNamespace)
3414 result = list_delete_first(result);
3421 * Fetch the active search path into a caller-allocated array of OIDs.
3422 * Returns the number of path entries. (If this is more than sarray_len,
3423 * then the data didn't fit and is not all stored.)
3425 * The returned list always includes the implicitly-prepended namespaces,
3426 * but never includes the temp namespace. (This is suitable for existing
3427 * users, which would want to ignore the temp namespace anyway.) This
3428 * definition allows us to not worry about initializing the temp namespace.
3431 fetch_search_path_array(Oid *sarray, int sarray_len)
3436 recomputeNamespacePath();
3438 foreach(l, activeSearchPath)
3440 Oid namespaceId = lfirst_oid(l);
3442 if (namespaceId == myTempNamespace)
3443 continue; /* do not include temp namespace */
3445 if (count < sarray_len)
3446 sarray[count] = namespaceId;
3455 * Export the FooIsVisible functions as SQL-callable functions.
3457 * Note: as of Postgres 8.4, these will silently return NULL if called on
3458 * a nonexistent object OID, rather than failing. This is to avoid race
3459 * condition errors when a query that's scanning a catalog using an MVCC
3460 * snapshot uses one of these functions. The underlying IsVisible functions
3461 * operate on SnapshotNow semantics and so might see the object as already
3462 * gone when it's still visible to the MVCC snapshot. (There is no race
3463 * condition in the current coding because we don't accept sinval messages
3464 * between the SearchSysCacheExists test and the subsequent lookup.)
3468 pg_table_is_visible(PG_FUNCTION_ARGS)
3470 Oid oid = PG_GETARG_OID(0);
3472 if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(oid)))
3475 PG_RETURN_BOOL(RelationIsVisible(oid));
3479 pg_type_is_visible(PG_FUNCTION_ARGS)
3481 Oid oid = PG_GETARG_OID(0);
3483 if (!SearchSysCacheExists1(TYPEOID, ObjectIdGetDatum(oid)))
3486 PG_RETURN_BOOL(TypeIsVisible(oid));
3490 pg_function_is_visible(PG_FUNCTION_ARGS)
3492 Oid oid = PG_GETARG_OID(0);
3494 if (!SearchSysCacheExists1(PROCOID, ObjectIdGetDatum(oid)))
3497 PG_RETURN_BOOL(FunctionIsVisible(oid));
3501 pg_operator_is_visible(PG_FUNCTION_ARGS)
3503 Oid oid = PG_GETARG_OID(0);
3505 if (!SearchSysCacheExists1(OPEROID, ObjectIdGetDatum(oid)))
3508 PG_RETURN_BOOL(OperatorIsVisible(oid));
3512 pg_opclass_is_visible(PG_FUNCTION_ARGS)
3514 Oid oid = PG_GETARG_OID(0);
3516 if (!SearchSysCacheExists1(CLAOID, ObjectIdGetDatum(oid)))
3519 PG_RETURN_BOOL(OpclassIsVisible(oid));
3523 pg_conversion_is_visible(PG_FUNCTION_ARGS)
3525 Oid oid = PG_GETARG_OID(0);
3527 if (!SearchSysCacheExists1(CONVOID, ObjectIdGetDatum(oid)))
3530 PG_RETURN_BOOL(ConversionIsVisible(oid));
3534 pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
3536 Oid oid = PG_GETARG_OID(0);
3538 if (!SearchSysCacheExists1(TSPARSEROID, ObjectIdGetDatum(oid)))
3541 PG_RETURN_BOOL(TSParserIsVisible(oid));
3545 pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
3547 Oid oid = PG_GETARG_OID(0);
3549 if (!SearchSysCacheExists1(TSDICTOID, ObjectIdGetDatum(oid)))
3552 PG_RETURN_BOOL(TSDictionaryIsVisible(oid));
3556 pg_ts_template_is_visible(PG_FUNCTION_ARGS)
3558 Oid oid = PG_GETARG_OID(0);
3560 if (!SearchSysCacheExists1(TSTEMPLATEOID, ObjectIdGetDatum(oid)))
3563 PG_RETURN_BOOL(TSTemplateIsVisible(oid));
3567 pg_ts_config_is_visible(PG_FUNCTION_ARGS)
3569 Oid oid = PG_GETARG_OID(0);
3571 if (!SearchSysCacheExists1(TSCONFIGOID, ObjectIdGetDatum(oid)))
3574 PG_RETURN_BOOL(TSConfigIsVisible(oid));
3578 pg_my_temp_schema(PG_FUNCTION_ARGS)
3580 PG_RETURN_OID(myTempNamespace);
3584 pg_is_other_temp_schema(PG_FUNCTION_ARGS)
3586 Oid oid = PG_GETARG_OID(0);
3588 PG_RETURN_BOOL(isOtherTempNamespace(oid));