PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
namespace.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * namespace.c
4  * code to support accessing and searching namespaces
5  *
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.
10  *
11  *
12  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  * IDENTIFICATION
16  * src/backend/catalog/namespace.c
17  *
18  *-------------------------------------------------------------------------
19  */
20 #include "postgres.h"
21 
22 #include "access/htup_details.h"
23 #include "access/parallel.h"
24 #include "access/xact.h"
25 #include "access/xlog.h"
26 #include "catalog/dependency.h"
27 #include "catalog/objectaccess.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_collation.h"
30 #include "catalog/pg_conversion.h"
32 #include "catalog/pg_namespace.h"
33 #include "catalog/pg_opclass.h"
34 #include "catalog/pg_operator.h"
35 #include "catalog/pg_opfamily.h"
36 #include "catalog/pg_proc.h"
37 #include "catalog/pg_ts_config.h"
38 #include "catalog/pg_ts_dict.h"
39 #include "catalog/pg_ts_parser.h"
40 #include "catalog/pg_ts_template.h"
41 #include "catalog/pg_type.h"
42 #include "commands/dbcommands.h"
43 #include "funcapi.h"
44 #include "mb/pg_wchar.h"
45 #include "miscadmin.h"
46 #include "nodes/makefuncs.h"
47 #include "parser/parse_func.h"
48 #include "storage/ipc.h"
49 #include "storage/lmgr.h"
50 #include "storage/sinval.h"
51 #include "utils/acl.h"
52 #include "utils/builtins.h"
53 #include "utils/catcache.h"
54 #include "utils/guc.h"
55 #include "utils/inval.h"
56 #include "utils/lsyscache.h"
57 #include "utils/memutils.h"
58 #include "utils/syscache.h"
59 
60 
61 /*
62  * The namespace search path is a possibly-empty list of namespace OIDs.
63  * In addition to the explicit list, implicitly-searched namespaces
64  * may be included:
65  *
66  * 1. If a TEMP table namespace has been initialized in this session, it
67  * is implicitly searched first. (The only time this doesn't happen is
68  * when we are obeying an override search path spec that says not to use the
69  * temp namespace, or the temp namespace is included in the explicit list.)
70  *
71  * 2. The system catalog namespace is always searched. If the system
72  * namespace is present in the explicit path then it will be searched in
73  * the specified order; otherwise it will be searched after TEMP tables and
74  * *before* the explicit list. (It might seem that the system namespace
75  * should be implicitly last, but this behavior appears to be required by
76  * SQL99. Also, this provides a way to search the system namespace first
77  * without thereby making it the default creation target namespace.)
78  *
79  * For security reasons, searches using the search path will ignore the temp
80  * namespace when searching for any object type other than relations and
81  * types. (We must allow types since temp tables have rowtypes.)
82  *
83  * The default creation target namespace is always the first element of the
84  * explicit list. If the explicit list is empty, there is no default target.
85  *
86  * The textual specification of search_path can include "$user" to refer to
87  * the namespace named the same as the current user, if any. (This is just
88  * ignored if there is no such namespace.) Also, it can include "pg_temp"
89  * to refer to the current backend's temp namespace. This is usually also
90  * ignorable if the temp namespace hasn't been set up, but there's a special
91  * case: if "pg_temp" appears first then it should be the default creation
92  * target. We kluge this case a little bit so that the temp namespace isn't
93  * set up until the first attempt to create something in it. (The reason for
94  * klugery is that we can't create the temp namespace outside a transaction,
95  * but initial GUC processing of search_path happens outside a transaction.)
96  * activeTempCreationPending is TRUE if "pg_temp" appears first in the string
97  * but is not reflected in activeCreationNamespace because the namespace isn't
98  * set up yet.
99  *
100  * In bootstrap mode, the search path is set equal to "pg_catalog", so that
101  * the system namespace is the only one searched or inserted into.
102  * initdb is also careful to set search_path to "pg_catalog" for its
103  * post-bootstrap standalone backend runs. Otherwise the default search
104  * path is determined by GUC. The factory default path contains the PUBLIC
105  * namespace (if it exists), preceded by the user's personal namespace
106  * (if one exists).
107  *
108  * We support a stack of "override" search path settings for use within
109  * specific sections of backend code. namespace_search_path is ignored
110  * whenever the override stack is nonempty. activeSearchPath is always
111  * the actually active path; it points either to the search list of the
112  * topmost stack entry, or to baseSearchPath which is the list derived
113  * from namespace_search_path.
114  *
115  * If baseSearchPathValid is false, then baseSearchPath (and other
116  * derived variables) need to be recomputed from namespace_search_path.
117  * We mark it invalid upon an assignment to namespace_search_path or receipt
118  * of a syscache invalidation event for pg_namespace. The recomputation
119  * is done during the next non-overridden lookup attempt. Note that an
120  * override spec is never subject to recomputation.
121  *
122  * Any namespaces mentioned in namespace_search_path that are not readable
123  * by the current user ID are simply left out of baseSearchPath; so
124  * we have to be willing to recompute the path when current userid changes.
125  * namespaceUser is the userid the path has been computed for.
126  *
127  * Note: all data pointed to by these List variables is in TopMemoryContext.
128  */
129 
130 /* These variables define the actually active state: */
131 
133 
134 /* default place to create stuff; if InvalidOid, no default */
136 
137 /* if TRUE, activeCreationNamespace is wrong, it should be temp namespace */
138 static bool activeTempCreationPending = false;
139 
140 /* These variables are the values last derived from namespace_search_path: */
141 
143 
145 
146 static bool baseTempCreationPending = false;
147 
149 
150 /* The above four values are valid only if baseSearchPathValid */
151 static bool baseSearchPathValid = true;
152 
153 /* Override requests are remembered in a stack of OverrideStackEntry structs */
154 
155 typedef struct
156 {
157  List *searchPath; /* the desired search path */
158  Oid creationNamespace; /* the desired creation namespace */
159  int nestLevel; /* subtransaction nesting level */
161 
163 
164 /*
165  * myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
166  * in a particular backend session (this happens when a CREATE TEMP TABLE
167  * command is first executed). Thereafter it's the OID of the temp namespace.
168  *
169  * myTempToastNamespace is the OID of the namespace for my temp tables' toast
170  * tables. It is set when myTempNamespace is, and is InvalidOid before that.
171  *
172  * myTempNamespaceSubID shows whether we've created the TEMP namespace in the
173  * current subtransaction. The flag propagates up the subtransaction tree,
174  * so the main transaction will correctly recognize the flag if all
175  * intermediate subtransactions commit. When it is InvalidSubTransactionId,
176  * we either haven't made the TEMP namespace yet, or have successfully
177  * committed its creation, depending on whether myTempNamespace is valid.
178  */
180 
182 
184 
185 /*
186  * This is the user's textual search path specification --- it's the value
187  * of the GUC variable 'search_path'.
188  */
190 
191 
192 /* Local functions */
193 static void recomputeNamespacePath(void);
194 static void InitTempTableNamespace(void);
195 static void RemoveTempRelations(Oid tempNamespaceId);
196 static void RemoveTempRelationsCallback(int code, Datum arg);
197 static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue);
198 static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
199  int **argnumbers);
200 
201 /* These don't really need to appear in any header file */
216 
217 
218 /*
219  * RangeVarGetRelid
220  * Given a RangeVar describing an existing relation,
221  * select the proper namespace and look up the relation OID.
222  *
223  * If the schema or relation is not found, return InvalidOid if missing_ok
224  * = true, otherwise raise an error.
225  *
226  * If nowait = true, throw an error if we'd have to wait for a lock.
227  *
228  * Callback allows caller to check permissions or acquire additional locks
229  * prior to grabbing the relation lock.
230  */
231 Oid
232 RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
233  bool missing_ok, bool nowait,
234  RangeVarGetRelidCallback callback, void *callback_arg)
235 {
236  uint64 inval_count;
237  Oid relId;
238  Oid oldRelId = InvalidOid;
239  bool retry = false;
240 
241  /*
242  * We check the catalog name and then ignore it.
243  */
244  if (relation->catalogname)
245  {
246  if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
247  ereport(ERROR,
248  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
249  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
250  relation->catalogname, relation->schemaname,
251  relation->relname)));
252  }
253 
254  /*
255  * DDL operations can change the results of a name lookup. Since all such
256  * operations will generate invalidation messages, we keep track of
257  * whether any such messages show up while we're performing the operation,
258  * and retry until either (1) no more invalidation messages show up or (2)
259  * the answer doesn't change.
260  *
261  * But if lockmode = NoLock, then we assume that either the caller is OK
262  * with the answer changing under them, or that they already hold some
263  * appropriate lock, and therefore return the first answer we get without
264  * checking for invalidation messages. Also, if the requested lock is
265  * already held, LockRelationOid will not AcceptInvalidationMessages, so
266  * we may fail to notice a change. We could protect against that case by
267  * calling AcceptInvalidationMessages() before beginning this loop, but
268  * that would add a significant amount overhead, so for now we don't.
269  */
270  for (;;)
271  {
272  /*
273  * Remember this value, so that, after looking up the relation name
274  * and locking its OID, we can check whether any invalidation messages
275  * have been processed that might require a do-over.
276  */
277  inval_count = SharedInvalidMessageCounter;
278 
279  /*
280  * Some non-default relpersistence value may have been specified. The
281  * parser never generates such a RangeVar in simple DML, but it can
282  * happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
283  * KEY)". Such a command will generate an added CREATE INDEX
284  * operation, which must be careful to find the temp table, even when
285  * pg_temp is not first in the search path.
286  */
287  if (relation->relpersistence == RELPERSISTENCE_TEMP)
288  {
290  relId = InvalidOid; /* this probably can't happen? */
291  else
292  {
293  if (relation->schemaname)
294  {
295  Oid namespaceId;
296 
297  namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
298 
299  /*
300  * For missing_ok, allow a non-existant schema name to
301  * return InvalidOid.
302  */
303  if (namespaceId != myTempNamespace)
304  ereport(ERROR,
305  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
306  errmsg("temporary tables cannot specify a schema name")));
307  }
308 
309  relId = get_relname_relid(relation->relname, myTempNamespace);
310  }
311  }
312  else if (relation->schemaname)
313  {
314  Oid namespaceId;
315 
316  /* use exact schema given */
317  namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
318  if (missing_ok && !OidIsValid(namespaceId))
319  relId = InvalidOid;
320  else
321  relId = get_relname_relid(relation->relname, namespaceId);
322  }
323  else
324  {
325  /* search the namespace path */
326  relId = RelnameGetRelid(relation->relname);
327  }
328 
329  /*
330  * Invoke caller-supplied callback, if any.
331  *
332  * This callback is a good place to check permissions: we haven't
333  * taken the table lock yet (and it's really best to check permissions
334  * before locking anything!), but we've gotten far enough to know what
335  * OID we think we should lock. Of course, concurrent DDL might
336  * change things while we're waiting for the lock, but in that case
337  * the callback will be invoked again for the new OID.
338  */
339  if (callback)
340  callback(relation, relId, oldRelId, callback_arg);
341 
342  /*
343  * If no lock requested, we assume the caller knows what they're
344  * doing. They should have already acquired a heavyweight lock on
345  * this relation earlier in the processing of this same statement, so
346  * it wouldn't be appropriate to AcceptInvalidationMessages() here, as
347  * that might pull the rug out from under them.
348  */
349  if (lockmode == NoLock)
350  break;
351 
352  /*
353  * If, upon retry, we get back the same OID we did last time, then the
354  * invalidation messages we processed did not change the final answer.
355  * So we're done.
356  *
357  * If we got a different OID, we've locked the relation that used to
358  * have this name rather than the one that does now. So release the
359  * lock.
360  */
361  if (retry)
362  {
363  if (relId == oldRelId)
364  break;
365  if (OidIsValid(oldRelId))
366  UnlockRelationOid(oldRelId, lockmode);
367  }
368 
369  /*
370  * Lock relation. This will also accept any pending invalidation
371  * messages. If we got back InvalidOid, indicating not found, then
372  * there's nothing to lock, but we accept invalidation messages
373  * anyway, to flush any negative catcache entries that may be
374  * lingering.
375  */
376  if (!OidIsValid(relId))
378  else if (!nowait)
379  LockRelationOid(relId, lockmode);
380  else if (!ConditionalLockRelationOid(relId, lockmode))
381  {
382  if (relation->schemaname)
383  ereport(ERROR,
384  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
385  errmsg("could not obtain lock on relation \"%s.%s\"",
386  relation->schemaname, relation->relname)));
387  else
388  ereport(ERROR,
389  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
390  errmsg("could not obtain lock on relation \"%s\"",
391  relation->relname)));
392  }
393 
394  /*
395  * If no invalidation message were processed, we're done!
396  */
397  if (inval_count == SharedInvalidMessageCounter)
398  break;
399 
400  /*
401  * Something may have changed. Let's repeat the name lookup, to make
402  * sure this name still references the same relation it did
403  * previously.
404  */
405  retry = true;
406  oldRelId = relId;
407  }
408 
409  if (!OidIsValid(relId) && !missing_ok)
410  {
411  if (relation->schemaname)
412  ereport(ERROR,
414  errmsg("relation \"%s.%s\" does not exist",
415  relation->schemaname, relation->relname)));
416  else
417  ereport(ERROR,
419  errmsg("relation \"%s\" does not exist",
420  relation->relname)));
421  }
422  return relId;
423 }
424 
425 /*
426  * RangeVarGetCreationNamespace
427  * Given a RangeVar describing a to-be-created relation,
428  * choose which namespace to create it in.
429  *
430  * Note: calling this may result in a CommandCounterIncrement operation.
431  * That will happen on the first request for a temp table in any particular
432  * backend run; we will need to either create or clean out the temp schema.
433  */
434 Oid
436 {
437  Oid namespaceId;
438 
439  /*
440  * We check the catalog name and then ignore it.
441  */
442  if (newRelation->catalogname)
443  {
444  if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
445  ereport(ERROR,
446  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
447  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
448  newRelation->catalogname, newRelation->schemaname,
449  newRelation->relname)));
450  }
451 
452  if (newRelation->schemaname)
453  {
454  /* check for pg_temp alias */
455  if (strcmp(newRelation->schemaname, "pg_temp") == 0)
456  {
457  /* Initialize temp namespace if first time through */
460  return myTempNamespace;
461  }
462  /* use exact schema given */
463  namespaceId = get_namespace_oid(newRelation->schemaname, false);
464  /* we do not check for USAGE rights here! */
465  }
466  else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
467  {
468  /* Initialize temp namespace if first time through */
471  return myTempNamespace;
472  }
473  else
474  {
475  /* use the default creation namespace */
478  {
479  /* Need to initialize temp namespace */
481  return myTempNamespace;
482  }
483  namespaceId = activeCreationNamespace;
484  if (!OidIsValid(namespaceId))
485  ereport(ERROR,
486  (errcode(ERRCODE_UNDEFINED_SCHEMA),
487  errmsg("no schema has been selected to create in")));
488  }
489 
490  /* Note: callers will check for CREATE rights when appropriate */
491 
492  return namespaceId;
493 }
494 
495 /*
496  * RangeVarGetAndCheckCreationNamespace
497  *
498  * This function returns the OID of the namespace in which a new relation
499  * with a given name should be created. If the user does not have CREATE
500  * permission on the target namespace, this function will instead signal
501  * an ERROR.
502  *
503  * If non-NULL, *existing_oid is set to the OID of any existing relation with
504  * the same name which already exists in that namespace, or to InvalidOid if
505  * no such relation exists.
506  *
507  * If lockmode != NoLock, the specified lock mode is acquired on the existing
508  * relation, if any, provided that the current user owns the target relation.
509  * However, if lockmode != NoLock and the user does not own the target
510  * relation, we throw an ERROR, as we must not try to lock relations the
511  * user does not have permissions on.
512  *
513  * As a side effect, this function acquires AccessShareLock on the target
514  * namespace. Without this, the namespace could be dropped before our
515  * transaction commits, leaving behind relations with relnamespace pointing
516  * to a no-longer-existent namespace.
517  *
518  * As a further side-effect, if the selected namespace is a temporary namespace,
519  * we mark the RangeVar as RELPERSISTENCE_TEMP.
520  */
521 Oid
523  LOCKMODE lockmode,
524  Oid *existing_relation_id)
525 {
526  uint64 inval_count;
527  Oid relid;
528  Oid oldrelid = InvalidOid;
529  Oid nspid;
530  Oid oldnspid = InvalidOid;
531  bool retry = false;
532 
533  /*
534  * We check the catalog name and then ignore it.
535  */
536  if (relation->catalogname)
537  {
538  if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
539  ereport(ERROR,
540  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
541  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
542  relation->catalogname, relation->schemaname,
543  relation->relname)));
544  }
545 
546  /*
547  * As in RangeVarGetRelidExtended(), we guard against concurrent DDL
548  * operations by tracking whether any invalidation messages are processed
549  * while we're doing the name lookups and acquiring locks. See comments
550  * in that function for a more detailed explanation of this logic.
551  */
552  for (;;)
553  {
554  AclResult aclresult;
555 
556  inval_count = SharedInvalidMessageCounter;
557 
558  /* Look up creation namespace and check for existing relation. */
559  nspid = RangeVarGetCreationNamespace(relation);
560  Assert(OidIsValid(nspid));
561  if (existing_relation_id != NULL)
562  relid = get_relname_relid(relation->relname, nspid);
563  else
564  relid = InvalidOid;
565 
566  /*
567  * In bootstrap processing mode, we don't bother with permissions or
568  * locking. Permissions might not be working yet, and locking is
569  * unnecessary.
570  */
572  break;
573 
574  /* Check namespace permissions. */
575  aclresult = pg_namespace_aclcheck(nspid, GetUserId(), ACL_CREATE);
576  if (aclresult != ACLCHECK_OK)
578  get_namespace_name(nspid));
579 
580  if (retry)
581  {
582  /* If nothing changed, we're done. */
583  if (relid == oldrelid && nspid == oldnspid)
584  break;
585  /* If creation namespace has changed, give up old lock. */
586  if (nspid != oldnspid)
589  /* If name points to something different, give up old lock. */
590  if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
591  UnlockRelationOid(oldrelid, lockmode);
592  }
593 
594  /* Lock namespace. */
595  if (nspid != oldnspid)
597 
598  /* Lock relation, if required if and we have permission. */
599  if (lockmode != NoLock && OidIsValid(relid))
600  {
601  if (!pg_class_ownercheck(relid, GetUserId()))
603  relation->relname);
604  if (relid != oldrelid)
605  LockRelationOid(relid, lockmode);
606  }
607 
608  /* If no invalidation message were processed, we're done! */
609  if (inval_count == SharedInvalidMessageCounter)
610  break;
611 
612  /* Something may have changed, so recheck our work. */
613  retry = true;
614  oldrelid = relid;
615  oldnspid = nspid;
616  }
617 
618  RangeVarAdjustRelationPersistence(relation, nspid);
619  if (existing_relation_id != NULL)
620  *existing_relation_id = relid;
621  return nspid;
622 }
623 
624 /*
625  * Adjust the relpersistence for an about-to-be-created relation based on the
626  * creation namespace, and throw an error for invalid combinations.
627  */
628 void
630 {
631  switch (newRelation->relpersistence)
632  {
633  case RELPERSISTENCE_TEMP:
634  if (!isTempOrTempToastNamespace(nspid))
635  {
636  if (isAnyTempNamespace(nspid))
637  ereport(ERROR,
638  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
639  errmsg("cannot create relations in temporary schemas of other sessions")));
640  else
641  ereport(ERROR,
642  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
643  errmsg("cannot create temporary relation in non-temporary schema")));
644  }
645  break;
647  if (isTempOrTempToastNamespace(nspid))
648  newRelation->relpersistence = RELPERSISTENCE_TEMP;
649  else if (isAnyTempNamespace(nspid))
650  ereport(ERROR,
651  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
652  errmsg("cannot create relations in temporary schemas of other sessions")));
653  break;
654  default:
655  if (isAnyTempNamespace(nspid))
656  ereport(ERROR,
657  (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
658  errmsg("only temporary relations may be created in temporary schemas")));
659  }
660 }
661 
662 /*
663  * RelnameGetRelid
664  * Try to resolve an unqualified relation name.
665  * Returns OID if relation found in search path, else InvalidOid.
666  */
667 Oid
669 {
670  Oid relid;
671  ListCell *l;
672 
674 
675  foreach(l, activeSearchPath)
676  {
677  Oid namespaceId = lfirst_oid(l);
678 
679  relid = get_relname_relid(relname, namespaceId);
680  if (OidIsValid(relid))
681  return relid;
682  }
683 
684  /* Not found in path */
685  return InvalidOid;
686 }
687 
688 
689 /*
690  * RelationIsVisible
691  * Determine whether a relation (identified by OID) is visible in the
692  * current search path. Visible means "would be found by searching
693  * for the unqualified relation name".
694  */
695 bool
697 {
698  HeapTuple reltup;
699  Form_pg_class relform;
700  Oid relnamespace;
701  bool visible;
702 
703  reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
704  if (!HeapTupleIsValid(reltup))
705  elog(ERROR, "cache lookup failed for relation %u", relid);
706  relform = (Form_pg_class) GETSTRUCT(reltup);
707 
709 
710  /*
711  * Quick check: if it ain't in the path at all, it ain't visible. Items in
712  * the system namespace are surely in the path and so we needn't even do
713  * list_member_oid() for them.
714  */
715  relnamespace = relform->relnamespace;
716  if (relnamespace != PG_CATALOG_NAMESPACE &&
717  !list_member_oid(activeSearchPath, relnamespace))
718  visible = false;
719  else
720  {
721  /*
722  * If it is in the path, it might still not be visible; it could be
723  * hidden by another relation of the same name earlier in the path. So
724  * we must do a slow check for conflicting relations.
725  */
726  char *relname = NameStr(relform->relname);
727  ListCell *l;
728 
729  visible = false;
730  foreach(l, activeSearchPath)
731  {
732  Oid namespaceId = lfirst_oid(l);
733 
734  if (namespaceId == relnamespace)
735  {
736  /* Found it first in path */
737  visible = true;
738  break;
739  }
740  if (OidIsValid(get_relname_relid(relname, namespaceId)))
741  {
742  /* Found something else first in path */
743  break;
744  }
745  }
746  }
747 
748  ReleaseSysCache(reltup);
749 
750  return visible;
751 }
752 
753 
754 /*
755  * TypenameGetTypid
756  * Try to resolve an unqualified datatype name.
757  * Returns OID if type found in search path, else InvalidOid.
758  *
759  * This is essentially the same as RelnameGetRelid.
760  */
761 Oid
762 TypenameGetTypid(const char *typname)
763 {
764  Oid typid;
765  ListCell *l;
766 
768 
769  foreach(l, activeSearchPath)
770  {
771  Oid namespaceId = lfirst_oid(l);
772 
774  PointerGetDatum(typname),
775  ObjectIdGetDatum(namespaceId));
776  if (OidIsValid(typid))
777  return typid;
778  }
779 
780  /* Not found in path */
781  return InvalidOid;
782 }
783 
784 /*
785  * TypeIsVisible
786  * Determine whether a type (identified by OID) is visible in the
787  * current search path. Visible means "would be found by searching
788  * for the unqualified type name".
789  */
790 bool
792 {
793  HeapTuple typtup;
794  Form_pg_type typform;
795  Oid typnamespace;
796  bool visible;
797 
798  typtup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
799  if (!HeapTupleIsValid(typtup))
800  elog(ERROR, "cache lookup failed for type %u", typid);
801  typform = (Form_pg_type) GETSTRUCT(typtup);
802 
804 
805  /*
806  * Quick check: if it ain't in the path at all, it ain't visible. Items in
807  * the system namespace are surely in the path and so we needn't even do
808  * list_member_oid() for them.
809  */
810  typnamespace = typform->typnamespace;
811  if (typnamespace != PG_CATALOG_NAMESPACE &&
812  !list_member_oid(activeSearchPath, typnamespace))
813  visible = false;
814  else
815  {
816  /*
817  * If it is in the path, it might still not be visible; it could be
818  * hidden by another type of the same name earlier in the path. So we
819  * must do a slow check for conflicting types.
820  */
821  char *typname = NameStr(typform->typname);
822  ListCell *l;
823 
824  visible = false;
825  foreach(l, activeSearchPath)
826  {
827  Oid namespaceId = lfirst_oid(l);
828 
829  if (namespaceId == typnamespace)
830  {
831  /* Found it first in path */
832  visible = true;
833  break;
834  }
836  PointerGetDatum(typname),
837  ObjectIdGetDatum(namespaceId)))
838  {
839  /* Found something else first in path */
840  break;
841  }
842  }
843  }
844 
845  ReleaseSysCache(typtup);
846 
847  return visible;
848 }
849 
850 
851 /*
852  * FuncnameGetCandidates
853  * Given a possibly-qualified function name and argument count,
854  * retrieve a list of the possible matches.
855  *
856  * If nargs is -1, we return all functions matching the given name,
857  * regardless of argument count. (argnames must be NIL, and expand_variadic
858  * and expand_defaults must be false, in this case.)
859  *
860  * If argnames isn't NIL, we are considering a named- or mixed-notation call,
861  * and only functions having all the listed argument names will be returned.
862  * (We assume that length(argnames) <= nargs and all the passed-in names are
863  * distinct.) The returned structs will include an argnumbers array showing
864  * the actual argument index for each logical argument position.
865  *
866  * If expand_variadic is true, then variadic functions having the same number
867  * or fewer arguments will be retrieved, with the variadic argument and any
868  * additional argument positions filled with the variadic element type.
869  * nvargs in the returned struct is set to the number of such arguments.
870  * If expand_variadic is false, variadic arguments are not treated specially,
871  * and the returned nvargs will always be zero.
872  *
873  * If expand_defaults is true, functions that could match after insertion of
874  * default argument values will also be retrieved. In this case the returned
875  * structs could have nargs > passed-in nargs, and ndargs is set to the number
876  * of additional args (which can be retrieved from the function's
877  * proargdefaults entry).
878  *
879  * It is not possible for nvargs and ndargs to both be nonzero in the same
880  * list entry, since default insertion allows matches to functions with more
881  * than nargs arguments while the variadic transformation requires the same
882  * number or less.
883  *
884  * When argnames isn't NIL, the returned args[] type arrays are not ordered
885  * according to the functions' declarations, but rather according to the call:
886  * first any positional arguments, then the named arguments, then defaulted
887  * arguments (if needed and allowed by expand_defaults). The argnumbers[]
888  * array can be used to map this back to the catalog information.
889  * argnumbers[k] is set to the proargtypes index of the k'th call argument.
890  *
891  * We search a single namespace if the function name is qualified, else
892  * all namespaces in the search path. In the multiple-namespace case,
893  * we arrange for entries in earlier namespaces to mask identical entries in
894  * later namespaces.
895  *
896  * When expanding variadics, we arrange for non-variadic functions to mask
897  * variadic ones if the expanded argument list is the same. It is still
898  * possible for there to be conflicts between different variadic functions,
899  * however.
900  *
901  * It is guaranteed that the return list will never contain multiple entries
902  * with identical argument lists. When expand_defaults is true, the entries
903  * could have more than nargs positions, but we still guarantee that they are
904  * distinct in the first nargs positions. However, if argnames isn't NIL or
905  * either expand_variadic or expand_defaults is true, there might be multiple
906  * candidate functions that expand to identical argument lists. Rather than
907  * throw error here, we report such situations by returning a single entry
908  * with oid = 0 that represents a set of such conflicting candidates.
909  * The caller might end up discarding such an entry anyway, but if it selects
910  * such an entry it should react as though the call were ambiguous.
911  *
912  * If missing_ok is true, an empty list (NULL) is returned if the name was
913  * schema- qualified with a schema that does not exist. Likewise if no
914  * candidate is found for other reasons.
915  */
917 FuncnameGetCandidates(List *names, int nargs, List *argnames,
918  bool expand_variadic, bool expand_defaults,
919  bool missing_ok)
920 {
921  FuncCandidateList resultList = NULL;
922  bool any_special = false;
923  char *schemaname;
924  char *funcname;
925  Oid namespaceId;
926  CatCList *catlist;
927  int i;
928 
929  /* check for caller error */
930  Assert(nargs >= 0 || !(expand_variadic | expand_defaults));
931 
932  /* deconstruct the name list */
933  DeconstructQualifiedName(names, &schemaname, &funcname);
934 
935  if (schemaname)
936  {
937  /* use exact schema given */
938  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
939  if (!OidIsValid(namespaceId))
940  return NULL;
941  }
942  else
943  {
944  /* flag to indicate we need namespace search */
945  namespaceId = InvalidOid;
947  }
948 
949  /* Search syscache by name only */
951 
952  for (i = 0; i < catlist->n_members; i++)
953  {
954  HeapTuple proctup = &catlist->members[i]->tuple;
955  Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
956  int pronargs = procform->pronargs;
957  int effective_nargs;
958  int pathpos = 0;
959  bool variadic;
960  bool use_defaults;
961  Oid va_elem_type;
962  int *argnumbers = NULL;
963  FuncCandidateList newResult;
964 
965  if (OidIsValid(namespaceId))
966  {
967  /* Consider only procs in specified namespace */
968  if (procform->pronamespace != namespaceId)
969  continue;
970  }
971  else
972  {
973  /*
974  * Consider only procs that are in the search path and are not in
975  * the temp namespace.
976  */
977  ListCell *nsp;
978 
979  foreach(nsp, activeSearchPath)
980  {
981  if (procform->pronamespace == lfirst_oid(nsp) &&
982  procform->pronamespace != myTempNamespace)
983  break;
984  pathpos++;
985  }
986  if (nsp == NULL)
987  continue; /* proc is not in search path */
988  }
989 
990  if (argnames != NIL)
991  {
992  /*
993  * Call uses named or mixed notation
994  *
995  * Named or mixed notation can match a variadic function only if
996  * expand_variadic is off; otherwise there is no way to match the
997  * presumed-nameless parameters expanded from the variadic array.
998  */
999  if (OidIsValid(procform->provariadic) && expand_variadic)
1000  continue;
1001  va_elem_type = InvalidOid;
1002  variadic = false;
1003 
1004  /*
1005  * Check argument count.
1006  */
1007  Assert(nargs >= 0); /* -1 not supported with argnames */
1008 
1009  if (pronargs > nargs && expand_defaults)
1010  {
1011  /* Ignore if not enough default expressions */
1012  if (nargs + procform->pronargdefaults < pronargs)
1013  continue;
1014  use_defaults = true;
1015  }
1016  else
1017  use_defaults = false;
1018 
1019  /* Ignore if it doesn't match requested argument count */
1020  if (pronargs != nargs && !use_defaults)
1021  continue;
1022 
1023  /* Check for argument name match, generate positional mapping */
1024  if (!MatchNamedCall(proctup, nargs, argnames,
1025  &argnumbers))
1026  continue;
1027 
1028  /* Named argument matching is always "special" */
1029  any_special = true;
1030  }
1031  else
1032  {
1033  /*
1034  * Call uses positional notation
1035  *
1036  * Check if function is variadic, and get variadic element type if
1037  * so. If expand_variadic is false, we should just ignore
1038  * variadic-ness.
1039  */
1040  if (pronargs <= nargs && expand_variadic)
1041  {
1042  va_elem_type = procform->provariadic;
1043  variadic = OidIsValid(va_elem_type);
1044  any_special |= variadic;
1045  }
1046  else
1047  {
1048  va_elem_type = InvalidOid;
1049  variadic = false;
1050  }
1051 
1052  /*
1053  * Check if function can match by using parameter defaults.
1054  */
1055  if (pronargs > nargs && expand_defaults)
1056  {
1057  /* Ignore if not enough default expressions */
1058  if (nargs + procform->pronargdefaults < pronargs)
1059  continue;
1060  use_defaults = true;
1061  any_special = true;
1062  }
1063  else
1064  use_defaults = false;
1065 
1066  /* Ignore if it doesn't match requested argument count */
1067  if (nargs >= 0 && pronargs != nargs && !variadic && !use_defaults)
1068  continue;
1069  }
1070 
1071  /*
1072  * We must compute the effective argument list so that we can easily
1073  * compare it to earlier results. We waste a palloc cycle if it gets
1074  * masked by an earlier result, but really that's a pretty infrequent
1075  * case so it's not worth worrying about.
1076  */
1077  effective_nargs = Max(pronargs, nargs);
1078  newResult = (FuncCandidateList)
1080  effective_nargs * sizeof(Oid));
1081  newResult->pathpos = pathpos;
1082  newResult->oid = HeapTupleGetOid(proctup);
1083  newResult->nargs = effective_nargs;
1084  newResult->argnumbers = argnumbers;
1085  if (argnumbers)
1086  {
1087  /* Re-order the argument types into call's logical order */
1088  Oid *proargtypes = procform->proargtypes.values;
1089  int i;
1090 
1091  for (i = 0; i < pronargs; i++)
1092  newResult->args[i] = proargtypes[argnumbers[i]];
1093  }
1094  else
1095  {
1096  /* Simple positional case, just copy proargtypes as-is */
1097  memcpy(newResult->args, procform->proargtypes.values,
1098  pronargs * sizeof(Oid));
1099  }
1100  if (variadic)
1101  {
1102  int i;
1103 
1104  newResult->nvargs = effective_nargs - pronargs + 1;
1105  /* Expand variadic argument into N copies of element type */
1106  for (i = pronargs - 1; i < effective_nargs; i++)
1107  newResult->args[i] = va_elem_type;
1108  }
1109  else
1110  newResult->nvargs = 0;
1111  newResult->ndargs = use_defaults ? pronargs - nargs : 0;
1112 
1113  /*
1114  * Does it have the same arguments as something we already accepted?
1115  * If so, decide what to do to avoid returning duplicate argument
1116  * lists. We can skip this check for the single-namespace case if no
1117  * special (named, variadic or defaults) match has been made, since
1118  * then the unique index on pg_proc guarantees all the matches have
1119  * different argument lists.
1120  */
1121  if (resultList != NULL &&
1122  (any_special || !OidIsValid(namespaceId)))
1123  {
1124  /*
1125  * If we have an ordered list from SearchSysCacheList (the normal
1126  * case), then any conflicting proc must immediately adjoin this
1127  * one in the list, so we only need to look at the newest result
1128  * item. If we have an unordered list, we have to scan the whole
1129  * result list. Also, if either the current candidate or any
1130  * previous candidate is a special match, we can't assume that
1131  * conflicts are adjacent.
1132  *
1133  * We ignore defaulted arguments in deciding what is a match.
1134  */
1135  FuncCandidateList prevResult;
1136 
1137  if (catlist->ordered && !any_special)
1138  {
1139  /* ndargs must be 0 if !any_special */
1140  if (effective_nargs == resultList->nargs &&
1141  memcmp(newResult->args,
1142  resultList->args,
1143  effective_nargs * sizeof(Oid)) == 0)
1144  prevResult = resultList;
1145  else
1146  prevResult = NULL;
1147  }
1148  else
1149  {
1150  int cmp_nargs = newResult->nargs - newResult->ndargs;
1151 
1152  for (prevResult = resultList;
1153  prevResult;
1154  prevResult = prevResult->next)
1155  {
1156  if (cmp_nargs == prevResult->nargs - prevResult->ndargs &&
1157  memcmp(newResult->args,
1158  prevResult->args,
1159  cmp_nargs * sizeof(Oid)) == 0)
1160  break;
1161  }
1162  }
1163 
1164  if (prevResult)
1165  {
1166  /*
1167  * We have a match with a previous result. Decide which one
1168  * to keep, or mark it ambiguous if we can't decide. The
1169  * logic here is preference > 0 means prefer the old result,
1170  * preference < 0 means prefer the new, preference = 0 means
1171  * ambiguous.
1172  */
1173  int preference;
1174 
1175  if (pathpos != prevResult->pathpos)
1176  {
1177  /*
1178  * Prefer the one that's earlier in the search path.
1179  */
1180  preference = pathpos - prevResult->pathpos;
1181  }
1182  else if (variadic && prevResult->nvargs == 0)
1183  {
1184  /*
1185  * With variadic functions we could have, for example,
1186  * both foo(numeric) and foo(variadic numeric[]) in the
1187  * same namespace; if so we prefer the non-variadic match
1188  * on efficiency grounds.
1189  */
1190  preference = 1;
1191  }
1192  else if (!variadic && prevResult->nvargs > 0)
1193  {
1194  preference = -1;
1195  }
1196  else
1197  {
1198  /*----------
1199  * We can't decide. This can happen with, for example,
1200  * both foo(numeric, variadic numeric[]) and
1201  * foo(variadic numeric[]) in the same namespace, or
1202  * both foo(int) and foo (int, int default something)
1203  * in the same namespace, or both foo(a int, b text)
1204  * and foo(b text, a int) in the same namespace.
1205  *----------
1206  */
1207  preference = 0;
1208  }
1209 
1210  if (preference > 0)
1211  {
1212  /* keep previous result */
1213  pfree(newResult);
1214  continue;
1215  }
1216  else if (preference < 0)
1217  {
1218  /* remove previous result from the list */
1219  if (prevResult == resultList)
1220  resultList = prevResult->next;
1221  else
1222  {
1223  FuncCandidateList prevPrevResult;
1224 
1225  for (prevPrevResult = resultList;
1226  prevPrevResult;
1227  prevPrevResult = prevPrevResult->next)
1228  {
1229  if (prevResult == prevPrevResult->next)
1230  {
1231  prevPrevResult->next = prevResult->next;
1232  break;
1233  }
1234  }
1235  Assert(prevPrevResult); /* assert we found it */
1236  }
1237  pfree(prevResult);
1238  /* fall through to add newResult to list */
1239  }
1240  else
1241  {
1242  /* mark old result as ambiguous, discard new */
1243  prevResult->oid = InvalidOid;
1244  pfree(newResult);
1245  continue;
1246  }
1247  }
1248  }
1249 
1250  /*
1251  * Okay to add it to result list
1252  */
1253  newResult->next = resultList;
1254  resultList = newResult;
1255  }
1256 
1257  ReleaseSysCacheList(catlist);
1258 
1259  return resultList;
1260 }
1261 
1262 /*
1263  * MatchNamedCall
1264  * Given a pg_proc heap tuple and a call's list of argument names,
1265  * check whether the function could match the call.
1266  *
1267  * The call could match if all supplied argument names are accepted by
1268  * the function, in positions after the last positional argument, and there
1269  * are defaults for all unsupplied arguments.
1270  *
1271  * The number of positional arguments is nargs - list_length(argnames).
1272  * Note caller has already done basic checks on argument count.
1273  *
1274  * On match, return true and fill *argnumbers with a palloc'd array showing
1275  * the mapping from call argument positions to actual function argument
1276  * numbers. Defaulted arguments are included in this map, at positions
1277  * after the last supplied argument.
1278  */
1279 static bool
1280 MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
1281  int **argnumbers)
1282 {
1283  Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(proctup);
1284  int pronargs = procform->pronargs;
1285  int numposargs = nargs - list_length(argnames);
1286  int pronallargs;
1287  Oid *p_argtypes;
1288  char **p_argnames;
1289  char *p_argmodes;
1290  bool arggiven[FUNC_MAX_ARGS];
1291  bool isnull;
1292  int ap; /* call args position */
1293  int pp; /* proargs position */
1294  ListCell *lc;
1295 
1296  Assert(argnames != NIL);
1297  Assert(numposargs >= 0);
1298  Assert(nargs <= pronargs);
1299 
1300  /* Ignore this function if its proargnames is null */
1302  &isnull);
1303  if (isnull)
1304  return false;
1305 
1306  /* OK, let's extract the argument names and types */
1307  pronallargs = get_func_arg_info(proctup,
1308  &p_argtypes, &p_argnames, &p_argmodes);
1309  Assert(p_argnames != NULL);
1310 
1311  /* initialize state for matching */
1312  *argnumbers = (int *) palloc(pronargs * sizeof(int));
1313  memset(arggiven, false, pronargs * sizeof(bool));
1314 
1315  /* there are numposargs positional args before the named args */
1316  for (ap = 0; ap < numposargs; ap++)
1317  {
1318  (*argnumbers)[ap] = ap;
1319  arggiven[ap] = true;
1320  }
1321 
1322  /* now examine the named args */
1323  foreach(lc, argnames)
1324  {
1325  char *argname = (char *) lfirst(lc);
1326  bool found;
1327  int i;
1328 
1329  pp = 0;
1330  found = false;
1331  for (i = 0; i < pronallargs; i++)
1332  {
1333  /* consider only input parameters */
1334  if (p_argmodes &&
1335  (p_argmodes[i] != FUNC_PARAM_IN &&
1336  p_argmodes[i] != FUNC_PARAM_INOUT &&
1337  p_argmodes[i] != FUNC_PARAM_VARIADIC))
1338  continue;
1339  if (p_argnames[i] && strcmp(p_argnames[i], argname) == 0)
1340  {
1341  /* fail if argname matches a positional argument */
1342  if (arggiven[pp])
1343  return false;
1344  arggiven[pp] = true;
1345  (*argnumbers)[ap] = pp;
1346  found = true;
1347  break;
1348  }
1349  /* increase pp only for input parameters */
1350  pp++;
1351  }
1352  /* if name isn't in proargnames, fail */
1353  if (!found)
1354  return false;
1355  ap++;
1356  }
1357 
1358  Assert(ap == nargs); /* processed all actual parameters */
1359 
1360  /* Check for default arguments */
1361  if (nargs < pronargs)
1362  {
1363  int first_arg_with_default = pronargs - procform->pronargdefaults;
1364 
1365  for (pp = numposargs; pp < pronargs; pp++)
1366  {
1367  if (arggiven[pp])
1368  continue;
1369  /* fail if arg not given and no default available */
1370  if (pp < first_arg_with_default)
1371  return false;
1372  (*argnumbers)[ap++] = pp;
1373  }
1374  }
1375 
1376  Assert(ap == pronargs); /* processed all function parameters */
1377 
1378  return true;
1379 }
1380 
1381 /*
1382  * FunctionIsVisible
1383  * Determine whether a function (identified by OID) is visible in the
1384  * current search path. Visible means "would be found by searching
1385  * for the unqualified function name with exact argument matches".
1386  */
1387 bool
1389 {
1390  HeapTuple proctup;
1391  Form_pg_proc procform;
1392  Oid pronamespace;
1393  bool visible;
1394 
1395  proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1396  if (!HeapTupleIsValid(proctup))
1397  elog(ERROR, "cache lookup failed for function %u", funcid);
1398  procform = (Form_pg_proc) GETSTRUCT(proctup);
1399 
1401 
1402  /*
1403  * Quick check: if it ain't in the path at all, it ain't visible. Items in
1404  * the system namespace are surely in the path and so we needn't even do
1405  * list_member_oid() for them.
1406  */
1407  pronamespace = procform->pronamespace;
1408  if (pronamespace != PG_CATALOG_NAMESPACE &&
1409  !list_member_oid(activeSearchPath, pronamespace))
1410  visible = false;
1411  else
1412  {
1413  /*
1414  * If it is in the path, it might still not be visible; it could be
1415  * hidden by another proc of the same name and arguments earlier in
1416  * the path. So we must do a slow check to see if this is the same
1417  * proc that would be found by FuncnameGetCandidates.
1418  */
1419  char *proname = NameStr(procform->proname);
1420  int nargs = procform->pronargs;
1421  FuncCandidateList clist;
1422 
1423  visible = false;
1424 
1425  clist = FuncnameGetCandidates(list_make1(makeString(proname)),
1426  nargs, NIL, false, false, false);
1427 
1428  for (; clist; clist = clist->next)
1429  {
1430  if (memcmp(clist->args, procform->proargtypes.values,
1431  nargs * sizeof(Oid)) == 0)
1432  {
1433  /* Found the expected entry; is it the right proc? */
1434  visible = (clist->oid == funcid);
1435  break;
1436  }
1437  }
1438  }
1439 
1440  ReleaseSysCache(proctup);
1441 
1442  return visible;
1443 }
1444 
1445 
1446 /*
1447  * OpernameGetOprid
1448  * Given a possibly-qualified operator name and exact input datatypes,
1449  * look up the operator. Returns InvalidOid if not found.
1450  *
1451  * Pass oprleft = InvalidOid for a prefix op, oprright = InvalidOid for
1452  * a postfix op.
1453  *
1454  * If the operator name is not schema-qualified, it is sought in the current
1455  * namespace search path. If the name is schema-qualified and the given
1456  * schema does not exist, InvalidOid is returned.
1457  */
1458 Oid
1459 OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
1460 {
1461  char *schemaname;
1462  char *opername;
1463  CatCList *catlist;
1464  ListCell *l;
1465 
1466  /* deconstruct the name list */
1467  DeconstructQualifiedName(names, &schemaname, &opername);
1468 
1469  if (schemaname)
1470  {
1471  /* search only in exact schema given */
1472  Oid namespaceId;
1473 
1474  namespaceId = LookupExplicitNamespace(schemaname, true);
1475  if (OidIsValid(namespaceId))
1476  {
1477  HeapTuple opertup;
1478 
1479  opertup = SearchSysCache4(OPERNAMENSP,
1480  CStringGetDatum(opername),
1481  ObjectIdGetDatum(oprleft),
1482  ObjectIdGetDatum(oprright),
1483  ObjectIdGetDatum(namespaceId));
1484  if (HeapTupleIsValid(opertup))
1485  {
1486  Oid result = HeapTupleGetOid(opertup);
1487 
1488  ReleaseSysCache(opertup);
1489  return result;
1490  }
1491  }
1492 
1493  return InvalidOid;
1494  }
1495 
1496  /* Search syscache by name and argument types */
1497  catlist = SearchSysCacheList3(OPERNAMENSP,
1498  CStringGetDatum(opername),
1499  ObjectIdGetDatum(oprleft),
1500  ObjectIdGetDatum(oprright));
1501 
1502  if (catlist->n_members == 0)
1503  {
1504  /* no hope, fall out early */
1505  ReleaseSysCacheList(catlist);
1506  return InvalidOid;
1507  }
1508 
1509  /*
1510  * We have to find the list member that is first in the search path, if
1511  * there's more than one. This doubly-nested loop looks ugly, but in
1512  * practice there should usually be few catlist members.
1513  */
1515 
1516  foreach(l, activeSearchPath)
1517  {
1518  Oid namespaceId = lfirst_oid(l);
1519  int i;
1520 
1521  if (namespaceId == myTempNamespace)
1522  continue; /* do not look in temp namespace */
1523 
1524  for (i = 0; i < catlist->n_members; i++)
1525  {
1526  HeapTuple opertup = &catlist->members[i]->tuple;
1527  Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1528 
1529  if (operform->oprnamespace == namespaceId)
1530  {
1531  Oid result = HeapTupleGetOid(opertup);
1532 
1533  ReleaseSysCacheList(catlist);
1534  return result;
1535  }
1536  }
1537  }
1538 
1539  ReleaseSysCacheList(catlist);
1540  return InvalidOid;
1541 }
1542 
1543 /*
1544  * OpernameGetCandidates
1545  * Given a possibly-qualified operator name and operator kind,
1546  * retrieve a list of the possible matches.
1547  *
1548  * If oprkind is '\0', we return all operators matching the given name,
1549  * regardless of arguments.
1550  *
1551  * We search a single namespace if the operator name is qualified, else
1552  * all namespaces in the search path. The return list will never contain
1553  * multiple entries with identical argument lists --- in the multiple-
1554  * namespace case, we arrange for entries in earlier namespaces to mask
1555  * identical entries in later namespaces.
1556  *
1557  * The returned items always have two args[] entries --- one or the other
1558  * will be InvalidOid for a prefix or postfix oprkind. nargs is 2, too.
1559  */
1561 OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
1562 {
1563  FuncCandidateList resultList = NULL;
1564  char *resultSpace = NULL;
1565  int nextResult = 0;
1566  char *schemaname;
1567  char *opername;
1568  Oid namespaceId;
1569  CatCList *catlist;
1570  int i;
1571 
1572  /* deconstruct the name list */
1573  DeconstructQualifiedName(names, &schemaname, &opername);
1574 
1575  if (schemaname)
1576  {
1577  /* use exact schema given */
1578  namespaceId = LookupExplicitNamespace(schemaname, missing_schema_ok);
1579  if (missing_schema_ok && !OidIsValid(namespaceId))
1580  return NULL;
1581  }
1582  else
1583  {
1584  /* flag to indicate we need namespace search */
1585  namespaceId = InvalidOid;
1587  }
1588 
1589  /* Search syscache by name only */
1590  catlist = SearchSysCacheList1(OPERNAMENSP, CStringGetDatum(opername));
1591 
1592  /*
1593  * In typical scenarios, most if not all of the operators found by the
1594  * catcache search will end up getting returned; and there can be quite a
1595  * few, for common operator names such as '=' or '+'. To reduce the time
1596  * spent in palloc, we allocate the result space as an array large enough
1597  * to hold all the operators. The original coding of this routine did a
1598  * separate palloc for each operator, but profiling revealed that the
1599  * pallocs used an unreasonably large fraction of parsing time.
1600  */
1601 #define SPACE_PER_OP MAXALIGN(offsetof(struct _FuncCandidateList, args) + \
1602  2 * sizeof(Oid))
1603 
1604  if (catlist->n_members > 0)
1605  resultSpace = palloc(catlist->n_members * SPACE_PER_OP);
1606 
1607  for (i = 0; i < catlist->n_members; i++)
1608  {
1609  HeapTuple opertup = &catlist->members[i]->tuple;
1610  Form_pg_operator operform = (Form_pg_operator) GETSTRUCT(opertup);
1611  int pathpos = 0;
1612  FuncCandidateList newResult;
1613 
1614  /* Ignore operators of wrong kind, if specific kind requested */
1615  if (oprkind && operform->oprkind != oprkind)
1616  continue;
1617 
1618  if (OidIsValid(namespaceId))
1619  {
1620  /* Consider only opers in specified namespace */
1621  if (operform->oprnamespace != namespaceId)
1622  continue;
1623  /* No need to check args, they must all be different */
1624  }
1625  else
1626  {
1627  /*
1628  * Consider only opers that are in the search path and are not in
1629  * the temp namespace.
1630  */
1631  ListCell *nsp;
1632 
1633  foreach(nsp, activeSearchPath)
1634  {
1635  if (operform->oprnamespace == lfirst_oid(nsp) &&
1636  operform->oprnamespace != myTempNamespace)
1637  break;
1638  pathpos++;
1639  }
1640  if (nsp == NULL)
1641  continue; /* oper is not in search path */
1642 
1643  /*
1644  * Okay, it's in the search path, but does it have the same
1645  * arguments as something we already accepted? If so, keep only
1646  * the one that appears earlier in the search path.
1647  *
1648  * If we have an ordered list from SearchSysCacheList (the normal
1649  * case), then any conflicting oper must immediately adjoin this
1650  * one in the list, so we only need to look at the newest result
1651  * item. If we have an unordered list, we have to scan the whole
1652  * result list.
1653  */
1654  if (resultList)
1655  {
1656  FuncCandidateList prevResult;
1657 
1658  if (catlist->ordered)
1659  {
1660  if (operform->oprleft == resultList->args[0] &&
1661  operform->oprright == resultList->args[1])
1662  prevResult = resultList;
1663  else
1664  prevResult = NULL;
1665  }
1666  else
1667  {
1668  for (prevResult = resultList;
1669  prevResult;
1670  prevResult = prevResult->next)
1671  {
1672  if (operform->oprleft == prevResult->args[0] &&
1673  operform->oprright == prevResult->args[1])
1674  break;
1675  }
1676  }
1677  if (prevResult)
1678  {
1679  /* We have a match with a previous result */
1680  Assert(pathpos != prevResult->pathpos);
1681  if (pathpos > prevResult->pathpos)
1682  continue; /* keep previous result */
1683  /* replace previous result */
1684  prevResult->pathpos = pathpos;
1685  prevResult->oid = HeapTupleGetOid(opertup);
1686  continue; /* args are same, of course */
1687  }
1688  }
1689  }
1690 
1691  /*
1692  * Okay to add it to result list
1693  */
1694  newResult = (FuncCandidateList) (resultSpace + nextResult);
1695  nextResult += SPACE_PER_OP;
1696 
1697  newResult->pathpos = pathpos;
1698  newResult->oid = HeapTupleGetOid(opertup);
1699  newResult->nargs = 2;
1700  newResult->nvargs = 0;
1701  newResult->ndargs = 0;
1702  newResult->argnumbers = NULL;
1703  newResult->args[0] = operform->oprleft;
1704  newResult->args[1] = operform->oprright;
1705  newResult->next = resultList;
1706  resultList = newResult;
1707  }
1708 
1709  ReleaseSysCacheList(catlist);
1710 
1711  return resultList;
1712 }
1713 
1714 /*
1715  * OperatorIsVisible
1716  * Determine whether an operator (identified by OID) is visible in the
1717  * current search path. Visible means "would be found by searching
1718  * for the unqualified operator name with exact argument matches".
1719  */
1720 bool
1722 {
1723  HeapTuple oprtup;
1724  Form_pg_operator oprform;
1725  Oid oprnamespace;
1726  bool visible;
1727 
1728  oprtup = SearchSysCache1(OPEROID, ObjectIdGetDatum(oprid));
1729  if (!HeapTupleIsValid(oprtup))
1730  elog(ERROR, "cache lookup failed for operator %u", oprid);
1731  oprform = (Form_pg_operator) GETSTRUCT(oprtup);
1732 
1734 
1735  /*
1736  * Quick check: if it ain't in the path at all, it ain't visible. Items in
1737  * the system namespace are surely in the path and so we needn't even do
1738  * list_member_oid() for them.
1739  */
1740  oprnamespace = oprform->oprnamespace;
1741  if (oprnamespace != PG_CATALOG_NAMESPACE &&
1742  !list_member_oid(activeSearchPath, oprnamespace))
1743  visible = false;
1744  else
1745  {
1746  /*
1747  * If it is in the path, it might still not be visible; it could be
1748  * hidden by another operator of the same name and arguments earlier
1749  * in the path. So we must do a slow check to see if this is the same
1750  * operator that would be found by OpernameGetOprid.
1751  */
1752  char *oprname = NameStr(oprform->oprname);
1753 
1754  visible = (OpernameGetOprid(list_make1(makeString(oprname)),
1755  oprform->oprleft, oprform->oprright)
1756  == oprid);
1757  }
1758 
1759  ReleaseSysCache(oprtup);
1760 
1761  return visible;
1762 }
1763 
1764 
1765 /*
1766  * OpclassnameGetOpcid
1767  * Try to resolve an unqualified index opclass name.
1768  * Returns OID if opclass found in search path, else InvalidOid.
1769  *
1770  * This is essentially the same as TypenameGetTypid, but we have to have
1771  * an extra argument for the index AM OID.
1772  */
1773 Oid
1774 OpclassnameGetOpcid(Oid amid, const char *opcname)
1775 {
1776  Oid opcid;
1777  ListCell *l;
1778 
1780 
1781  foreach(l, activeSearchPath)
1782  {
1783  Oid namespaceId = lfirst_oid(l);
1784 
1785  if (namespaceId == myTempNamespace)
1786  continue; /* do not look in temp namespace */
1787 
1788  opcid = GetSysCacheOid3(CLAAMNAMENSP,
1789  ObjectIdGetDatum(amid),
1790  PointerGetDatum(opcname),
1791  ObjectIdGetDatum(namespaceId));
1792  if (OidIsValid(opcid))
1793  return opcid;
1794  }
1795 
1796  /* Not found in path */
1797  return InvalidOid;
1798 }
1799 
1800 /*
1801  * OpclassIsVisible
1802  * Determine whether an opclass (identified by OID) is visible in the
1803  * current search path. Visible means "would be found by searching
1804  * for the unqualified opclass name".
1805  */
1806 bool
1808 {
1809  HeapTuple opctup;
1810  Form_pg_opclass opcform;
1811  Oid opcnamespace;
1812  bool visible;
1813 
1814  opctup = SearchSysCache1(CLAOID, ObjectIdGetDatum(opcid));
1815  if (!HeapTupleIsValid(opctup))
1816  elog(ERROR, "cache lookup failed for opclass %u", opcid);
1817  opcform = (Form_pg_opclass) GETSTRUCT(opctup);
1818 
1820 
1821  /*
1822  * Quick check: if it ain't in the path at all, it ain't visible. Items in
1823  * the system namespace are surely in the path and so we needn't even do
1824  * list_member_oid() for them.
1825  */
1826  opcnamespace = opcform->opcnamespace;
1827  if (opcnamespace != PG_CATALOG_NAMESPACE &&
1828  !list_member_oid(activeSearchPath, opcnamespace))
1829  visible = false;
1830  else
1831  {
1832  /*
1833  * If it is in the path, it might still not be visible; it could be
1834  * hidden by another opclass of the same name earlier in the path. So
1835  * we must do a slow check to see if this opclass would be found by
1836  * OpclassnameGetOpcid.
1837  */
1838  char *opcname = NameStr(opcform->opcname);
1839 
1840  visible = (OpclassnameGetOpcid(opcform->opcmethod, opcname) == opcid);
1841  }
1842 
1843  ReleaseSysCache(opctup);
1844 
1845  return visible;
1846 }
1847 
1848 /*
1849  * OpfamilynameGetOpfid
1850  * Try to resolve an unqualified index opfamily name.
1851  * Returns OID if opfamily found in search path, else InvalidOid.
1852  *
1853  * This is essentially the same as TypenameGetTypid, but we have to have
1854  * an extra argument for the index AM OID.
1855  */
1856 Oid
1857 OpfamilynameGetOpfid(Oid amid, const char *opfname)
1858 {
1859  Oid opfid;
1860  ListCell *l;
1861 
1863 
1864  foreach(l, activeSearchPath)
1865  {
1866  Oid namespaceId = lfirst_oid(l);
1867 
1868  if (namespaceId == myTempNamespace)
1869  continue; /* do not look in temp namespace */
1870 
1872  ObjectIdGetDatum(amid),
1873  PointerGetDatum(opfname),
1874  ObjectIdGetDatum(namespaceId));
1875  if (OidIsValid(opfid))
1876  return opfid;
1877  }
1878 
1879  /* Not found in path */
1880  return InvalidOid;
1881 }
1882 
1883 /*
1884  * OpfamilyIsVisible
1885  * Determine whether an opfamily (identified by OID) is visible in the
1886  * current search path. Visible means "would be found by searching
1887  * for the unqualified opfamily name".
1888  */
1889 bool
1891 {
1892  HeapTuple opftup;
1893  Form_pg_opfamily opfform;
1894  Oid opfnamespace;
1895  bool visible;
1896 
1897  opftup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1898  if (!HeapTupleIsValid(opftup))
1899  elog(ERROR, "cache lookup failed for opfamily %u", opfid);
1900  opfform = (Form_pg_opfamily) GETSTRUCT(opftup);
1901 
1903 
1904  /*
1905  * Quick check: if it ain't in the path at all, it ain't visible. Items in
1906  * the system namespace are surely in the path and so we needn't even do
1907  * list_member_oid() for them.
1908  */
1909  opfnamespace = opfform->opfnamespace;
1910  if (opfnamespace != PG_CATALOG_NAMESPACE &&
1911  !list_member_oid(activeSearchPath, opfnamespace))
1912  visible = false;
1913  else
1914  {
1915  /*
1916  * If it is in the path, it might still not be visible; it could be
1917  * hidden by another opfamily of the same name earlier in the path. So
1918  * we must do a slow check to see if this opfamily would be found by
1919  * OpfamilynameGetOpfid.
1920  */
1921  char *opfname = NameStr(opfform->opfname);
1922 
1923  visible = (OpfamilynameGetOpfid(opfform->opfmethod, opfname) == opfid);
1924  }
1925 
1926  ReleaseSysCache(opftup);
1927 
1928  return visible;
1929 }
1930 
1931 /*
1932  * CollationGetCollid
1933  * Try to resolve an unqualified collation name.
1934  * Returns OID if collation found in search path, else InvalidOid.
1935  */
1936 Oid
1937 CollationGetCollid(const char *collname)
1938 {
1939  int32 dbencoding = GetDatabaseEncoding();
1940  ListCell *l;
1941 
1943 
1944  foreach(l, activeSearchPath)
1945  {
1946  Oid namespaceId = lfirst_oid(l);
1947  Oid collid;
1948 
1949  if (namespaceId == myTempNamespace)
1950  continue; /* do not look in temp namespace */
1951 
1952  /* Check for database-encoding-specific entry */
1954  PointerGetDatum(collname),
1955  Int32GetDatum(dbencoding),
1956  ObjectIdGetDatum(namespaceId));
1957  if (OidIsValid(collid))
1958  return collid;
1959 
1960  /* Check for any-encoding entry */
1962  PointerGetDatum(collname),
1963  Int32GetDatum(-1),
1964  ObjectIdGetDatum(namespaceId));
1965  if (OidIsValid(collid))
1966  return collid;
1967  }
1968 
1969  /* Not found in path */
1970  return InvalidOid;
1971 }
1972 
1973 /*
1974  * CollationIsVisible
1975  * Determine whether a collation (identified by OID) is visible in the
1976  * current search path. Visible means "would be found by searching
1977  * for the unqualified collation name".
1978  */
1979 bool
1981 {
1982  HeapTuple colltup;
1983  Form_pg_collation collform;
1984  Oid collnamespace;
1985  bool visible;
1986 
1987  colltup = SearchSysCache1(COLLOID, ObjectIdGetDatum(collid));
1988  if (!HeapTupleIsValid(colltup))
1989  elog(ERROR, "cache lookup failed for collation %u", collid);
1990  collform = (Form_pg_collation) GETSTRUCT(colltup);
1991 
1993 
1994  /*
1995  * Quick check: if it ain't in the path at all, it ain't visible. Items in
1996  * the system namespace are surely in the path and so we needn't even do
1997  * list_member_oid() for them.
1998  */
1999  collnamespace = collform->collnamespace;
2000  if (collnamespace != PG_CATALOG_NAMESPACE &&
2001  !list_member_oid(activeSearchPath, collnamespace))
2002  visible = false;
2003  else
2004  {
2005  /*
2006  * If it is in the path, it might still not be visible; it could be
2007  * hidden by another conversion of the same name earlier in the path.
2008  * So we must do a slow check to see if this conversion would be found
2009  * by CollationGetCollid.
2010  */
2011  char *collname = NameStr(collform->collname);
2012 
2013  visible = (CollationGetCollid(collname) == collid);
2014  }
2015 
2016  ReleaseSysCache(colltup);
2017 
2018  return visible;
2019 }
2020 
2021 
2022 /*
2023  * ConversionGetConid
2024  * Try to resolve an unqualified conversion name.
2025  * Returns OID if conversion found in search path, else InvalidOid.
2026  *
2027  * This is essentially the same as RelnameGetRelid.
2028  */
2029 Oid
2030 ConversionGetConid(const char *conname)
2031 {
2032  Oid conid;
2033  ListCell *l;
2034 
2036 
2037  foreach(l, activeSearchPath)
2038  {
2039  Oid namespaceId = lfirst_oid(l);
2040 
2041  if (namespaceId == myTempNamespace)
2042  continue; /* do not look in temp namespace */
2043 
2044  conid = GetSysCacheOid2(CONNAMENSP,
2045  PointerGetDatum(conname),
2046  ObjectIdGetDatum(namespaceId));
2047  if (OidIsValid(conid))
2048  return conid;
2049  }
2050 
2051  /* Not found in path */
2052  return InvalidOid;
2053 }
2054 
2055 /*
2056  * ConversionIsVisible
2057  * Determine whether a conversion (identified by OID) is visible in the
2058  * current search path. Visible means "would be found by searching
2059  * for the unqualified conversion name".
2060  */
2061 bool
2063 {
2064  HeapTuple contup;
2065  Form_pg_conversion conform;
2066  Oid connamespace;
2067  bool visible;
2068 
2069  contup = SearchSysCache1(CONVOID, ObjectIdGetDatum(conid));
2070  if (!HeapTupleIsValid(contup))
2071  elog(ERROR, "cache lookup failed for conversion %u", conid);
2072  conform = (Form_pg_conversion) GETSTRUCT(contup);
2073 
2075 
2076  /*
2077  * Quick check: if it ain't in the path at all, it ain't visible. Items in
2078  * the system namespace are surely in the path and so we needn't even do
2079  * list_member_oid() for them.
2080  */
2081  connamespace = conform->connamespace;
2082  if (connamespace != PG_CATALOG_NAMESPACE &&
2083  !list_member_oid(activeSearchPath, connamespace))
2084  visible = false;
2085  else
2086  {
2087  /*
2088  * If it is in the path, it might still not be visible; it could be
2089  * hidden by another conversion of the same name earlier in the path.
2090  * So we must do a slow check to see if this conversion would be found
2091  * by ConversionGetConid.
2092  */
2093  char *conname = NameStr(conform->conname);
2094 
2095  visible = (ConversionGetConid(conname) == conid);
2096  }
2097 
2098  ReleaseSysCache(contup);
2099 
2100  return visible;
2101 }
2102 
2103 /*
2104  * get_ts_parser_oid - find a TS parser by possibly qualified name
2105  *
2106  * If not found, returns InvalidOid if missing_ok, else throws error
2107  */
2108 Oid
2109 get_ts_parser_oid(List *names, bool missing_ok)
2110 {
2111  char *schemaname;
2112  char *parser_name;
2113  Oid namespaceId;
2114  Oid prsoid = InvalidOid;
2115  ListCell *l;
2116 
2117  /* deconstruct the name list */
2118  DeconstructQualifiedName(names, &schemaname, &parser_name);
2119 
2120  if (schemaname)
2121  {
2122  /* use exact schema given */
2123  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2124  if (missing_ok && !OidIsValid(namespaceId))
2125  prsoid = InvalidOid;
2126  else
2128  PointerGetDatum(parser_name),
2129  ObjectIdGetDatum(namespaceId));
2130  }
2131  else
2132  {
2133  /* search for it in search path */
2135 
2136  foreach(l, activeSearchPath)
2137  {
2138  namespaceId = lfirst_oid(l);
2139 
2140  if (namespaceId == myTempNamespace)
2141  continue; /* do not look in temp namespace */
2142 
2144  PointerGetDatum(parser_name),
2145  ObjectIdGetDatum(namespaceId));
2146  if (OidIsValid(prsoid))
2147  break;
2148  }
2149  }
2150 
2151  if (!OidIsValid(prsoid) && !missing_ok)
2152  ereport(ERROR,
2153  (errcode(ERRCODE_UNDEFINED_OBJECT),
2154  errmsg("text search parser \"%s\" does not exist",
2155  NameListToString(names))));
2156 
2157  return prsoid;
2158 }
2159 
2160 /*
2161  * TSParserIsVisible
2162  * Determine whether a parser (identified by OID) is visible in the
2163  * current search path. Visible means "would be found by searching
2164  * for the unqualified parser name".
2165  */
2166 bool
2168 {
2169  HeapTuple tup;
2170  Form_pg_ts_parser form;
2171  Oid namespace;
2172  bool visible;
2173 
2175  if (!HeapTupleIsValid(tup))
2176  elog(ERROR, "cache lookup failed for text search parser %u", prsId);
2177  form = (Form_pg_ts_parser) GETSTRUCT(tup);
2178 
2180 
2181  /*
2182  * Quick check: if it ain't in the path at all, it ain't visible. Items in
2183  * the system namespace are surely in the path and so we needn't even do
2184  * list_member_oid() for them.
2185  */
2186  namespace = form->prsnamespace;
2187  if (namespace != PG_CATALOG_NAMESPACE &&
2188  !list_member_oid(activeSearchPath, namespace))
2189  visible = false;
2190  else
2191  {
2192  /*
2193  * If it is in the path, it might still not be visible; it could be
2194  * hidden by another parser of the same name earlier in the path. So
2195  * we must do a slow check for conflicting parsers.
2196  */
2197  char *name = NameStr(form->prsname);
2198  ListCell *l;
2199 
2200  visible = false;
2201  foreach(l, activeSearchPath)
2202  {
2203  Oid namespaceId = lfirst_oid(l);
2204 
2205  if (namespaceId == myTempNamespace)
2206  continue; /* do not look in temp namespace */
2207 
2208  if (namespaceId == namespace)
2209  {
2210  /* Found it first in path */
2211  visible = true;
2212  break;
2213  }
2215  PointerGetDatum(name),
2216  ObjectIdGetDatum(namespaceId)))
2217  {
2218  /* Found something else first in path */
2219  break;
2220  }
2221  }
2222  }
2223 
2224  ReleaseSysCache(tup);
2225 
2226  return visible;
2227 }
2228 
2229 /*
2230  * get_ts_dict_oid - find a TS dictionary by possibly qualified name
2231  *
2232  * If not found, returns InvalidOid if failOK, else throws error
2233  */
2234 Oid
2235 get_ts_dict_oid(List *names, bool missing_ok)
2236 {
2237  char *schemaname;
2238  char *dict_name;
2239  Oid namespaceId;
2240  Oid dictoid = InvalidOid;
2241  ListCell *l;
2242 
2243  /* deconstruct the name list */
2244  DeconstructQualifiedName(names, &schemaname, &dict_name);
2245 
2246  if (schemaname)
2247  {
2248  /* use exact schema given */
2249  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2250  if (missing_ok && !OidIsValid(namespaceId))
2251  dictoid = InvalidOid;
2252  else
2253  dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2254  PointerGetDatum(dict_name),
2255  ObjectIdGetDatum(namespaceId));
2256  }
2257  else
2258  {
2259  /* search for it in search path */
2261 
2262  foreach(l, activeSearchPath)
2263  {
2264  namespaceId = lfirst_oid(l);
2265 
2266  if (namespaceId == myTempNamespace)
2267  continue; /* do not look in temp namespace */
2268 
2269  dictoid = GetSysCacheOid2(TSDICTNAMENSP,
2270  PointerGetDatum(dict_name),
2271  ObjectIdGetDatum(namespaceId));
2272  if (OidIsValid(dictoid))
2273  break;
2274  }
2275  }
2276 
2277  if (!OidIsValid(dictoid) && !missing_ok)
2278  ereport(ERROR,
2279  (errcode(ERRCODE_UNDEFINED_OBJECT),
2280  errmsg("text search dictionary \"%s\" does not exist",
2281  NameListToString(names))));
2282 
2283  return dictoid;
2284 }
2285 
2286 /*
2287  * TSDictionaryIsVisible
2288  * Determine whether a dictionary (identified by OID) is visible in the
2289  * current search path. Visible means "would be found by searching
2290  * for the unqualified dictionary name".
2291  */
2292 bool
2294 {
2295  HeapTuple tup;
2296  Form_pg_ts_dict form;
2297  Oid namespace;
2298  bool visible;
2299 
2300  tup = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dictId));
2301  if (!HeapTupleIsValid(tup))
2302  elog(ERROR, "cache lookup failed for text search dictionary %u",
2303  dictId);
2304  form = (Form_pg_ts_dict) GETSTRUCT(tup);
2305 
2307 
2308  /*
2309  * Quick check: if it ain't in the path at all, it ain't visible. Items in
2310  * the system namespace are surely in the path and so we needn't even do
2311  * list_member_oid() for them.
2312  */
2313  namespace = form->dictnamespace;
2314  if (namespace != PG_CATALOG_NAMESPACE &&
2315  !list_member_oid(activeSearchPath, namespace))
2316  visible = false;
2317  else
2318  {
2319  /*
2320  * If it is in the path, it might still not be visible; it could be
2321  * hidden by another dictionary of the same name earlier in the path.
2322  * So we must do a slow check for conflicting dictionaries.
2323  */
2324  char *name = NameStr(form->dictname);
2325  ListCell *l;
2326 
2327  visible = false;
2328  foreach(l, activeSearchPath)
2329  {
2330  Oid namespaceId = lfirst_oid(l);
2331 
2332  if (namespaceId == myTempNamespace)
2333  continue; /* do not look in temp namespace */
2334 
2335  if (namespaceId == namespace)
2336  {
2337  /* Found it first in path */
2338  visible = true;
2339  break;
2340  }
2342  PointerGetDatum(name),
2343  ObjectIdGetDatum(namespaceId)))
2344  {
2345  /* Found something else first in path */
2346  break;
2347  }
2348  }
2349  }
2350 
2351  ReleaseSysCache(tup);
2352 
2353  return visible;
2354 }
2355 
2356 /*
2357  * get_ts_template_oid - find a TS template by possibly qualified name
2358  *
2359  * If not found, returns InvalidOid if missing_ok, else throws error
2360  */
2361 Oid
2362 get_ts_template_oid(List *names, bool missing_ok)
2363 {
2364  char *schemaname;
2365  char *template_name;
2366  Oid namespaceId;
2367  Oid tmploid = InvalidOid;
2368  ListCell *l;
2369 
2370  /* deconstruct the name list */
2371  DeconstructQualifiedName(names, &schemaname, &template_name);
2372 
2373  if (schemaname)
2374  {
2375  /* use exact schema given */
2376  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2377  if (missing_ok && !OidIsValid(namespaceId))
2378  tmploid = InvalidOid;
2379  else
2381  PointerGetDatum(template_name),
2382  ObjectIdGetDatum(namespaceId));
2383  }
2384  else
2385  {
2386  /* search for it in search path */
2388 
2389  foreach(l, activeSearchPath)
2390  {
2391  namespaceId = lfirst_oid(l);
2392 
2393  if (namespaceId == myTempNamespace)
2394  continue; /* do not look in temp namespace */
2395 
2397  PointerGetDatum(template_name),
2398  ObjectIdGetDatum(namespaceId));
2399  if (OidIsValid(tmploid))
2400  break;
2401  }
2402  }
2403 
2404  if (!OidIsValid(tmploid) && !missing_ok)
2405  ereport(ERROR,
2406  (errcode(ERRCODE_UNDEFINED_OBJECT),
2407  errmsg("text search template \"%s\" does not exist",
2408  NameListToString(names))));
2409 
2410  return tmploid;
2411 }
2412 
2413 /*
2414  * TSTemplateIsVisible
2415  * Determine whether a template (identified by OID) is visible in the
2416  * current search path. Visible means "would be found by searching
2417  * for the unqualified template name".
2418  */
2419 bool
2421 {
2422  HeapTuple tup;
2423  Form_pg_ts_template form;
2424  Oid namespace;
2425  bool visible;
2426 
2428  if (!HeapTupleIsValid(tup))
2429  elog(ERROR, "cache lookup failed for text search template %u", tmplId);
2430  form = (Form_pg_ts_template) GETSTRUCT(tup);
2431 
2433 
2434  /*
2435  * Quick check: if it ain't in the path at all, it ain't visible. Items in
2436  * the system namespace are surely in the path and so we needn't even do
2437  * list_member_oid() for them.
2438  */
2439  namespace = form->tmplnamespace;
2440  if (namespace != PG_CATALOG_NAMESPACE &&
2441  !list_member_oid(activeSearchPath, namespace))
2442  visible = false;
2443  else
2444  {
2445  /*
2446  * If it is in the path, it might still not be visible; it could be
2447  * hidden by another template of the same name earlier in the path. So
2448  * we must do a slow check for conflicting templates.
2449  */
2450  char *name = NameStr(form->tmplname);
2451  ListCell *l;
2452 
2453  visible = false;
2454  foreach(l, activeSearchPath)
2455  {
2456  Oid namespaceId = lfirst_oid(l);
2457 
2458  if (namespaceId == myTempNamespace)
2459  continue; /* do not look in temp namespace */
2460 
2461  if (namespaceId == namespace)
2462  {
2463  /* Found it first in path */
2464  visible = true;
2465  break;
2466  }
2468  PointerGetDatum(name),
2469  ObjectIdGetDatum(namespaceId)))
2470  {
2471  /* Found something else first in path */
2472  break;
2473  }
2474  }
2475  }
2476 
2477  ReleaseSysCache(tup);
2478 
2479  return visible;
2480 }
2481 
2482 /*
2483  * get_ts_config_oid - find a TS config by possibly qualified name
2484  *
2485  * If not found, returns InvalidOid if missing_ok, else throws error
2486  */
2487 Oid
2488 get_ts_config_oid(List *names, bool missing_ok)
2489 {
2490  char *schemaname;
2491  char *config_name;
2492  Oid namespaceId;
2493  Oid cfgoid = InvalidOid;
2494  ListCell *l;
2495 
2496  /* deconstruct the name list */
2497  DeconstructQualifiedName(names, &schemaname, &config_name);
2498 
2499  if (schemaname)
2500  {
2501  /* use exact schema given */
2502  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
2503  if (missing_ok && !OidIsValid(namespaceId))
2504  cfgoid = InvalidOid;
2505  else
2507  PointerGetDatum(config_name),
2508  ObjectIdGetDatum(namespaceId));
2509  }
2510  else
2511  {
2512  /* search for it in search path */
2514 
2515  foreach(l, activeSearchPath)
2516  {
2517  namespaceId = lfirst_oid(l);
2518 
2519  if (namespaceId == myTempNamespace)
2520  continue; /* do not look in temp namespace */
2521 
2523  PointerGetDatum(config_name),
2524  ObjectIdGetDatum(namespaceId));
2525  if (OidIsValid(cfgoid))
2526  break;
2527  }
2528  }
2529 
2530  if (!OidIsValid(cfgoid) && !missing_ok)
2531  ereport(ERROR,
2532  (errcode(ERRCODE_UNDEFINED_OBJECT),
2533  errmsg("text search configuration \"%s\" does not exist",
2534  NameListToString(names))));
2535 
2536  return cfgoid;
2537 }
2538 
2539 /*
2540  * TSConfigIsVisible
2541  * Determine whether a text search configuration (identified by OID)
2542  * is visible in the current search path. Visible means "would be found
2543  * by searching for the unqualified text search configuration name".
2544  */
2545 bool
2547 {
2548  HeapTuple tup;
2549  Form_pg_ts_config form;
2550  Oid namespace;
2551  bool visible;
2552 
2554  if (!HeapTupleIsValid(tup))
2555  elog(ERROR, "cache lookup failed for text search configuration %u",
2556  cfgid);
2557  form = (Form_pg_ts_config) GETSTRUCT(tup);
2558 
2560 
2561  /*
2562  * Quick check: if it ain't in the path at all, it ain't visible. Items in
2563  * the system namespace are surely in the path and so we needn't even do
2564  * list_member_oid() for them.
2565  */
2566  namespace = form->cfgnamespace;
2567  if (namespace != PG_CATALOG_NAMESPACE &&
2568  !list_member_oid(activeSearchPath, namespace))
2569  visible = false;
2570  else
2571  {
2572  /*
2573  * If it is in the path, it might still not be visible; it could be
2574  * hidden by another configuration of the same name earlier in the
2575  * path. So we must do a slow check for conflicting configurations.
2576  */
2577  char *name = NameStr(form->cfgname);
2578  ListCell *l;
2579 
2580  visible = false;
2581  foreach(l, activeSearchPath)
2582  {
2583  Oid namespaceId = lfirst_oid(l);
2584 
2585  if (namespaceId == myTempNamespace)
2586  continue; /* do not look in temp namespace */
2587 
2588  if (namespaceId == namespace)
2589  {
2590  /* Found it first in path */
2591  visible = true;
2592  break;
2593  }
2595  PointerGetDatum(name),
2596  ObjectIdGetDatum(namespaceId)))
2597  {
2598  /* Found something else first in path */
2599  break;
2600  }
2601  }
2602  }
2603 
2604  ReleaseSysCache(tup);
2605 
2606  return visible;
2607 }
2608 
2609 
2610 /*
2611  * DeconstructQualifiedName
2612  * Given a possibly-qualified name expressed as a list of String nodes,
2613  * extract the schema name and object name.
2614  *
2615  * *nspname_p is set to NULL if there is no explicit schema name.
2616  */
2617 void
2619  char **nspname_p,
2620  char **objname_p)
2621 {
2622  char *catalogname;
2623  char *schemaname = NULL;
2624  char *objname = NULL;
2625 
2626  switch (list_length(names))
2627  {
2628  case 1:
2629  objname = strVal(linitial(names));
2630  break;
2631  case 2:
2632  schemaname = strVal(linitial(names));
2633  objname = strVal(lsecond(names));
2634  break;
2635  case 3:
2636  catalogname = strVal(linitial(names));
2637  schemaname = strVal(lsecond(names));
2638  objname = strVal(lthird(names));
2639 
2640  /*
2641  * We check the catalog name and then ignore it.
2642  */
2643  if (strcmp(catalogname, get_database_name(MyDatabaseId)) != 0)
2644  ereport(ERROR,
2645  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2646  errmsg("cross-database references are not implemented: %s",
2647  NameListToString(names))));
2648  break;
2649  default:
2650  ereport(ERROR,
2651  (errcode(ERRCODE_SYNTAX_ERROR),
2652  errmsg("improper qualified name (too many dotted names): %s",
2653  NameListToString(names))));
2654  break;
2655  }
2656 
2657  *nspname_p = schemaname;
2658  *objname_p = objname;
2659 }
2660 
2661 /*
2662  * LookupNamespaceNoError
2663  * Look up a schema name.
2664  *
2665  * Returns the namespace OID, or InvalidOid if not found.
2666  *
2667  * Note this does NOT perform any permissions check --- callers are
2668  * responsible for being sure that an appropriate check is made.
2669  * In the majority of cases LookupExplicitNamespace is preferable.
2670  */
2671 Oid
2672 LookupNamespaceNoError(const char *nspname)
2673 {
2674  /* check for pg_temp alias */
2675  if (strcmp(nspname, "pg_temp") == 0)
2676  {
2678  {
2680  return myTempNamespace;
2681  }
2682 
2683  /*
2684  * Since this is used only for looking up existing objects, there is
2685  * no point in trying to initialize the temp namespace here; and doing
2686  * so might create problems for some callers. Just report "not found".
2687  */
2688  return InvalidOid;
2689  }
2690 
2691  return get_namespace_oid(nspname, true);
2692 }
2693 
2694 /*
2695  * LookupExplicitNamespace
2696  * Process an explicitly-specified schema name: look up the schema
2697  * and verify we have USAGE (lookup) rights in it.
2698  *
2699  * Returns the namespace OID
2700  */
2701 Oid
2702 LookupExplicitNamespace(const char *nspname, bool missing_ok)
2703 {
2704  Oid namespaceId;
2705  AclResult aclresult;
2706 
2707  /* check for pg_temp alias */
2708  if (strcmp(nspname, "pg_temp") == 0)
2709  {
2711  return myTempNamespace;
2712 
2713  /*
2714  * Since this is used only for looking up existing objects, there is
2715  * no point in trying to initialize the temp namespace here; and doing
2716  * so might create problems for some callers --- just fall through.
2717  */
2718  }
2719 
2720  namespaceId = get_namespace_oid(nspname, missing_ok);
2721  if (missing_ok && !OidIsValid(namespaceId))
2722  return InvalidOid;
2723 
2724  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_USAGE);
2725  if (aclresult != ACLCHECK_OK)
2727  nspname);
2728  /* Schema search hook for this lookup */
2729  InvokeNamespaceSearchHook(namespaceId, true);
2730 
2731  return namespaceId;
2732 }
2733 
2734 /*
2735  * LookupCreationNamespace
2736  * Look up the schema and verify we have CREATE rights on it.
2737  *
2738  * This is just like LookupExplicitNamespace except for the different
2739  * permission check, and that we are willing to create pg_temp if needed.
2740  *
2741  * Note: calling this may result in a CommandCounterIncrement operation,
2742  * if we have to create or clean out the temp namespace.
2743  */
2744 Oid
2745 LookupCreationNamespace(const char *nspname)
2746 {
2747  Oid namespaceId;
2748  AclResult aclresult;
2749 
2750  /* check for pg_temp alias */
2751  if (strcmp(nspname, "pg_temp") == 0)
2752  {
2753  /* Initialize temp namespace if first time through */
2756  return myTempNamespace;
2757  }
2758 
2759  namespaceId = get_namespace_oid(nspname, false);
2760 
2761  aclresult = pg_namespace_aclcheck(namespaceId, GetUserId(), ACL_CREATE);
2762  if (aclresult != ACLCHECK_OK)
2764  nspname);
2765 
2766  return namespaceId;
2767 }
2768 
2769 /*
2770  * Common checks on switching namespaces.
2771  *
2772  * We complain if either the old or new namespaces is a temporary schema
2773  * (or temporary toast schema), or if either the old or new namespaces is the
2774  * TOAST schema.
2775  */
2776 void
2777 CheckSetNamespace(Oid oldNspOid, Oid nspOid)
2778 {
2779  /* disallow renaming into or out of temp schemas */
2780  if (isAnyTempNamespace(nspOid) || isAnyTempNamespace(oldNspOid))
2781  ereport(ERROR,
2782  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2783  errmsg("cannot move objects into or out of temporary schemas")));
2784 
2785  /* same for TOAST schema */
2786  if (nspOid == PG_TOAST_NAMESPACE || oldNspOid == PG_TOAST_NAMESPACE)
2787  ereport(ERROR,
2788  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2789  errmsg("cannot move objects into or out of TOAST schema")));
2790 }
2791 
2792 /*
2793  * QualifiedNameGetCreationNamespace
2794  * Given a possibly-qualified name for an object (in List-of-Values
2795  * format), determine what namespace the object should be created in.
2796  * Also extract and return the object name (last component of list).
2797  *
2798  * Note: this does not apply any permissions check. Callers must check
2799  * for CREATE rights on the selected namespace when appropriate.
2800  *
2801  * Note: calling this may result in a CommandCounterIncrement operation,
2802  * if we have to create or clean out the temp namespace.
2803  */
2804 Oid
2805 QualifiedNameGetCreationNamespace(List *names, char **objname_p)
2806 {
2807  char *schemaname;
2808  Oid namespaceId;
2809 
2810  /* deconstruct the name list */
2811  DeconstructQualifiedName(names, &schemaname, objname_p);
2812 
2813  if (schemaname)
2814  {
2815  /* check for pg_temp alias */
2816  if (strcmp(schemaname, "pg_temp") == 0)
2817  {
2818  /* Initialize temp namespace if first time through */
2821  return myTempNamespace;
2822  }
2823  /* use exact schema given */
2824  namespaceId = get_namespace_oid(schemaname, false);
2825  /* we do not check for USAGE rights here! */
2826  }
2827  else
2828  {
2829  /* use the default creation namespace */
2832  {
2833  /* Need to initialize temp namespace */
2835  return myTempNamespace;
2836  }
2837  namespaceId = activeCreationNamespace;
2838  if (!OidIsValid(namespaceId))
2839  ereport(ERROR,
2840  (errcode(ERRCODE_UNDEFINED_SCHEMA),
2841  errmsg("no schema has been selected to create in")));
2842  }
2843 
2844  return namespaceId;
2845 }
2846 
2847 /*
2848  * get_namespace_oid - given a namespace name, look up the OID
2849  *
2850  * If missing_ok is false, throw an error if namespace name not found. If
2851  * true, just return InvalidOid.
2852  */
2853 Oid
2854 get_namespace_oid(const char *nspname, bool missing_ok)
2855 {
2856  Oid oid;
2857 
2859  if (!OidIsValid(oid) && !missing_ok)
2860  ereport(ERROR,
2861  (errcode(ERRCODE_UNDEFINED_SCHEMA),
2862  errmsg("schema \"%s\" does not exist", nspname)));
2863 
2864  return oid;
2865 }
2866 
2867 /*
2868  * makeRangeVarFromNameList
2869  * Utility routine to convert a qualified-name list into RangeVar form.
2870  */
2871 RangeVar *
2873 {
2874  RangeVar *rel = makeRangeVar(NULL, NULL, -1);
2875 
2876  switch (list_length(names))
2877  {
2878  case 1:
2879  rel->relname = strVal(linitial(names));
2880  break;
2881  case 2:
2882  rel->schemaname = strVal(linitial(names));
2883  rel->relname = strVal(lsecond(names));
2884  break;
2885  case 3:
2886  rel->catalogname = strVal(linitial(names));
2887  rel->schemaname = strVal(lsecond(names));
2888  rel->relname = strVal(lthird(names));
2889  break;
2890  default:
2891  ereport(ERROR,
2892  (errcode(ERRCODE_SYNTAX_ERROR),
2893  errmsg("improper relation name (too many dotted names): %s",
2894  NameListToString(names))));
2895  break;
2896  }
2897 
2898  return rel;
2899 }
2900 
2901 /*
2902  * NameListToString
2903  * Utility routine to convert a qualified-name list into a string.
2904  *
2905  * This is used primarily to form error messages, and so we do not quote
2906  * the list elements, for the sake of legibility.
2907  *
2908  * In most scenarios the list elements should always be Value strings,
2909  * but we also allow A_Star for the convenience of ColumnRef processing.
2910  */
2911 char *
2913 {
2915  ListCell *l;
2916 
2917  initStringInfo(&string);
2918 
2919  foreach(l, names)
2920  {
2921  Node *name = (Node *) lfirst(l);
2922 
2923  if (l != list_head(names))
2924  appendStringInfoChar(&string, '.');
2925 
2926  if (IsA(name, String))
2927  appendStringInfoString(&string, strVal(name));
2928  else if (IsA(name, A_Star))
2929  appendStringInfoChar(&string, '*');
2930  else
2931  elog(ERROR, "unexpected node type in name list: %d",
2932  (int) nodeTag(name));
2933  }
2934 
2935  return string.data;
2936 }
2937 
2938 /*
2939  * NameListToQuotedString
2940  * Utility routine to convert a qualified-name list into a string.
2941  *
2942  * Same as above except that names will be double-quoted where necessary,
2943  * so the string could be re-parsed (eg, by textToQualifiedNameList).
2944  */
2945 char *
2947 {
2949  ListCell *l;
2950 
2951  initStringInfo(&string);
2952 
2953  foreach(l, names)
2954  {
2955  if (l != list_head(names))
2956  appendStringInfoChar(&string, '.');
2958  }
2959 
2960  return string.data;
2961 }
2962 
2963 /*
2964  * isTempNamespace - is the given namespace my temporary-table namespace?
2965  */
2966 bool
2967 isTempNamespace(Oid namespaceId)
2968 {
2969  if (OidIsValid(myTempNamespace) && myTempNamespace == namespaceId)
2970  return true;
2971  return false;
2972 }
2973 
2974 /*
2975  * isTempToastNamespace - is the given namespace my temporary-toast-table
2976  * namespace?
2977  */
2978 bool
2980 {
2981  if (OidIsValid(myTempToastNamespace) && myTempToastNamespace == namespaceId)
2982  return true;
2983  return false;
2984 }
2985 
2986 /*
2987  * isTempOrTempToastNamespace - is the given namespace my temporary-table
2988  * namespace or my temporary-toast-table namespace?
2989  */
2990 bool
2992 {
2993  if (OidIsValid(myTempNamespace) &&
2994  (myTempNamespace == namespaceId || myTempToastNamespace == namespaceId))
2995  return true;
2996  return false;
2997 }
2998 
2999 /*
3000  * isAnyTempNamespace - is the given namespace a temporary-table namespace
3001  * (either my own, or another backend's)? Temporary-toast-table namespaces
3002  * are included, too.
3003  */
3004 bool
3006 {
3007  bool result;
3008  char *nspname;
3009 
3010  /* True if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3011  nspname = get_namespace_name(namespaceId);
3012  if (!nspname)
3013  return false; /* no such namespace? */
3014  result = (strncmp(nspname, "pg_temp_", 8) == 0) ||
3015  (strncmp(nspname, "pg_toast_temp_", 14) == 0);
3016  pfree(nspname);
3017  return result;
3018 }
3019 
3020 /*
3021  * isOtherTempNamespace - is the given namespace some other backend's
3022  * temporary-table namespace (including temporary-toast-table namespaces)?
3023  *
3024  * Note: for most purposes in the C code, this function is obsolete. Use
3025  * RELATION_IS_OTHER_TEMP() instead to detect non-local temp relations.
3026  */
3027 bool
3029 {
3030  /* If it's my own temp namespace, say "false" */
3031  if (isTempOrTempToastNamespace(namespaceId))
3032  return false;
3033  /* Else, if it's any temp namespace, say "true" */
3034  return isAnyTempNamespace(namespaceId);
3035 }
3036 
3037 /*
3038  * GetTempNamespaceBackendId - if the given namespace is a temporary-table
3039  * namespace (either my own, or another backend's), return the BackendId
3040  * that owns it. Temporary-toast-table namespaces are included, too.
3041  * If it isn't a temp namespace, return InvalidBackendId.
3042  */
3043 int
3045 {
3046  int result;
3047  char *nspname;
3048 
3049  /* See if the namespace name starts with "pg_temp_" or "pg_toast_temp_" */
3050  nspname = get_namespace_name(namespaceId);
3051  if (!nspname)
3052  return InvalidBackendId; /* no such namespace? */
3053  if (strncmp(nspname, "pg_temp_", 8) == 0)
3054  result = atoi(nspname + 8);
3055  else if (strncmp(nspname, "pg_toast_temp_", 14) == 0)
3056  result = atoi(nspname + 14);
3057  else
3058  result = InvalidBackendId;
3059  pfree(nspname);
3060  return result;
3061 }
3062 
3063 /*
3064  * GetTempToastNamespace - get the OID of my temporary-toast-table namespace,
3065  * which must already be assigned. (This is only used when creating a toast
3066  * table for a temp table, so we must have already done InitTempTableNamespace)
3067  */
3068 Oid
3070 {
3072  return myTempToastNamespace;
3073 }
3074 
3075 
3076 /*
3077  * GetOverrideSearchPath - fetch current search path definition in form
3078  * used by PushOverrideSearchPath.
3079  *
3080  * The result structure is allocated in the specified memory context
3081  * (which might or might not be equal to CurrentMemoryContext); but any
3082  * junk created by revalidation calculations will be in CurrentMemoryContext.
3083  */
3086 {
3087  OverrideSearchPath *result;
3088  List *schemas;
3089  MemoryContext oldcxt;
3090 
3092 
3093  oldcxt = MemoryContextSwitchTo(context);
3094 
3095  result = (OverrideSearchPath *) palloc0(sizeof(OverrideSearchPath));
3096  schemas = list_copy(activeSearchPath);
3097  while (schemas && linitial_oid(schemas) != activeCreationNamespace)
3098  {
3099  if (linitial_oid(schemas) == myTempNamespace)
3100  result->addTemp = true;
3101  else
3102  {
3104  result->addCatalog = true;
3105  }
3106  schemas = list_delete_first(schemas);
3107  }
3108  result->schemas = schemas;
3109 
3110  MemoryContextSwitchTo(oldcxt);
3111 
3112  return result;
3113 }
3114 
3115 /*
3116  * CopyOverrideSearchPath - copy the specified OverrideSearchPath.
3117  *
3118  * The result structure is allocated in CurrentMemoryContext.
3119  */
3122 {
3123  OverrideSearchPath *result;
3124 
3125  result = (OverrideSearchPath *) palloc(sizeof(OverrideSearchPath));
3126  result->schemas = list_copy(path->schemas);
3127  result->addCatalog = path->addCatalog;
3128  result->addTemp = path->addTemp;
3129 
3130  return result;
3131 }
3132 
3133 /*
3134  * OverrideSearchPathMatchesCurrent - does path match current setting?
3135  */
3136 bool
3138 {
3139  ListCell *lc,
3140  *lcp;
3141 
3143 
3144  /* We scan down the activeSearchPath to see if it matches the input. */
3145  lc = list_head(activeSearchPath);
3146 
3147  /* If path->addTemp, first item should be my temp namespace. */
3148  if (path->addTemp)
3149  {
3150  if (lc && lfirst_oid(lc) == myTempNamespace)
3151  lc = lnext(lc);
3152  else
3153  return false;
3154  }
3155  /* If path->addCatalog, next item should be pg_catalog. */
3156  if (path->addCatalog)
3157  {
3158  if (lc && lfirst_oid(lc) == PG_CATALOG_NAMESPACE)
3159  lc = lnext(lc);
3160  else
3161  return false;
3162  }
3163  /* We should now be looking at the activeCreationNamespace. */
3164  if (activeCreationNamespace != (lc ? lfirst_oid(lc) : InvalidOid))
3165  return false;
3166  /* The remainder of activeSearchPath should match path->schemas. */
3167  foreach(lcp, path->schemas)
3168  {
3169  if (lc && lfirst_oid(lc) == lfirst_oid(lcp))
3170  lc = lnext(lc);
3171  else
3172  return false;
3173  }
3174  if (lc)
3175  return false;
3176  return true;
3177 }
3178 
3179 /*
3180  * PushOverrideSearchPath - temporarily override the search path
3181  *
3182  * We allow nested overrides, hence the push/pop terminology. The GUC
3183  * search_path variable is ignored while an override is active.
3184  *
3185  * It's possible that newpath->useTemp is set but there is no longer any
3186  * active temp namespace, if the path was saved during a transaction that
3187  * created a temp namespace and was later rolled back. In that case we just
3188  * ignore useTemp. A plausible alternative would be to create a new temp
3189  * namespace, but for existing callers that's not necessary because an empty
3190  * temp namespace wouldn't affect their results anyway.
3191  *
3192  * It's also worth noting that other schemas listed in newpath might not
3193  * exist anymore either. We don't worry about this because OIDs that match
3194  * no existing namespace will simply not produce any hits during searches.
3195  */
3196 void
3198 {
3199  OverrideStackEntry *entry;
3200  List *oidlist;
3201  Oid firstNS;
3202  MemoryContext oldcxt;
3203 
3204  /*
3205  * Copy the list for safekeeping, and insert implicitly-searched
3206  * namespaces as needed. This code should track recomputeNamespacePath.
3207  */
3209 
3210  oidlist = list_copy(newpath->schemas);
3211 
3212  /*
3213  * Remember the first member of the explicit list.
3214  */
3215  if (oidlist == NIL)
3216  firstNS = InvalidOid;
3217  else
3218  firstNS = linitial_oid(oidlist);
3219 
3220  /*
3221  * Add any implicitly-searched namespaces to the list. Note these go on
3222  * the front, not the back; also notice that we do not check USAGE
3223  * permissions for these.
3224  */
3225  if (newpath->addCatalog)
3226  oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3227 
3228  if (newpath->addTemp && OidIsValid(myTempNamespace))
3229  oidlist = lcons_oid(myTempNamespace, oidlist);
3230 
3231  /*
3232  * Build the new stack entry, then insert it at the head of the list.
3233  */
3234  entry = (OverrideStackEntry *) palloc(sizeof(OverrideStackEntry));
3235  entry->searchPath = oidlist;
3236  entry->creationNamespace = firstNS;
3238 
3239  overrideStack = lcons(entry, overrideStack);
3240 
3241  /* And make it active. */
3242  activeSearchPath = entry->searchPath;
3244  activeTempCreationPending = false; /* XXX is this OK? */
3245 
3246  MemoryContextSwitchTo(oldcxt);
3247 }
3248 
3249 /*
3250  * PopOverrideSearchPath - undo a previous PushOverrideSearchPath
3251  *
3252  * Any push during a (sub)transaction will be popped automatically at abort.
3253  * But it's caller error if a push isn't popped in normal control flow.
3254  */
3255 void
3257 {
3258  OverrideStackEntry *entry;
3259 
3260  /* Sanity checks. */
3261  if (overrideStack == NIL)
3262  elog(ERROR, "bogus PopOverrideSearchPath call");
3263  entry = (OverrideStackEntry *) linitial(overrideStack);
3264  if (entry->nestLevel != GetCurrentTransactionNestLevel())
3265  elog(ERROR, "bogus PopOverrideSearchPath call");
3266 
3267  /* Pop the stack and free storage. */
3268  overrideStack = list_delete_first(overrideStack);
3269  list_free(entry->searchPath);
3270  pfree(entry);
3271 
3272  /* Activate the next level down. */
3273  if (overrideStack)
3274  {
3275  entry = (OverrideStackEntry *) linitial(overrideStack);
3276  activeSearchPath = entry->searchPath;
3278  activeTempCreationPending = false; /* XXX is this OK? */
3279  }
3280  else
3281  {
3282  /* If not baseSearchPathValid, this is useless but harmless */
3283  activeSearchPath = baseSearchPath;
3286  }
3287 }
3288 
3289 
3290 /*
3291  * get_collation_oid - find a collation by possibly qualified name
3292  */
3293 Oid
3294 get_collation_oid(List *name, bool missing_ok)
3295 {
3296  char *schemaname;
3297  char *collation_name;
3298  int32 dbencoding = GetDatabaseEncoding();
3299  Oid namespaceId;
3300  Oid colloid;
3301  ListCell *l;
3302 
3303  /* deconstruct the name list */
3304  DeconstructQualifiedName(name, &schemaname, &collation_name);
3305 
3306  if (schemaname)
3307  {
3308  /* use exact schema given */
3309  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3310  if (missing_ok && !OidIsValid(namespaceId))
3311  return InvalidOid;
3312 
3313  /* first try for encoding-specific entry, then any-encoding */
3314  colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3315  PointerGetDatum(collation_name),
3316  Int32GetDatum(dbencoding),
3317  ObjectIdGetDatum(namespaceId));
3318  if (OidIsValid(colloid))
3319  return colloid;
3320  colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3321  PointerGetDatum(collation_name),
3322  Int32GetDatum(-1),
3323  ObjectIdGetDatum(namespaceId));
3324  if (OidIsValid(colloid))
3325  return colloid;
3326  }
3327  else
3328  {
3329  /* search for it in search path */
3331 
3332  foreach(l, activeSearchPath)
3333  {
3334  namespaceId = lfirst_oid(l);
3335 
3336  if (namespaceId == myTempNamespace)
3337  continue; /* do not look in temp namespace */
3338 
3339  colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3340  PointerGetDatum(collation_name),
3341  Int32GetDatum(dbencoding),
3342  ObjectIdGetDatum(namespaceId));
3343  if (OidIsValid(colloid))
3344  return colloid;
3345  colloid = GetSysCacheOid3(COLLNAMEENCNSP,
3346  PointerGetDatum(collation_name),
3347  Int32GetDatum(-1),
3348  ObjectIdGetDatum(namespaceId));
3349  if (OidIsValid(colloid))
3350  return colloid;
3351  }
3352  }
3353 
3354  /* Not found in path */
3355  if (!missing_ok)
3356  ereport(ERROR,
3357  (errcode(ERRCODE_UNDEFINED_OBJECT),
3358  errmsg("collation \"%s\" for encoding \"%s\" does not exist",
3360  return InvalidOid;
3361 }
3362 
3363 /*
3364  * get_conversion_oid - find a conversion by possibly qualified name
3365  */
3366 Oid
3367 get_conversion_oid(List *name, bool missing_ok)
3368 {
3369  char *schemaname;
3370  char *conversion_name;
3371  Oid namespaceId;
3372  Oid conoid = InvalidOid;
3373  ListCell *l;
3374 
3375  /* deconstruct the name list */
3376  DeconstructQualifiedName(name, &schemaname, &conversion_name);
3377 
3378  if (schemaname)
3379  {
3380  /* use exact schema given */
3381  namespaceId = LookupExplicitNamespace(schemaname, missing_ok);
3382  if (missing_ok && !OidIsValid(namespaceId))
3383  conoid = InvalidOid;
3384  else
3385  conoid = GetSysCacheOid2(CONNAMENSP,
3386  PointerGetDatum(conversion_name),
3387  ObjectIdGetDatum(namespaceId));
3388  }
3389  else
3390  {
3391  /* search for it in search path */
3393 
3394  foreach(l, activeSearchPath)
3395  {
3396  namespaceId = lfirst_oid(l);
3397 
3398  if (namespaceId == myTempNamespace)
3399  continue; /* do not look in temp namespace */
3400 
3401  conoid = GetSysCacheOid2(CONNAMENSP,
3402  PointerGetDatum(conversion_name),
3403  ObjectIdGetDatum(namespaceId));
3404  if (OidIsValid(conoid))
3405  return conoid;
3406  }
3407  }
3408 
3409  /* Not found in path */
3410  if (!OidIsValid(conoid) && !missing_ok)
3411  ereport(ERROR,
3412  (errcode(ERRCODE_UNDEFINED_OBJECT),
3413  errmsg("conversion \"%s\" does not exist",
3414  NameListToString(name))));
3415  return conoid;
3416 }
3417 
3418 /*
3419  * FindDefaultConversionProc - find default encoding conversion proc
3420  */
3421 Oid
3422 FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
3423 {
3424  Oid proc;
3425  ListCell *l;
3426 
3428 
3429  foreach(l, activeSearchPath)
3430  {
3431  Oid namespaceId = lfirst_oid(l);
3432 
3433  if (namespaceId == myTempNamespace)
3434  continue; /* do not look in temp namespace */
3435 
3436  proc = FindDefaultConversion(namespaceId, for_encoding, to_encoding);
3437  if (OidIsValid(proc))
3438  return proc;
3439  }
3440 
3441  /* Not found in path */
3442  return InvalidOid;
3443 }
3444 
3445 /*
3446  * recomputeNamespacePath - recompute path derived variables if needed.
3447  */
3448 static void
3450 {
3451  Oid roleid = GetUserId();
3452  char *rawname;
3453  List *namelist;
3454  List *oidlist;
3455  List *newpath;
3456  ListCell *l;
3457  bool temp_missing;
3458  Oid firstNS;
3459  MemoryContext oldcxt;
3460 
3461  /* Do nothing if an override search spec is active. */
3462  if (overrideStack)
3463  return;
3464 
3465  /* Do nothing if path is already valid. */
3466  if (baseSearchPathValid && namespaceUser == roleid)
3467  return;
3468 
3469  /* Need a modifiable copy of namespace_search_path string */
3470  rawname = pstrdup(namespace_search_path);
3471 
3472  /* Parse string into list of identifiers */
3473  if (!SplitIdentifierString(rawname, ',', &namelist))
3474  {
3475  /* syntax error in name list */
3476  /* this should not happen if GUC checked check_search_path */
3477  elog(ERROR, "invalid list syntax");
3478  }
3479 
3480  /*
3481  * Convert the list of names to a list of OIDs. If any names are not
3482  * recognizable or we don't have read access, just leave them out of the
3483  * list. (We can't raise an error, since the search_path setting has
3484  * already been accepted.) Don't make duplicate entries, either.
3485  */
3486  oidlist = NIL;
3487  temp_missing = false;
3488  foreach(l, namelist)
3489  {
3490  char *curname = (char *) lfirst(l);
3491  Oid namespaceId;
3492 
3493  if (strcmp(curname, "$user") == 0)
3494  {
3495  /* $user --- substitute namespace matching user name, if any */
3496  HeapTuple tuple;
3497 
3498  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3499  if (HeapTupleIsValid(tuple))
3500  {
3501  char *rname;
3502 
3503  rname = NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname);
3504  namespaceId = get_namespace_oid(rname, true);
3505  ReleaseSysCache(tuple);
3506  if (OidIsValid(namespaceId) &&
3507  !list_member_oid(oidlist, namespaceId) &&
3508  pg_namespace_aclcheck(namespaceId, roleid,
3509  ACL_USAGE) == ACLCHECK_OK &&
3510  InvokeNamespaceSearchHook(namespaceId, false))
3511  oidlist = lappend_oid(oidlist, namespaceId);
3512  }
3513  }
3514  else if (strcmp(curname, "pg_temp") == 0)
3515  {
3516  /* pg_temp --- substitute temp namespace, if any */
3518  {
3519  if (!list_member_oid(oidlist, myTempNamespace) &&
3521  oidlist = lappend_oid(oidlist, myTempNamespace);
3522  }
3523  else
3524  {
3525  /* If it ought to be the creation namespace, set flag */
3526  if (oidlist == NIL)
3527  temp_missing = true;
3528  }
3529  }
3530  else
3531  {
3532  /* normal namespace reference */
3533  namespaceId = get_namespace_oid(curname, true);
3534  if (OidIsValid(namespaceId) &&
3535  !list_member_oid(oidlist, namespaceId) &&
3536  pg_namespace_aclcheck(namespaceId, roleid,
3537  ACL_USAGE) == ACLCHECK_OK &&
3538  InvokeNamespaceSearchHook(namespaceId, false))
3539  oidlist = lappend_oid(oidlist, namespaceId);
3540  }
3541  }
3542 
3543  /*
3544  * Remember the first member of the explicit list. (Note: this is
3545  * nominally wrong if temp_missing, but we need it anyway to distinguish
3546  * explicit from implicit mention of pg_catalog.)
3547  */
3548  if (oidlist == NIL)
3549  firstNS = InvalidOid;
3550  else
3551  firstNS = linitial_oid(oidlist);
3552 
3553  /*
3554  * Add any implicitly-searched namespaces to the list. Note these go on
3555  * the front, not the back; also notice that we do not check USAGE
3556  * permissions for these.
3557  */
3558  if (!list_member_oid(oidlist, PG_CATALOG_NAMESPACE))
3559  oidlist = lcons_oid(PG_CATALOG_NAMESPACE, oidlist);
3560 
3561  if (OidIsValid(myTempNamespace) &&
3562  !list_member_oid(oidlist, myTempNamespace))
3563  oidlist = lcons_oid(myTempNamespace, oidlist);
3564 
3565  /*
3566  * Now that we've successfully built the new list of namespace OIDs, save
3567  * it in permanent storage.
3568  */
3570  newpath = list_copy(oidlist);
3571  MemoryContextSwitchTo(oldcxt);
3572 
3573  /* Now safe to assign to state variables. */
3574  list_free(baseSearchPath);
3575  baseSearchPath = newpath;
3576  baseCreationNamespace = firstNS;
3577  baseTempCreationPending = temp_missing;
3578 
3579  /* Mark the path valid. */
3580  baseSearchPathValid = true;
3581  namespaceUser = roleid;
3582 
3583  /* And make it active. */
3584  activeSearchPath = baseSearchPath;
3587 
3588  /* Clean up. */
3589  pfree(rawname);
3590  list_free(namelist);
3591  list_free(oidlist);
3592 }
3593 
3594 /*
3595  * InitTempTableNamespace
3596  * Initialize temp table namespace on first use in a particular backend
3597  */
3598 static void
3600 {
3601  char namespaceName[NAMEDATALEN];
3602  Oid namespaceId;
3603  Oid toastspaceId;
3604 
3606 
3607  /*
3608  * First, do permission check to see if we are authorized to make temp
3609  * tables. We use a nonstandard error message here since "databasename:
3610  * permission denied" might be a tad cryptic.
3611  *
3612  * Note that ACL_CREATE_TEMP rights are rechecked in pg_namespace_aclmask;
3613  * that's necessary since current user ID could change during the session.
3614  * But there's no need to make the namespace in the first place until a
3615  * temp table creation request is made by someone with appropriate rights.
3616  */
3619  ereport(ERROR,
3620  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3621  errmsg("permission denied to create temporary tables in database \"%s\"",
3623 
3624  /*
3625  * Do not allow a Hot Standby slave session to make temp tables. Aside
3626  * from problems with modifying the system catalogs, there is a naming
3627  * conflict: pg_temp_N belongs to the session with BackendId N on the
3628  * master, not to a slave session with the same BackendId. We should not
3629  * be able to get here anyway due to XactReadOnly checks, but let's just
3630  * make real sure. Note that this also backstops various operations that
3631  * allow XactReadOnly transactions to modify temp tables; they'd need
3632  * RecoveryInProgress checks if not for this.
3633  */
3634  if (RecoveryInProgress())
3635  ereport(ERROR,
3636  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3637  errmsg("cannot create temporary tables during recovery")));
3638 
3639  /* Parallel workers can't create temporary tables, either. */
3640  if (IsParallelWorker())
3641  ereport(ERROR,
3642  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
3643  errmsg("cannot create temporary tables in parallel mode")));
3644 
3645  snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", MyBackendId);
3646 
3647  namespaceId = get_namespace_oid(namespaceName, true);
3648  if (!OidIsValid(namespaceId))
3649  {
3650  /*
3651  * First use of this temp namespace in this database; create it. The
3652  * temp namespaces are always owned by the superuser. We leave their
3653  * permissions at default --- i.e., no access except to superuser ---
3654  * to ensure that unprivileged users can't peek at other backends'
3655  * temp tables. This works because the places that access the temp
3656  * namespace for my own backend skip permissions checks on it.
3657  */
3658  namespaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3659  true);
3660  /* Advance command counter to make namespace visible */
3662  }
3663  else
3664  {
3665  /*
3666  * If the namespace already exists, clean it out (in case the former
3667  * owner crashed without doing so).
3668  */
3669  RemoveTempRelations(namespaceId);
3670  }
3671 
3672  /*
3673  * If the corresponding toast-table namespace doesn't exist yet, create
3674  * it. (We assume there is no need to clean it out if it does exist, since
3675  * dropping a parent table should make its toast table go away.)
3676  */
3677  snprintf(namespaceName, sizeof(namespaceName), "pg_toast_temp_%d",
3678  MyBackendId);
3679 
3680  toastspaceId = get_namespace_oid(namespaceName, true);
3681  if (!OidIsValid(toastspaceId))
3682  {
3683  toastspaceId = NamespaceCreate(namespaceName, BOOTSTRAP_SUPERUSERID,
3684  true);
3685  /* Advance command counter to make namespace visible */
3687  }
3688 
3689  /*
3690  * Okay, we've prepared the temp namespace ... but it's not committed yet,
3691  * so all our work could be undone by transaction rollback. Set flag for
3692  * AtEOXact_Namespace to know what to do.
3693  */
3694  myTempNamespace = namespaceId;
3695  myTempToastNamespace = toastspaceId;
3696 
3697  /* It should not be done already. */
3700 
3701  baseSearchPathValid = false; /* need to rebuild list */
3702 }
3703 
3704 /*
3705  * End-of-transaction cleanup for namespaces.
3706  */
3707 void
3708 AtEOXact_Namespace(bool isCommit, bool parallel)
3709 {
3710  /*
3711  * If we abort the transaction in which a temp namespace was selected,
3712  * we'll have to do any creation or cleanout work over again. So, just
3713  * forget the namespace entirely until next time. On the other hand, if
3714  * we commit then register an exit callback to clean out the temp tables
3715  * at backend shutdown. (We only want to register the callback once per
3716  * session, so this is a good place to do it.)
3717  */
3718  if (myTempNamespaceSubID != InvalidSubTransactionId && !parallel)
3719  {
3720  if (isCommit)
3722  else
3723  {
3726  baseSearchPathValid = false; /* need to rebuild list */
3727  }
3729  }
3730 
3731  /*
3732  * Clean up if someone failed to do PopOverrideSearchPath
3733  */
3734  if (overrideStack)
3735  {
3736  if (isCommit)
3737  elog(WARNING, "leaked override search path");
3738  while (overrideStack)
3739  {
3740  OverrideStackEntry *entry;
3741 
3742  entry = (OverrideStackEntry *) linitial(overrideStack);
3743  overrideStack = list_delete_first(overrideStack);
3744  list_free(entry->searchPath);
3745  pfree(entry);
3746  }
3747  /* If not baseSearchPathValid, this is useless but harmless */
3748  activeSearchPath = baseSearchPath;
3751  }
3752 }
3753 
3754 /*
3755  * AtEOSubXact_Namespace
3756  *
3757  * At subtransaction commit, propagate the temp-namespace-creation
3758  * flag to the parent subtransaction.
3759  *
3760  * At subtransaction abort, forget the flag if we set it up.
3761  */
3762 void
3764  SubTransactionId parentSubid)
3765 {
3766  OverrideStackEntry *entry;
3767 
3768  if (myTempNamespaceSubID == mySubid)
3769  {
3770  if (isCommit)
3771  myTempNamespaceSubID = parentSubid;
3772  else
3773  {
3775  /* TEMP namespace creation failed, so reset state */
3778  baseSearchPathValid = false; /* need to rebuild list */
3779  }
3780  }
3781 
3782  /*
3783  * Clean up if someone failed to do PopOverrideSearchPath
3784  */
3785  while (overrideStack)
3786  {
3787  entry = (OverrideStackEntry *) linitial(overrideStack);
3789  break;
3790  if (isCommit)
3791  elog(WARNING, "leaked override search path");
3792  overrideStack = list_delete_first(overrideStack);
3793  list_free(entry->searchPath);
3794  pfree(entry);
3795  }
3796 
3797  /* Activate the next level down. */
3798  if (overrideStack)
3799  {
3800  entry = (OverrideStackEntry *) linitial(overrideStack);
3801  activeSearchPath = entry->searchPath;
3803  activeTempCreationPending = false; /* XXX is this OK? */
3804  }
3805  else
3806  {
3807  /* If not baseSearchPathValid, this is useless but harmless */
3808  activeSearchPath = baseSearchPath;
3811  }
3812 }
3813 
3814 /*
3815  * Remove all relations in the specified temp namespace.
3816  *
3817  * This is called at backend shutdown (if we made any temp relations).
3818  * It is also called when we begin using a pre-existing temp namespace,
3819  * in order to clean out any relations that might have been created by
3820  * a crashed backend.
3821  */
3822 static void
3823 RemoveTempRelations(Oid tempNamespaceId)
3824 {
3825  ObjectAddress object;
3826 
3827  /*
3828  * We want to get rid of everything in the target namespace, but not the
3829  * namespace itself (deleting it only to recreate it later would be a
3830  * waste of cycles). We do this by finding everything that has a
3831  * dependency on the namespace.
3832  */
3833  object.classId = NamespaceRelationId;
3834  object.objectId = tempNamespaceId;
3835  object.objectSubId = 0;
3836 
3837  deleteWhatDependsOn(&object, false);
3838 }
3839 
3840 /*
3841  * Callback to remove temp relations at backend exit.
3842  */
3843 static void
3845 {
3846  if (OidIsValid(myTempNamespace)) /* should always be true */
3847  {
3848  /* Need to ensure we have a usable transaction. */
3851 
3853 
3855  }
3856 }
3857 
3858 /*
3859  * Remove all temp tables from the temporary namespace.
3860  */
3861 void
3863 {
3866 }
3867 
3868 
3869 /*
3870  * Routines for handling the GUC variable 'search_path'.
3871  */
3872 
3873 /* check_hook: validate new search_path value */
3874 bool
3875 check_search_path(char **newval, void **extra, GucSource source)
3876 {
3877  char *rawname;
3878  List *namelist;
3879 
3880  /* Need a modifiable copy of string */
3881  rawname = pstrdup(*newval);
3882 
3883  /* Parse string into list of identifiers */
3884  if (!SplitIdentifierString(rawname, ',', &namelist))
3885  {
3886  /* syntax error in name list */
3887  GUC_check_errdetail("List syntax is invalid.");
3888  pfree(rawname);
3889  list_free(namelist);
3890  return false;
3891  }
3892 
3893  /*
3894  * We used to try to check that the named schemas exist, but there are
3895  * many valid use-cases for having search_path settings that include
3896  * schemas that don't exist; and often, we are not inside a transaction
3897  * here and so can't consult the system catalogs anyway. So now, the only
3898  * requirement is syntactic validity of the identifier list.
3899  */
3900 
3901  pfree(rawname);
3902  list_free(namelist);
3903 
3904  return true;
3905 }
3906 
3907 /* assign_hook: do extra actions as needed */
3908 void
3909 assign_search_path(const char *newval, void *extra)
3910 {
3911  /*
3912  * We mark the path as needing recomputation, but don't do anything until
3913  * it's needed. This avoids trying to do database access during GUC
3914  * initialization, or outside a transaction.
3915  */
3916  baseSearchPathValid = false;
3917 }
3918 
3919 /*
3920  * InitializeSearchPath: initialize module during InitPostgres.
3921  *
3922  * This is called after we are up enough to be able to do catalog lookups.
3923  */
3924 void
3926 {
3928  {
3929  /*
3930  * In bootstrap mode, the search path must be 'pg_catalog' so that
3931  * tables are created in the proper namespace; ignore the GUC setting.
3932  */
3933  MemoryContext oldcxt;
3934 
3936  baseSearchPath = list_make1_oid(PG_CATALOG_NAMESPACE);
3937  MemoryContextSwitchTo(oldcxt);
3939  baseTempCreationPending = false;
3940  baseSearchPathValid = true;
3942  activeSearchPath = baseSearchPath;
3945  }
3946  else
3947  {
3948  /*
3949  * In normal mode, arrange for a callback on any syscache invalidation
3950  * of pg_namespace rows.
3951  */
3954  (Datum) 0);
3955  /* Force search path to be recomputed on next use */
3956  baseSearchPathValid = false;
3957  }
3958 }
3959 
3960 /*
3961  * NamespaceCallback
3962  * Syscache inval callback function
3963  */
3964 static void
3965 NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
3966 {
3967  /* Force search path to be recomputed on next use */
3968  baseSearchPathValid = false;
3969 }
3970 
3971 /*
3972  * Fetch the active search path. The return value is a palloc'ed list
3973  * of OIDs; the caller is responsible for freeing this storage as
3974  * appropriate.
3975  *
3976  * The returned list includes the implicitly-prepended namespaces only if
3977  * includeImplicit is true.
3978  *
3979  * Note: calling this may result in a CommandCounterIncrement operation,
3980  * if we have to create or clean out the temp namespace.
3981  */
3982 List *
3983 fetch_search_path(bool includeImplicit)
3984 {
3985  List *result;
3986 
3988 
3989  /*
3990  * If the temp namespace should be first, force it to exist. This is so
3991  * that callers can trust the result to reflect the actual default
3992  * creation namespace. It's a bit bogus to do this here, since
3993  * current_schema() is supposedly a stable function without side-effects,
3994  * but the alternatives seem worse.
3995  */
3997  {
4000  }
4001 
4002  result = list_copy(activeSearchPath);
4003  if (!includeImplicit)
4004  {
4005  while (result && linitial_oid(result) != activeCreationNamespace)
4006  result = list_delete_first(result);
4007  }
4008 
4009  return result;
4010 }
4011 
4012 /*
4013  * Fetch the active search path into a caller-allocated array of OIDs.
4014  * Returns the number of path entries. (If this is more than sarray_len,
4015  * then the data didn't fit and is not all stored.)
4016  *
4017  * The returned list always includes the implicitly-prepended namespaces,
4018  * but never includes the temp namespace. (This is suitable for existing
4019  * users, which would want to ignore the temp namespace anyway.) This
4020  * definition allows us to not worry about initializing the temp namespace.
4021  */
4022 int
4023 fetch_search_path_array(Oid *sarray, int sarray_len)
4024 {
4025  int count = 0;
4026  ListCell *l;
4027 
4029 
4030  foreach(l, activeSearchPath)
4031  {
4032  Oid namespaceId = lfirst_oid(l);
4033 
4034  if (namespaceId == myTempNamespace)
4035  continue; /* do not include temp namespace */
4036 
4037  if (count < sarray_len)
4038  sarray[count] = namespaceId;
4039  count++;
4040  }
4041 
4042  return count;
4043 }
4044 
4045 
4046 /*
4047  * Export the FooIsVisible functions as SQL-callable functions.
4048  *
4049  * Note: as of Postgres 8.4, these will silently return NULL if called on
4050  * a nonexistent object OID, rather than failing. This is to avoid race
4051  * condition errors when a query that's scanning a catalog using an MVCC
4052  * snapshot uses one of these functions. The underlying IsVisible functions
4053  * always use an up-to-date snapshot and so might see the object as already
4054  * gone when it's still visible to the transaction snapshot. (There is no race
4055  * condition in the current coding because we don't accept sinval messages
4056  * between the SearchSysCacheExists test and the subsequent lookup.)
4057  */
4058 
4059 Datum
4061 {
4062  Oid oid = PG_GETARG_OID(0);
4063 
4065  PG_RETURN_NULL();
4066 
4068 }
4069 
4070 Datum
4072 {
4073  Oid oid = PG_GETARG_OID(0);
4074 
4076  PG_RETURN_NULL();
4077 
4079 }
4080 
4081 Datum
4083 {
4084  Oid oid = PG_GETARG_OID(0);
4085 
4087  PG_RETURN_NULL();
4088 
4090 }
4091 
4092 Datum
4094 {
4095  Oid oid = PG_GETARG_OID(0);
4096 
4098  PG_RETURN_NULL();
4099 
4101 }
4102 
4103 Datum
4105 {
4106  Oid oid = PG_GETARG_OID(0);
4107 
4109  PG_RETURN_NULL();
4110 
4112 }
4113 
4114 Datum
4116 {
4117  Oid oid = PG_GETARG_OID(0);
4118 
4120  PG_RETURN_NULL();
4121 
4123 }
4124 
4125 Datum
4127 {
4128  Oid oid = PG_GETARG_OID(0);
4129 
4131  PG_RETURN_NULL();
4132 
4134 }
4135 
4136 Datum
4138 {
4139  Oid oid = PG_GETARG_OID(0);
4140 
4142  PG_RETURN_NULL();
4143 
4145 }
4146 
4147 Datum
4149 {
4150  Oid oid = PG_GETARG_OID(0);
4151 
4153  PG_RETURN_NULL();
4154 
4156 }
4157 
4158 Datum
4160 {
4161  Oid oid = PG_GETARG_OID(0);
4162 
4164  PG_RETURN_NULL();
4165 
4167 }
4168 
4169 Datum
4171 {
4172  Oid oid = PG_GETARG_OID(0);
4173 
4175  PG_RETURN_NULL();
4176 
4178 }
4179 
4180 Datum
4182 {
4183  Oid oid = PG_GETARG_OID(0);
4184 
4186  PG_RETURN_NULL();
4187 
4189 }
4190 
4191 Datum
4193 {
4195 }
4196 
4197 Datum
4199 {
4200  Oid oid = PG_GETARG_OID(0);
4201 
4203 }
Value * makeString(char *str)
Definition: value.c:53
void ResetTempTableNamespace(void)
Definition: namespace.c:3862
#define NIL
Definition: pg_list.h:69
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
static bool baseSearchPathValid
Definition: namespace.c:151
#define NamespaceRelationId
Definition: pg_namespace.h:34
#define IsA(nodeptr, _type_)
Definition: nodes.h:542
int n_members
Definition: catcache.h:149
Oid get_namespace_oid(const char *nspname, bool missing_ok)
Definition: namespace.c:2854
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2702
BackendId MyBackendId
Definition: globals.c:72
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
#define AssertState(condition)
Definition: c.h:670
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:60
void AcceptInvalidationMessages(void)
Definition: inval.c:660
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:9518
FormData_pg_ts_config * Form_pg_ts_config
Definition: pg_ts_config.h:41
int LOCKMODE
Definition: lockdefs.h:26
Oid GetUserId(void)
Definition: miscinit.c:282
Oid TypenameGetTypid(const char *typname)
Definition: namespace.c:762
Datum pg_type_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4071
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:182
Oid oprid(Operator op)
Definition: parse_oper.c:243
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok, bool nowait, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:232
#define GUC_check_errdetail
Definition: guc.h:408
Oid RelnameGetRelid(const char *relname)
Definition: namespace.c:668
Datum pg_my_temp_schema(PG_FUNCTION_ARGS)
Definition: namespace.c:4192
Oid QualifiedNameGetCreationNamespace(List *names, char **objname_p)
Definition: namespace.c:2805
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:2991
#define PointerGetDatum(X)
Definition: postgres.h:564
static Oid myTempToastNamespace
Definition: namespace.c:181
Oid LookupCreationNamespace(const char *nspname)
Definition: namespace.c:2745
#define SearchSysCache4(cacheId, key1, key2, key3, key4)
Definition: syscache.h:147
char * pstrdup(const char *in)
Definition: mcxt.c:1168
void CommitTransactionCommand(void)
Definition: xact.c:2743
Datum pg_opclass_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4104
void PushOverrideSearchPath(OverrideSearchPath *newpath)
Definition: namespace.c:3197
Datum pg_conversion_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4137
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:792
static Oid myTempNamespace
Definition: namespace.c:179
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
static List * overrideStack
Definition: namespace.c:162
List * list_copy(const List *oldlist)
Definition: list.c:1160
Definition: nodes.h:491
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid get_ts_config_oid(List *names, bool missing_ok)
Definition: namespace.c:2488
bool OperatorIsVisible(Oid oprid)
Definition: namespace.c:1721
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int GetTempNamespaceBackendId(Oid namespaceId)
Definition: namespace.c:3044
void DeconstructQualifiedName(List *names, char **nspname_p, char **objname_p)
Definition: namespace.c:2618
bool FunctionIsVisible(Oid funcid)
Definition: namespace.c:1388
static Oid namespaceUser
Definition: namespace.c:148
void(* RangeVarGetRelidCallback)(const RangeVar *relation, Oid relId, Oid oldRelId, void *callback_arg)
Definition: namespace.h:50
RangeVar * makeRangeVarFromNameList(List *names)
Definition: namespace.c:2872
Oid CollationGetCollid(const char *collname)
Definition: namespace.c:1937
uint32 SubTransactionId
Definition: c.h:397
List * lcons_oid(Oid datum, List *list)
Definition: list.c:295
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_TOAST_NAMESPACE
Definition: pg_namespace.h:74
bool RecoveryInProgress(void)
Definition: xlog.c:7547
Oid OpclassnameGetOpcid(Oid amid, const char *opcname)
Definition: namespace.c:1774
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:530
int fetch_search_path_array(Oid *sarray, int sarray_len)
Definition: namespace.c:4023
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4218
AclResult pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4467
#define GetSysCacheOid3(cacheId, key1, key2, key3)
Definition: syscache.h:172
void RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
Definition: namespace.c:629
#define lsecond(l)
Definition: pg_list.h:114
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
signed int int32
Definition: c.h:253
#define GetSysCacheOid2(cacheId, key1, key2)
Definition: syscache.h:170
FuncCandidateList OpernameGetCandidates(List *names, char oprkind, bool missing_schema_ok)
Definition: namespace.c:1561
GucSource
Definition: guc.h:105
static void recomputeNamespacePath(void)
Definition: namespace.c:3449
struct _FuncCandidateList * FuncCandidateList
char * schemaname
Definition: primnodes.h:73
#define GetSysCacheOid1(cacheId, key1)
Definition: syscache.h:168
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:164
static char * relname(char const *dir, char const *base)
Definition: zic.c:755
#define FUNC_MAX_ARGS
#define InvokeNamespaceSearchHook(objectId, ereport_on_violation)
Definition: objectaccess.h:174
CatCTup * members[FLEXIBLE_ARRAY_MEMBER]
Definition: catcache.h:150
#define list_make1(x1)
Definition: pg_list.h:133
#define NAMEDATALEN
Oid ConversionGetConid(const char *conname)
Definition: namespace.c:2030
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
char * relname
Definition: primnodes.h:74
Oid OpernameGetOprid(List *names, Oid oprleft, Oid oprright)
Definition: namespace.c:1459
Oid get_ts_dict_oid(List *names, bool missing_ok)
Definition: namespace.c:2235
static Oid activeCreationNamespace
Definition: namespace.c:135
Oid OpfamilynameGetOpfid(Oid amid, const char *opfname)
Definition: namespace.c:1857
#define SearchSysCacheExists1(cacheId, key1)
Definition: syscache.h:159
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:995
#define linitial(l)
Definition: pg_list.h:110
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
void deleteWhatDependsOn(const ObjectAddress *object, bool showNotices)
Definition: dependency.c:407
#define ACL_CREATE
Definition: parsenodes.h:73
bool TSConfigIsVisible(Oid cfgid)
Definition: namespace.c:2546
static bool baseTempCreationPending
Definition: namespace.c:146
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:917
void InitializeSearchPath(void)
Definition: namespace.c:3925
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:49
OverrideSearchPath * CopyOverrideSearchPath(OverrideSearchPath *path)
Definition: namespace.c:3121
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:1651
OverrideSearchPath * GetOverrideSearchPath(MemoryContext context)
Definition: namespace.c:3085
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2024
Datum pg_opfamily_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4115
FormData_pg_ts_dict * Form_pg_ts_dict
Definition: pg_ts_dict.h:45
Oid GetTempToastNamespace(void)
Definition: namespace.c:3069
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
Oid get_ts_template_oid(List *names, bool missing_ok)
Definition: namespace.c:2362
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3006
#define NoLock
Definition: lockdefs.h:34
#define PG_GETARG_OID(n)
Definition: fmgr.h:231
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3128
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3391
Datum pg_function_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4082
#define CStringGetDatum(X)
Definition: postgres.h:586
char string[11]
Definition: preproc-type.c:46
void LockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:830
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
unsigned int uint32
Definition: c.h:265
static SubTransactionId myTempNamespaceSubID
Definition: namespace.c:183
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:2967
#define ACL_USAGE
Definition: parsenodes.h:71
#define SearchSysCacheList1(cacheId, key1)
Definition: syscache.h:186
bool CollationIsVisible(Oid collid)
Definition: namespace.c:1980
#define PG_CATALOG_NAMESPACE
Definition: pg_namespace.h:71
#define SPACE_PER_OP
struct _FuncCandidateList * next
Definition: namespace.h:30
static void NamespaceCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: namespace.c:3965
Datum pg_ts_config_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4181
#define lnext(lc)
Definition: pg_list.h:105
static bool activeTempCreationPending
Definition: namespace.c:138
#define ereport(elevel, rest)
Definition: elog.h:122
bool OpfamilyIsVisible(Oid opfid)
Definition: namespace.c:1890
#define IsParallelWorker()
Definition: parallel.h:54
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Datum pg_ts_template_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4170
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition: namespace.c:2777
void UnlockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:851
static Oid baseCreationNamespace
Definition: namespace.c:144
static void InitTempTableNamespace(void)
Definition: namespace.c:3599
bool isTempToastNamespace(Oid namespaceId)
Definition: namespace.c:2979
#define Anum_pg_proc_proargnames
Definition: pg_proc.h:112
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
bool TSDictionaryIsVisible(Oid dictId)
Definition: namespace.c:2293
#define WARNING
Definition: elog.h:40
char * NameListToString(List *names)
Definition: namespace.c:2912
char * NameListToQuotedString(List *names)
Definition: namespace.c:2946
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition: namespace.c:522
#define ReleaseSysCacheList(x)
Definition: syscache.h:195
void PopOverrideSearchPath(void)
Definition: namespace.c:3256
#define InvalidBackendId
Definition: backendid.h:23
FormData_pg_opfamily * Form_pg_opfamily
Definition: pg_opfamily.h:44
char * namespace_search_path
Definition: namespace.c:189
static List * baseSearchPath
Definition: namespace.c:142
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1354
void * palloc0(Size size)
Definition: mcxt.c:923
AclResult
Definition: acl.h:169
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:303
uintptr_t Datum
Definition: postgres.h:374
void CommandCounterIncrement(void)
Definition: xact.c:919
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
FormData_pg_ts_parser * Form_pg_ts_parser
Definition: pg_ts_parser.h:44
FormData_pg_conversion * Form_pg_conversion
Definition: pg_conversion.h:56
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1152
#define list_make1_oid(x1)
Definition: pg_list.h:145
Datum pg_ts_parser_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4148
Oid MyDatabaseId
Definition: globals.c:74
bool OpclassIsVisible(Oid opcid)
Definition: namespace.c:1807
uint64 SharedInvalidMessageCounter
Definition: sinval.c:26
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
void assign_search_path(const char *newval, void *extra)
Definition: namespace.c:3909
Datum pg_ts_dict_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4159
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:758
List * lcons(void *datum, List *list)
Definition: list.c:259
bool ConversionIsVisible(Oid conid)
Definition: namespace.c:2062
bool OverrideSearchPathMatchesCurrent(OverrideSearchPath *path)
Definition: namespace.c:3137
#define Max(x, y)
Definition: c.h:792
Datum pg_is_other_temp_schema(PG_FUNCTION_ARGS)
Definition: namespace.c:4198
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
AclResult pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4417
#define NULL
Definition: c.h:226
Oid get_ts_parser_oid(List *names, bool missing_ok)
Definition: namespace.c:2109
#define Assert(condition)
Definition: c.h:667
#define lfirst(lc)
Definition: pg_list.h:106
const char * GetDatabaseEncodingName(void)
Definition: mbutils.c:1021
bool TypeIsVisible(Oid typid)
Definition: namespace.c:791
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:646
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4529
void StartTransactionCommand(void)
Definition: xact.c:2673
Datum pg_operator_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4093
static void RemoveTempRelations(Oid tempNamespaceId)
Definition: namespace.c:3823
#define linitial_oid(l)
Definition: pg_list.h:112
bool check_search_path(char **newval, void **extra, GucSource source)
Definition: namespace.c:3875
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
Oid FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
Definition: namespace.c:3422
#define SearchSysCacheExists2(cacheId, key1, key2)
Definition: syscache.h:161
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:104
#define InvalidSubTransactionId
Definition: c.h:399
FormData_pg_operator* Form_pg_operator
Definition: pg_operator.h:57
const char * name
Definition: encode.c:521
static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames, int **argnumbers)
Definition: namespace.c:1280
FormData_pg_collation * Form_pg_collation
Definition: pg_collation.h:47
Datum pg_collation_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4126
#define nodeTag(nodeptr)
Definition: nodes.h:496
char relpersistence
Definition: primnodes.h:77
Oid get_conversion_oid(List *name, bool missing_ok)
Definition: namespace.c:3367
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:364
FormData_pg_class * Form_pg_class
Definition: pg_class.h:92
static List * activeSearchPath
Definition: namespace.c:132
#define Int32GetDatum(X)
Definition: postgres.h:487
bool ordered
Definition: catcache.h:145
bool TSTemplateIsVisible(Oid tmplId)
Definition: namespace.c:2420
bool TSParserIsVisible(Oid prsId)
Definition: namespace.c:2167
void * palloc(Size size)
Definition: mcxt.c:894
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define SearchSysCacheList3(cacheId, key1, key2, key3)
Definition: syscache.h:190
bool RelationIsVisible(Oid relid)
Definition: namespace.c:696
bool isOtherTempNamespace(Oid namespaceId)
Definition: namespace.c:3028
void list_free(List *list)
Definition: list.c:1133
FormData_pg_ts_template * Form_pg_ts_template
int i
#define ACL_CREATE_TEMP
Definition: parsenodes.h:74
#define NameStr(name)
Definition: c.h:494
void * arg
#define lthird(l)
Definition: pg_list.h:118
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3005
#define PG_FUNCTION_ARGS
Definition: fmgr.h:150
HeapTupleData tuple
Definition: catcache.h:111
#define elog
Definition: elog.h:218
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3763
Oid FindDefaultConversion(Oid name_space, int32 for_encoding, int32 to_encoding)
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:670
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:166
Datum pg_table_is_visible(PG_FUNCTION_ARGS)
Definition: namespace.c:4060
FormData_pg_opclass * Form_pg_opclass
Definition: pg_opclass.h:68
void AtEOXact_Namespace(bool isCommit, bool parallel)
Definition: namespace.c:3708
Oid get_collation_oid(List *name, bool missing_ok)
Definition: namespace.c:3294
Definition: pg_list.h:45
#define PG_RETURN_OID(x)
Definition: fmgr.h:304
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:3983
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
#define PG_RETURN_NULL()
Definition: fmgr.h:289
char * catalogname
Definition: primnodes.h:72
static void RemoveTempRelationsCallback(int code, Datum arg)
Definition: namespace.c:3844
#define offsetof(type, field)
Definition: c.h:547
Oid RangeVarGetCreationNamespace(const RangeVar *newRelation)
Definition: namespace.c:435
#define lfirst_oid(lc)
Definition: pg_list.h:108
Oid NamespaceCreate(const char *nspName, Oid ownerId, bool isTemp)
Definition: pg_namespace.c:41
List * list_delete_first(List *list)
Definition: list.c:666
Oid LookupNamespaceNoError(const char *nspname)
Definition: namespace.c:2672