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