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