-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathnamespace.c
5087 lines (4483 loc) · 138 KB
/
namespace.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* namespace.c
* code to support accessing and searching namespaces
*
* This is separate from pg_namespace.c, which contains the routines that
* directly manipulate the pg_namespace system catalog. This module
* provides routines associated with defining a "namespace search path"
* and implementing search-path-controlled searches.
*
*
* Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/backend/catalog/namespace.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "access/parallel.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/dependency.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_conversion.h"
#include "catalog/pg_database.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_opfamily.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic_ext.h"
#include "catalog/pg_ts_config.h"
#include "catalog/pg_ts_dict.h"
#include "catalog/pg_ts_parser.h"
#include "catalog/pg_ts_template.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#include "common/hashfn_unstable.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/guc_hooks.h"
#include "utils/inval.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
/*
* The namespace search path is a possibly-empty list of namespace OIDs.
* In addition to the explicit list, implicitly-searched namespaces
* may be included:
*
* 1. If a TEMP table namespace has been initialized in this session, it
* is implicitly searched first.
*
* 2. The system catalog namespace is always searched. If the system
* namespace is present in the explicit path then it will be searched in
* the specified order; otherwise it will be searched after TEMP tables and
* *before* the explicit list. (It might seem that the system namespace
* should be implicitly last, but this behavior appears to be required by
* SQL99. Also, this provides a way to search the system namespace first
* without thereby making it the default creation target namespace.)
*
* For security reasons, searches using the search path will ignore the temp
* namespace when searching for any object type other than relations and
* types. (We must allow types since temp tables have rowtypes.)
*
* The default creation target namespace is always the first element of the
* explicit list. If the explicit list is empty, there is no default target.
*
* The textual specification of search_path can include "$user" to refer to
* the namespace named the same as the current user, if any. (This is just
* ignored if there is no such namespace.) Also, it can include "pg_temp"
* to refer to the current backend's temp namespace. This is usually also
* ignorable if the temp namespace hasn't been set up, but there's a special
* case: if "pg_temp" appears first then it should be the default creation
* target. We kluge this case a little bit so that the temp namespace isn't
* set up until the first attempt to create something in it. (The reason for
* klugery is that we can't create the temp namespace outside a transaction,
* but initial GUC processing of search_path happens outside a transaction.)
* activeTempCreationPending is true if "pg_temp" appears first in the string
* but is not reflected in activeCreationNamespace because the namespace isn't
* set up yet.
*
* In bootstrap mode, the search path is set equal to "pg_catalog", so that
* the system namespace is the only one searched or inserted into.
* initdb is also careful to set search_path to "pg_catalog" for its
* post-bootstrap standalone backend runs. Otherwise the default search
* path is determined by GUC. The factory default path contains the PUBLIC
* namespace (if it exists), preceded by the user's personal namespace
* (if one exists).
*
* activeSearchPath is always the actually active path; it points to
* baseSearchPath which is the list derived from namespace_search_path.
*
* If baseSearchPathValid is false, then baseSearchPath (and other derived
* variables) need to be recomputed from namespace_search_path, or retrieved
* from the search path cache if there haven't been any syscache
* invalidations. We mark it invalid upon an assignment to
* namespace_search_path or receipt of a syscache invalidation event for
* pg_namespace or pg_authid. The recomputation is done during the next
* lookup attempt.
*
* Any namespaces mentioned in namespace_search_path that are not readable
* by the current user ID are simply left out of baseSearchPath; so
* we have to be willing to recompute the path when current userid changes.
* namespaceUser is the userid the path has been computed for.
*
* Note: all data pointed to by these List variables is in TopMemoryContext.
*
* activePathGeneration is incremented whenever the effective values of
* activeSearchPath/activeCreationNamespace/activeTempCreationPending change.
* This can be used to quickly detect whether any change has happened since
* a previous examination of the search path state.
*/
/* These variables define the actually active state: */
static List *activeSearchPath = NIL;
/* default place to create stuff; if InvalidOid, no default */
static Oid activeCreationNamespace = InvalidOid;
/* if true, activeCreationNamespace is wrong, it should be temp namespace */
static bool activeTempCreationPending = false;
/* current generation counter; make sure this is never zero */
static uint64 activePathGeneration = 1;
/* These variables are the values last derived from namespace_search_path: */
static List *baseSearchPath = NIL;
static Oid baseCreationNamespace = InvalidOid;
static bool baseTempCreationPending = false;
static Oid namespaceUser = InvalidOid;
/* The above four values are valid only if baseSearchPathValid */
static bool baseSearchPathValid = true;
/*
* Storage for search path cache. Clear searchPathCacheValid as a simple
* way to invalidate *all* the cache entries, not just the active one.
*/
static bool searchPathCacheValid = false;
static MemoryContext SearchPathCacheContext = NULL;
typedef struct SearchPathCacheKey
{
const char *searchPath;
Oid roleid;
} SearchPathCacheKey;
typedef struct SearchPathCacheEntry
{
SearchPathCacheKey key;
List *oidlist; /* namespace OIDs that pass ACL checks */
List *finalPath; /* cached final computed search path */
Oid firstNS; /* first explicitly-listed namespace */
bool temp_missing;
bool forceRecompute; /* force recompute of finalPath */
/* needed for simplehash */
char status;
} SearchPathCacheEntry;
/*
* myTempNamespace is InvalidOid until and unless a TEMP namespace is set up
* in a particular backend session (this happens when a CREATE TEMP TABLE
* command is first executed). Thereafter it's the OID of the temp namespace.
*
* myTempToastNamespace is the OID of the namespace for my temp tables' toast
* tables. It is set when myTempNamespace is, and is InvalidOid before that.
*
* myTempNamespaceSubID shows whether we've created the TEMP namespace in the
* current subtransaction. The flag propagates up the subtransaction tree,
* so the main transaction will correctly recognize the flag if all
* intermediate subtransactions commit. When it is InvalidSubTransactionId,
* we either haven't made the TEMP namespace yet, or have successfully
* committed its creation, depending on whether myTempNamespace is valid.
*/
static Oid myTempNamespace = InvalidOid;
static Oid myTempToastNamespace = InvalidOid;
static SubTransactionId myTempNamespaceSubID = InvalidSubTransactionId;
/*
* This is the user's textual search path specification --- it's the value
* of the GUC variable 'search_path'.
*/
char *namespace_search_path = NULL;
/* Local functions */
static bool RelationIsVisibleExt(Oid relid, bool *is_missing);
static bool TypeIsVisibleExt(Oid typid, bool *is_missing);
static bool FunctionIsVisibleExt(Oid funcid, bool *is_missing);
static bool OperatorIsVisibleExt(Oid oprid, bool *is_missing);
static bool OpclassIsVisibleExt(Oid opcid, bool *is_missing);
static bool OpfamilyIsVisibleExt(Oid opfid, bool *is_missing);
static bool CollationIsVisibleExt(Oid collid, bool *is_missing);
static bool ConversionIsVisibleExt(Oid conid, bool *is_missing);
static bool StatisticsObjIsVisibleExt(Oid stxid, bool *is_missing);
static bool TSParserIsVisibleExt(Oid prsId, bool *is_missing);
static bool TSDictionaryIsVisibleExt(Oid dictId, bool *is_missing);
static bool TSTemplateIsVisibleExt(Oid tmplId, bool *is_missing);
static bool TSConfigIsVisibleExt(Oid cfgid, bool *is_missing);
static void recomputeNamespacePath(void);
static void AccessTempTableNamespace(bool force);
static void InitTempTableNamespace(void);
static void RemoveTempRelations(Oid tempNamespaceId);
static void RemoveTempRelationsCallback(int code, Datum arg);
static void InvalidationCallback(Datum arg, int cacheid, uint32 hashvalue);
static bool MatchNamedCall(HeapTuple proctup, int nargs, List *argnames,
bool include_out_arguments, int pronargs,
int **argnumbers);
/*
* Recomputing the namespace path can be costly when done frequently, such as
* when a function has search_path set in proconfig. Add a search path cache
* that can be used by recomputeNamespacePath().
*
* The cache is also used to remember already-validated strings in
* check_search_path() to avoid the need to call SplitIdentifierString()
* repeatedly.
*
* The search path cache is based on a wrapper around a simplehash hash table
* (nsphash, defined below). The spcache wrapper deals with OOM while trying
* to initialize a key, optimizes repeated lookups of the same key, and also
* offers a more convenient API.
*/
static inline uint32
spcachekey_hash(SearchPathCacheKey key)
{
fasthash_state hs;
int sp_len;
fasthash_init(&hs, 0);
hs.accum = key.roleid;
fasthash_combine(&hs);
/*
* Combine search path into the hash and save the length for tweaking the
* final mix.
*/
sp_len = fasthash_accum_cstring(&hs, key.searchPath);
return fasthash_final32(&hs, sp_len);
}
static inline bool
spcachekey_equal(SearchPathCacheKey a, SearchPathCacheKey b)
{
return a.roleid == b.roleid &&
strcmp(a.searchPath, b.searchPath) == 0;
}
#define SH_PREFIX nsphash
#define SH_ELEMENT_TYPE SearchPathCacheEntry
#define SH_KEY_TYPE SearchPathCacheKey
#define SH_KEY key
#define SH_HASH_KEY(tb, key) spcachekey_hash(key)
#define SH_EQUAL(tb, a, b) spcachekey_equal(a, b)
#define SH_SCOPE static inline
#define SH_DECLARE
#define SH_DEFINE
#include "lib/simplehash.h"
/*
* We only expect a small number of unique search_path strings to be used. If
* this cache grows to an unreasonable size, reset it to avoid steady-state
* memory growth. Most likely, only a few of those entries will benefit from
* the cache, and the cache will be quickly repopulated with such entries.
*/
#define SPCACHE_RESET_THRESHOLD 256
static nsphash_hash *SearchPathCache = NULL;
static SearchPathCacheEntry *LastSearchPathCacheEntry = NULL;
/*
* Create or reset search_path cache as necessary.
*/
static void
spcache_init(void)
{
if (SearchPathCache && searchPathCacheValid &&
SearchPathCache->members < SPCACHE_RESET_THRESHOLD)
return;
searchPathCacheValid = false;
baseSearchPathValid = false;
/*
* Make sure we don't leave dangling pointers if a failure happens during
* initialization.
*/
SearchPathCache = NULL;
LastSearchPathCacheEntry = NULL;
if (SearchPathCacheContext == NULL)
{
/* Make the context we'll keep search path cache hashtable in */
SearchPathCacheContext = AllocSetContextCreate(TopMemoryContext,
"search_path processing cache",
ALLOCSET_DEFAULT_SIZES);
}
else
{
MemoryContextReset(SearchPathCacheContext);
}
/* arbitrary initial starting size of 16 elements */
SearchPathCache = nsphash_create(SearchPathCacheContext, 16, NULL);
searchPathCacheValid = true;
}
/*
* Look up entry in search path cache without inserting. Returns NULL if not
* present.
*/
static SearchPathCacheEntry *
spcache_lookup(const char *searchPath, Oid roleid)
{
if (LastSearchPathCacheEntry &&
LastSearchPathCacheEntry->key.roleid == roleid &&
strcmp(LastSearchPathCacheEntry->key.searchPath, searchPath) == 0)
{
return LastSearchPathCacheEntry;
}
else
{
SearchPathCacheEntry *entry;
SearchPathCacheKey cachekey = {
.searchPath = searchPath,
.roleid = roleid
};
entry = nsphash_lookup(SearchPathCache, cachekey);
if (entry)
LastSearchPathCacheEntry = entry;
return entry;
}
}
/*
* Look up or insert entry in search path cache.
*
* Initialize key safely, so that OOM does not leave an entry without a valid
* key. Caller must ensure that non-key contents are properly initialized.
*/
static SearchPathCacheEntry *
spcache_insert(const char *searchPath, Oid roleid)
{
if (LastSearchPathCacheEntry &&
LastSearchPathCacheEntry->key.roleid == roleid &&
strcmp(LastSearchPathCacheEntry->key.searchPath, searchPath) == 0)
{
return LastSearchPathCacheEntry;
}
else
{
SearchPathCacheEntry *entry;
SearchPathCacheKey cachekey = {
.searchPath = searchPath,
.roleid = roleid
};
/*
* searchPath is not saved in SearchPathCacheContext. First perform a
* lookup, and copy searchPath only if we need to create a new entry.
*/
entry = nsphash_lookup(SearchPathCache, cachekey);
if (!entry)
{
bool found;
cachekey.searchPath = MemoryContextStrdup(SearchPathCacheContext, searchPath);
entry = nsphash_insert(SearchPathCache, cachekey, &found);
Assert(!found);
entry->oidlist = NIL;
entry->finalPath = NIL;
entry->firstNS = InvalidOid;
entry->temp_missing = false;
entry->forceRecompute = false;
/* do not touch entry->status, used by simplehash */
}
LastSearchPathCacheEntry = entry;
return entry;
}
}
/*
* RangeVarGetRelidExtended
* Given a RangeVar describing an existing relation,
* select the proper namespace and look up the relation OID.
*
* If the schema or relation is not found, return InvalidOid if flags contains
* RVR_MISSING_OK, otherwise raise an error.
*
* If flags contains RVR_NOWAIT, throw an error if we'd have to wait for a
* lock.
*
* If flags contains RVR_SKIP_LOCKED, return InvalidOid if we'd have to wait
* for a lock.
*
* flags cannot contain both RVR_NOWAIT and RVR_SKIP_LOCKED.
*
* Note that if RVR_MISSING_OK and RVR_SKIP_LOCKED are both specified, a
* return value of InvalidOid could either mean the relation is missing or it
* could not be locked.
*
* Callback allows caller to check permissions or acquire additional locks
* prior to grabbing the relation lock.
*/
Oid
RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode,
uint32 flags,
RangeVarGetRelidCallback callback, void *callback_arg)
{
uint64 inval_count;
Oid relId;
Oid oldRelId = InvalidOid;
bool retry = false;
bool missing_ok = (flags & RVR_MISSING_OK) != 0;
/* verify that flags do no conflict */
Assert(!((flags & RVR_NOWAIT) && (flags & RVR_SKIP_LOCKED)));
/*
* We check the catalog name and then ignore it.
*/
if (relation->catalogname)
{
if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
relation->catalogname, relation->schemaname,
relation->relname)));
}
/*
* DDL operations can change the results of a name lookup. Since all such
* operations will generate invalidation messages, we keep track of
* whether any such messages show up while we're performing the operation,
* and retry until either (1) no more invalidation messages show up or (2)
* the answer doesn't change.
*
* But if lockmode = NoLock, then we assume that either the caller is OK
* with the answer changing under them, or that they already hold some
* appropriate lock, and therefore return the first answer we get without
* checking for invalidation messages. Also, if the requested lock is
* already held, LockRelationOid will not AcceptInvalidationMessages, so
* we may fail to notice a change. We could protect against that case by
* calling AcceptInvalidationMessages() before beginning this loop, but
* that would add a significant amount overhead, so for now we don't.
*/
for (;;)
{
/*
* Remember this value, so that, after looking up the relation name
* and locking its OID, we can check whether any invalidation messages
* have been processed that might require a do-over.
*/
inval_count = SharedInvalidMessageCounter;
/*
* Some non-default relpersistence value may have been specified. The
* parser never generates such a RangeVar in simple DML, but it can
* happen in contexts such as "CREATE TEMP TABLE foo (f1 int PRIMARY
* KEY)". Such a command will generate an added CREATE INDEX
* operation, which must be careful to find the temp table, even when
* pg_temp is not first in the search path.
*/
if (relation->relpersistence == RELPERSISTENCE_TEMP)
{
if (!OidIsValid(myTempNamespace))
relId = InvalidOid; /* this probably can't happen? */
else
{
if (relation->schemaname)
{
Oid namespaceId;
namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
/*
* For missing_ok, allow a non-existent schema name to
* return InvalidOid.
*/
if (namespaceId != myTempNamespace)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("temporary tables cannot specify a schema name")));
}
relId = get_relname_relid(relation->relname, myTempNamespace);
}
}
else if (relation->schemaname)
{
Oid namespaceId;
/* use exact schema given */
namespaceId = LookupExplicitNamespace(relation->schemaname, missing_ok);
if (missing_ok && !OidIsValid(namespaceId))
relId = InvalidOid;
else
relId = get_relname_relid(relation->relname, namespaceId);
}
else
{
/* search the namespace path */
relId = RelnameGetRelid(relation->relname);
}
/*
* Invoke caller-supplied callback, if any.
*
* This callback is a good place to check permissions: we haven't
* taken the table lock yet (and it's really best to check permissions
* before locking anything!), but we've gotten far enough to know what
* OID we think we should lock. Of course, concurrent DDL might
* change things while we're waiting for the lock, but in that case
* the callback will be invoked again for the new OID.
*/
if (callback)
callback(relation, relId, oldRelId, callback_arg);
/*
* If no lock requested, we assume the caller knows what they're
* doing. They should have already acquired a heavyweight lock on
* this relation earlier in the processing of this same statement, so
* it wouldn't be appropriate to AcceptInvalidationMessages() here, as
* that might pull the rug out from under them.
*/
if (lockmode == NoLock)
break;
/*
* If, upon retry, we get back the same OID we did last time, then the
* invalidation messages we processed did not change the final answer.
* So we're done.
*
* If we got a different OID, we've locked the relation that used to
* have this name rather than the one that does now. So release the
* lock.
*/
if (retry)
{
if (relId == oldRelId)
break;
if (OidIsValid(oldRelId))
UnlockRelationOid(oldRelId, lockmode);
}
/*
* Lock relation. This will also accept any pending invalidation
* messages. If we got back InvalidOid, indicating not found, then
* there's nothing to lock, but we accept invalidation messages
* anyway, to flush any negative catcache entries that may be
* lingering.
*/
if (!OidIsValid(relId))
AcceptInvalidationMessages();
else if (!(flags & (RVR_NOWAIT | RVR_SKIP_LOCKED)))
LockRelationOid(relId, lockmode);
else if (!ConditionalLockRelationOid(relId, lockmode))
{
int elevel = (flags & RVR_SKIP_LOCKED) ? DEBUG1 : ERROR;
if (relation->schemaname)
ereport(elevel,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("could not obtain lock on relation \"%s.%s\"",
relation->schemaname, relation->relname)));
else
ereport(elevel,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("could not obtain lock on relation \"%s\"",
relation->relname)));
return InvalidOid;
}
/*
* If no invalidation message were processed, we're done!
*/
if (inval_count == SharedInvalidMessageCounter)
break;
/*
* Something may have changed. Let's repeat the name lookup, to make
* sure this name still references the same relation it did
* previously.
*/
retry = true;
oldRelId = relId;
}
if (!OidIsValid(relId))
{
int elevel = missing_ok ? DEBUG1 : ERROR;
if (relation->schemaname)
ereport(elevel,
(errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("relation \"%s.%s\" does not exist",
relation->schemaname, relation->relname)));
else
ereport(elevel,
(errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("relation \"%s\" does not exist",
relation->relname)));
}
return relId;
}
/*
* RangeVarGetCreationNamespace
* Given a RangeVar describing a to-be-created relation,
* choose which namespace to create it in.
*
* Note: calling this may result in a CommandCounterIncrement operation.
* That will happen on the first request for a temp table in any particular
* backend run; we will need to either create or clean out the temp schema.
*/
Oid
RangeVarGetCreationNamespace(const RangeVar *newRelation)
{
Oid namespaceId;
/*
* We check the catalog name and then ignore it.
*/
if (newRelation->catalogname)
{
if (strcmp(newRelation->catalogname, get_database_name(MyDatabaseId)) != 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
newRelation->catalogname, newRelation->schemaname,
newRelation->relname)));
}
if (newRelation->schemaname)
{
/* check for pg_temp alias */
if (strcmp(newRelation->schemaname, "pg_temp") == 0)
{
/* Initialize temp namespace */
AccessTempTableNamespace(false);
return myTempNamespace;
}
/* use exact schema given */
namespaceId = get_namespace_oid(newRelation->schemaname, false);
/* we do not check for USAGE rights here! */
}
else if (newRelation->relpersistence == RELPERSISTENCE_TEMP)
{
/* Initialize temp namespace */
AccessTempTableNamespace(false);
return myTempNamespace;
}
else
{
/* use the default creation namespace */
recomputeNamespacePath();
if (activeTempCreationPending)
{
/* Need to initialize temp namespace */
AccessTempTableNamespace(true);
return myTempNamespace;
}
namespaceId = activeCreationNamespace;
if (!OidIsValid(namespaceId))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_SCHEMA),
errmsg("no schema has been selected to create in")));
}
/* Note: callers will check for CREATE rights when appropriate */
return namespaceId;
}
/*
* RangeVarGetAndCheckCreationNamespace
*
* This function returns the OID of the namespace in which a new relation
* with a given name should be created. If the user does not have CREATE
* permission on the target namespace, this function will instead signal
* an ERROR.
*
* If non-NULL, *existing_relation_id is set to the OID of any existing relation
* with the same name which already exists in that namespace, or to InvalidOid
* if no such relation exists.
*
* If lockmode != NoLock, the specified lock mode is acquired on the existing
* relation, if any, provided that the current user owns the target relation.
* However, if lockmode != NoLock and the user does not own the target
* relation, we throw an ERROR, as we must not try to lock relations the
* user does not have permissions on.
*
* As a side effect, this function acquires AccessShareLock on the target
* namespace. Without this, the namespace could be dropped before our
* transaction commits, leaving behind relations with relnamespace pointing
* to a no-longer-existent namespace.
*
* As a further side-effect, if the selected namespace is a temporary namespace,
* we mark the RangeVar as RELPERSISTENCE_TEMP.
*/
Oid
RangeVarGetAndCheckCreationNamespace(RangeVar *relation,
LOCKMODE lockmode,
Oid *existing_relation_id)
{
uint64 inval_count;
Oid relid;
Oid oldrelid = InvalidOid;
Oid nspid;
Oid oldnspid = InvalidOid;
bool retry = false;
/*
* We check the catalog name and then ignore it.
*/
if (relation->catalogname)
{
if (strcmp(relation->catalogname, get_database_name(MyDatabaseId)) != 0)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
relation->catalogname, relation->schemaname,
relation->relname)));
}
/*
* As in RangeVarGetRelidExtended(), we guard against concurrent DDL
* operations by tracking whether any invalidation messages are processed
* while we're doing the name lookups and acquiring locks. See comments
* in that function for a more detailed explanation of this logic.
*/
for (;;)
{
AclResult aclresult;
inval_count = SharedInvalidMessageCounter;
/* Look up creation namespace and check for existing relation. */
nspid = RangeVarGetCreationNamespace(relation);
Assert(OidIsValid(nspid));
if (existing_relation_id != NULL)
relid = get_relname_relid(relation->relname, nspid);
else
relid = InvalidOid;
/*
* In bootstrap processing mode, we don't bother with permissions or
* locking. Permissions might not be working yet, and locking is
* unnecessary.
*/
if (IsBootstrapProcessingMode())
break;
/* Check namespace permissions. */
aclresult = object_aclcheck(NamespaceRelationId, nspid, GetUserId(), ACL_CREATE);
if (aclresult != ACLCHECK_OK)
aclcheck_error(aclresult, OBJECT_SCHEMA,
get_namespace_name(nspid));
if (retry)
{
/* If nothing changed, we're done. */
if (relid == oldrelid && nspid == oldnspid)
break;
/* If creation namespace has changed, give up old lock. */
if (nspid != oldnspid)
UnlockDatabaseObject(NamespaceRelationId, oldnspid, 0,
AccessShareLock);
/* If name points to something different, give up old lock. */
if (relid != oldrelid && OidIsValid(oldrelid) && lockmode != NoLock)
UnlockRelationOid(oldrelid, lockmode);
}
/* Lock namespace. */
if (nspid != oldnspid)
LockDatabaseObject(NamespaceRelationId, nspid, 0, AccessShareLock);
/* Lock relation, if required if and we have permission. */
if (lockmode != NoLock && OidIsValid(relid))
{
if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)),
relation->relname);
if (relid != oldrelid)
LockRelationOid(relid, lockmode);
}
/* If no invalidation message were processed, we're done! */
if (inval_count == SharedInvalidMessageCounter)
break;
/* Something may have changed, so recheck our work. */
retry = true;
oldrelid = relid;
oldnspid = nspid;
}
RangeVarAdjustRelationPersistence(relation, nspid);
if (existing_relation_id != NULL)
*existing_relation_id = relid;
return nspid;
}
/*
* Adjust the relpersistence for an about-to-be-created relation based on the
* creation namespace, and throw an error for invalid combinations.
*/
void
RangeVarAdjustRelationPersistence(RangeVar *newRelation, Oid nspid)
{
switch (newRelation->relpersistence)
{
case RELPERSISTENCE_TEMP:
if (!isTempOrTempToastNamespace(nspid))
{
if (isAnyTempNamespace(nspid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot create relations in temporary schemas of other sessions")));
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot create temporary relation in non-temporary schema")));
}
break;
case RELPERSISTENCE_PERMANENT:
if (isTempOrTempToastNamespace(nspid))
newRelation->relpersistence = RELPERSISTENCE_TEMP;
else if (isAnyTempNamespace(nspid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot create relations in temporary schemas of other sessions")));
break;
default:
if (isAnyTempNamespace(nspid))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("only temporary relations may be created in temporary schemas")));
}
}
/*
* RelnameGetRelid
* Try to resolve an unqualified relation name.
* Returns OID if relation found in search path, else InvalidOid.
*/
Oid
RelnameGetRelid(const char *relname)
{
Oid relid;
ListCell *l;
recomputeNamespacePath();
foreach(l, activeSearchPath)
{
Oid namespaceId = lfirst_oid(l);
relid = get_relname_relid(relname, namespaceId);
if (OidIsValid(relid))
return relid;
}
/* Not found in path */
return InvalidOid;
}
/*
* RelationIsVisible
* Determine whether a relation (identified by OID) is visible in the
* current search path. Visible means "would be found by searching
* for the unqualified relation name".
*/
bool
RelationIsVisible(Oid relid)
{
return RelationIsVisibleExt(relid, NULL);
}
/*
* RelationIsVisibleExt
* As above, but if the relation isn't found and is_missing is not NULL,
* then set *is_missing = true and return false instead of throwing
* an error. (Caller must initialize *is_missing = false.)
*/
static bool
RelationIsVisibleExt(Oid relid, bool *is_missing)
{
HeapTuple reltup;
Form_pg_class relform;
Oid relnamespace;
bool visible;
reltup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(reltup))
{
if (is_missing != NULL)
{
*is_missing = true;
return false;
}
elog(ERROR, "cache lookup failed for relation %u", relid);
}
relform = (Form_pg_class) GETSTRUCT(reltup);
recomputeNamespacePath();
/*
* Quick check: if it ain't in the path at all, it ain't visible. Items in
* the system namespace are surely in the path and so we needn't even do
* list_member_oid() for them.
*/
relnamespace = relform->relnamespace;
if (relnamespace != PG_CATALOG_NAMESPACE &&
!list_member_oid(activeSearchPath, relnamespace))
visible = false;
else
{
/*
* If it is in the path, it might still not be visible; it could be
* hidden by another relation of the same name earlier in the path. So
* we must do a slow check for conflicting relations.
*/
char *relname = NameStr(relform->relname);
ListCell *l;
visible = false;
foreach(l, activeSearchPath)
{
Oid namespaceId = lfirst_oid(l);
if (namespaceId == relnamespace)
{
/* Found it first in path */
visible = true;
break;
}
if (OidIsValid(get_relname_relid(relname, namespaceId)))
{
/* Found something else first in path */
break;
}
}
}
ReleaseSysCache(reltup);
return visible;
}
/*
* TypenameGetTypid
* Wrapper for binary compatibility.
*/
Oid
TypenameGetTypid(const char *typname)
{
return TypenameGetTypidExtended(typname, true);
}
/*