-
Notifications
You must be signed in to change notification settings - Fork 1k
/
pg_yb_utils.c
4742 lines (4225 loc) · 136 KB
/
pg_yb_utils.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
/*-------------------------------------------------------------------------
*
* pg_yb_utils.c
* Utilities for YugaByte/PostgreSQL integration that have to be defined on
* the PostgreSQL side.
*
* Copyright (c) YugaByte, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* IDENTIFICATION
* src/backend/utils/misc/pg_yb_utils.c
*
*-------------------------------------------------------------------------
*/
#include "pg_yb_utils.h"
#include <assert.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "access/tuptoaster.h"
#include "c.h"
#include "postgres.h"
#include "miscadmin.h"
#include "access/htup.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/tupdesc.h"
#include "access/xact.h"
#include "executor/ybcExpr.h"
#include "catalog/catalog.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/pg_am.h"
#include "catalog/pg_amop.h"
#include "catalog/pg_amproc.h"
#include "catalog/pg_attrdef.h"
#include "catalog/pg_auth_members.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_database.h"
#include "catalog/pg_db_role_setting.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_opclass.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_partitioned_table.h"
#include "catalog/pg_policy.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_range_d.h"
#include "catalog/pg_rewrite.h"
#include "catalog/pg_statistic_d.h"
#include "catalog/pg_tablespace.h"
#include "catalog/pg_trigger.h"
#include "catalog/pg_type.h"
#include "catalog/pg_yb_catalog_version.h"
#include "catalog/pg_yb_profile.h"
#include "catalog/pg_yb_role_profile.h"
#include "catalog/yb_catalog_version.h"
#include "catalog/yb_type.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/variable.h"
#include "commands/ybccmds.h"
#include "common/ip.h"
#include "common/pg_yb_common.h"
#include "lib/stringinfo.h"
#include "libpq/hba.h"
#include "libpq/libpq.h"
#include "libpq/libpq-be.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#include "parser/parse_utilcmd.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/pg_locale.h"
#include "utils/rel.h"
#include "utils/spccache.h"
#include "utils/syscache.h"
#include "utils/uuid.h"
#include "fmgr.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "yb/yql/pggate/util/ybc_util.h"
#include "yb/yql/pggate/ybc_pggate.h"
#include "pgstat.h"
#include "nodes/readfuncs.h"
#include "yb_ash.h"
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
static uint64_t yb_catalog_cache_version = YB_CATCACHE_VERSION_UNINITIALIZED;
static uint64_t yb_last_known_catalog_cache_version =
YB_CATCACHE_VERSION_UNINITIALIZED;
uint64_t YBGetActiveCatalogCacheVersion() {
if (yb_catalog_version_type == CATALOG_VERSION_CATALOG_TABLE &&
YBGetDdlNestingLevel() > 0)
return yb_catalog_cache_version + 1;
return yb_catalog_cache_version;
}
uint64_t
YbGetCatalogCacheVersion()
{
return yb_catalog_cache_version;
}
uint64_t
YbGetLastKnownCatalogCacheVersion()
{
const uint64_t shared_catalog_version = YbGetSharedCatalogVersion();
return shared_catalog_version > yb_last_known_catalog_cache_version ?
shared_catalog_version : yb_last_known_catalog_cache_version;
}
YBCPgLastKnownCatalogVersionInfo
YbGetCatalogCacheVersionForTablePrefetching()
{
// TODO: In future YBGetLastKnownCatalogCacheVersion must be used instead of
// YbGetMasterCatalogVersion to reduce numer of RPCs to a master.
// But this requires some additional changes. This optimization will
// be done separately.
uint64_t version = YB_CATCACHE_VERSION_UNINITIALIZED;
bool is_db_catalog_version_mode = YBIsDBCatalogVersionMode();
if (*YBCGetGFlags()->ysql_enable_read_request_caching)
{
YBCPgResetCatalogReadTime();
version = YbGetMasterCatalogVersion();
}
return (YBCPgLastKnownCatalogVersionInfo){
.version = version,
.is_db_catalog_version_mode = is_db_catalog_version_mode};
}
void
YbUpdateCatalogCacheVersion(uint64_t catalog_cache_version)
{
yb_catalog_cache_version = catalog_cache_version;
yb_pgstat_set_catalog_version(yb_catalog_cache_version);
YbUpdateLastKnownCatalogCacheVersion(yb_catalog_cache_version);
if (*YBCGetGFlags()->log_ysql_catalog_versions)
ereport(LOG,
(errmsg("set local catalog version: %" PRIu64,
yb_catalog_cache_version)));
}
void
YbUpdateLastKnownCatalogCacheVersion(uint64_t catalog_cache_version)
{
if (yb_last_known_catalog_cache_version < catalog_cache_version)
yb_last_known_catalog_cache_version = catalog_cache_version;
}
void
YbResetCatalogCacheVersion()
{
yb_catalog_cache_version = YB_CATCACHE_VERSION_UNINITIALIZED;
yb_pgstat_set_catalog_version(yb_catalog_cache_version);
}
/** These values are lazily initialized based on corresponding environment variables. */
int ybc_pg_double_write = -1;
int ybc_disable_pg_locking = -1;
/* Forward declarations */
static void YBCInstallTxnDdlHook();
static bool YBCanEnableDBCatalogVersionMode();
bool yb_enable_docdb_tracing = false;
bool yb_read_from_followers = false;
int32_t yb_follower_read_staleness_ms = 0;
bool
IsYugaByteEnabled()
{
/* We do not support Init/Bootstrap processing modes yet. */
return YBCPgIsYugaByteEnabled();
}
void
CheckIsYBSupportedRelation(Relation relation)
{
const char relkind = relation->rd_rel->relkind;
CheckIsYBSupportedRelationByKind(relkind);
}
void
CheckIsYBSupportedRelationByKind(char relkind)
{
if (!(relkind == RELKIND_RELATION || relkind == RELKIND_INDEX ||
relkind == RELKIND_VIEW || relkind == RELKIND_SEQUENCE ||
relkind == RELKIND_COMPOSITE_TYPE || relkind == RELKIND_PARTITIONED_TABLE ||
relkind == RELKIND_PARTITIONED_INDEX || relkind == RELKIND_FOREIGN_TABLE ||
relkind == RELKIND_MATVIEW))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("This feature is not supported in YugaByte.")));
}
bool
IsYBRelation(Relation relation)
{
/*
* NULL relation is possible if regular ForeignScan is confused for
* Yugabyte sequential scan, which is backed by ForeignScan, too.
* Rather than performing probably not trivial and unreliable checks by
* the caller to distinguish them, we allow NULL argument here.
*/
if (!IsYugaByteEnabled() || !relation)
return false;
const char relkind = relation->rd_rel->relkind;
CheckIsYBSupportedRelationByKind(relkind);
/* Currently only support regular tables and indexes.
* Temp tables and views are supported, but they are not YB relations. */
return (relkind == RELKIND_RELATION || relkind == RELKIND_INDEX || relkind == RELKIND_PARTITIONED_TABLE ||
relkind == RELKIND_PARTITIONED_INDEX || relkind == RELKIND_MATVIEW) &&
relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP;
}
bool
IsYBRelationById(Oid relid)
{
Relation relation = RelationIdGetRelation(relid);
bool is_supported = IsYBRelation(relation);
RelationClose(relation);
return is_supported;
}
bool
IsYBBackedRelation(Relation relation)
{
return IsYBRelation(relation) ||
(relation->rd_rel->relkind == RELKIND_VIEW &&
relation->rd_rel->relpersistence != RELPERSISTENCE_TEMP);
}
bool
YbIsTempRelation(Relation relation)
{
return relation->rd_rel->relpersistence == RELPERSISTENCE_TEMP;
}
bool IsRealYBColumn(Relation rel, int attrNum)
{
return (attrNum > 0 && !TupleDescAttr(rel->rd_att, attrNum - 1)->attisdropped) ||
(rel->rd_rel->relhasoids && attrNum == ObjectIdAttributeNumber);
}
bool IsYBSystemColumn(int attrNum)
{
return (attrNum == YBRowIdAttributeNumber ||
attrNum == YBIdxBaseTupleIdAttributeNumber ||
attrNum == YBUniqueIdxKeySuffixAttributeNumber);
}
AttrNumber YBGetFirstLowInvalidAttributeNumber(Relation relation)
{
return IsYBRelation(relation)
? YBFirstLowInvalidAttributeNumber
: FirstLowInvalidHeapAttributeNumber;
}
AttrNumber YBGetFirstLowInvalidAttributeNumberFromOid(Oid relid)
{
Relation relation = RelationIdGetRelation(relid);
AttrNumber attr_num = YBGetFirstLowInvalidAttributeNumber(relation);
RelationClose(relation);
return attr_num;
}
int YBAttnumToBmsIndex(Relation rel, AttrNumber attnum)
{
return YBAttnumToBmsIndexWithMinAttr(
YBGetFirstLowInvalidAttributeNumber(rel), attnum);
}
AttrNumber YBBmsIndexToAttnum(Relation rel, int idx)
{
return YBBmsIndexToAttnumWithMinAttr(
YBGetFirstLowInvalidAttributeNumber(rel), idx);
}
int YBAttnumToBmsIndexWithMinAttr(AttrNumber minattr, AttrNumber attnum)
{
return attnum - minattr + 1;
}
AttrNumber YBBmsIndexToAttnumWithMinAttr(AttrNumber minattr, int idx)
{
return idx + minattr - 1;
}
/*
* Get primary key columns as bitmap of a table,
* subtracting minattr from attributes.
*/
static Bitmapset *GetTablePrimaryKeyBms(Relation rel,
AttrNumber minattr,
bool includeYBSystemColumns)
{
Oid dboid = YBCGetDatabaseOid(rel);
int natts = RelationGetNumberOfAttributes(rel);
Bitmapset *pkey = NULL;
YBCPgTableDesc ybc_tabledesc = NULL;
MemoryContext oldctx;
/* Get the primary key columns 'pkey' from YugaByte. */
HandleYBStatus(YBCPgGetTableDesc(dboid, YbGetRelfileNodeId(rel),
&ybc_tabledesc));
oldctx = MemoryContextSwitchTo(CacheMemoryContext);
for (AttrNumber attnum = minattr; attnum <= natts; attnum++)
{
if ((!includeYBSystemColumns && !IsRealYBColumn(rel, attnum)) ||
(!IsRealYBColumn(rel, attnum) && !IsYBSystemColumn(attnum)))
{
continue;
}
YBCPgColumnInfo column_info = {0};
HandleYBTableDescStatus(YBCPgGetColumnInfo(ybc_tabledesc,
attnum,
&column_info),
ybc_tabledesc);
if (column_info.is_hash || column_info.is_primary)
{
pkey = bms_add_member(pkey, attnum - minattr);
}
}
MemoryContextSwitchTo(oldctx);
return pkey;
}
Bitmapset *YBGetTablePrimaryKeyBms(Relation rel)
{
if (!rel->primary_key_bms) {
rel->primary_key_bms = GetTablePrimaryKeyBms(
rel,
YBGetFirstLowInvalidAttributeNumber(rel) /* minattr */,
false /* includeYBSystemColumns */);
}
return rel->primary_key_bms;
}
Bitmapset *YBGetTableFullPrimaryKeyBms(Relation rel)
{
if (!rel->full_primary_key_bms) {
rel->full_primary_key_bms = GetTablePrimaryKeyBms(
rel,
YBSystemFirstLowInvalidAttributeNumber + 1 /* minattr */,
true /* includeYBSystemColumns */);
}
return rel->full_primary_key_bms;
}
extern bool YBRelHasOldRowTriggers(Relation rel, CmdType operation)
{
TriggerDesc *trigdesc = rel->trigdesc;
if (!trigdesc)
{
return false;
}
if (operation == CMD_DELETE)
{
return trigdesc->trig_delete_after_row ||
trigdesc->trig_delete_before_row;
}
if (operation != CMD_UPDATE)
{
return false;
}
if (rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
!rel->rd_rel->relispartition)
{
return trigdesc->trig_update_after_row ||
trigdesc->trig_update_before_row;
}
/*
* This is an update operation. We look for both update and delete triggers
* as update on partitioned tables can result in deletes as well.
*/
return trigdesc->trig_update_after_row ||
trigdesc->trig_update_before_row ||
trigdesc->trig_delete_after_row ||
trigdesc->trig_delete_before_row;
}
bool
YbIsDatabaseColocated(Oid dbid, bool *legacy_colocated_database)
{
bool colocated;
HandleYBStatus(YBCPgIsDatabaseColocated(dbid, &colocated,
legacy_colocated_database));
return colocated;
}
bool
YBRelHasSecondaryIndices(Relation relation)
{
if (!relation->rd_rel->relhasindex)
return false;
bool has_indices = false;
List *indexlist = RelationGetIndexList(relation);
ListCell *lc;
foreach(lc, indexlist)
{
if (lfirst_oid(lc) == relation->rd_pkindex)
continue;
has_indices = true;
break;
}
list_free(indexlist);
return has_indices;
}
bool
YBTransactionsEnabled()
{
static int cached_value = -1;
if (cached_value == -1)
{
cached_value = YBCIsEnvVarTrueWithDefault("YB_PG_TRANSACTIONS_ENABLED", true);
}
return IsYugaByteEnabled() && cached_value;
}
bool
YBIsReadCommittedSupported()
{
static int cached_value = -1;
if (cached_value == -1)
{
#ifdef NDEBUG
cached_value = YBCIsEnvVarTrueWithDefault("FLAGS_yb_enable_read_committed_isolation", false);
#else
cached_value = YBCIsEnvVarTrueWithDefault("FLAGS_yb_enable_read_committed_isolation", true);
#endif
}
return cached_value;
}
bool
IsYBReadCommitted()
{
return IsYugaByteEnabled() && YBIsReadCommittedSupported() &&
(XactIsoLevel == XACT_READ_COMMITTED || XactIsoLevel == XACT_READ_UNCOMMITTED);
}
bool
YBIsWaitQueueEnabled()
{
static int cached_value = -1;
if (cached_value == -1)
{
cached_value = YBCIsEnvVarTrueWithDefault("FLAGS_enable_wait_queues", true);
}
return IsYugaByteEnabled() && cached_value;
}
/*
* Return true if we are in per-database catalog version mode. In order to
* use per-database catalog version mode, two conditions must be met:
* * --FLAGS_ysql_enable_db_catalog_version_mode=true
* * the table pg_yb_catalog_version has one row per database.
* This function takes care of the YSQL upgrade from global catalog version
* mode to per-database catalog version mode when the default value of
* --FLAGS_ysql_enable_db_catalog_version_mode is changed to true. In this
* upgrade procedure --FLAGS_ysql_enable_db_catalog_version_mode is set to
* true before the table pg_yb_catalog_version is updated to have one row per
* database.
* This function does not consider going from per-database catalog version
* mode back to global catalog version mode.
*/
bool
YBIsDBCatalogVersionMode()
{
static bool cached_is_db_catalog_version_mode = false;
if (cached_is_db_catalog_version_mode)
return true;
/*
* During bootstrap phase in initdb, CATALOG_VERSION_PROTOBUF_ENTRY is used
* for catalog version type.
*/
if (!IsYugaByteEnabled() ||
YbGetCatalogVersionType() != CATALOG_VERSION_CATALOG_TABLE ||
!*YBCGetGFlags()->ysql_enable_db_catalog_version_mode)
return false;
/*
* During second phase of initdb, per-db catalog version mode is supported.
*/
if (YBCIsInitDbModeEnvVarSet())
{
cached_is_db_catalog_version_mode = true;
return true;
}
/*
* At this point, we know that FLAGS_ysql_enable_db_catalog_version_mode is
* turned on. However in case of YSQL upgrade we may not be ready to enable
* per-db catalog version mode yet. Note that we only provide support where
* we go from global catalog version mode to per-db catalog version mode,
* not for the opposite direction.
*/
if (YBCanEnableDBCatalogVersionMode())
{
cached_is_db_catalog_version_mode = true;
/*
* If MyDatabaseId is not resolved, the caller is going to set up the
* catalog version in per-database catalog version mode. There is
* no need to set it up here.
*/
if (OidIsValid(MyDatabaseId))
{
/*
* MyDatabaseId is already resolved so the caller may have already
* set up the catalog version in global catalog version mode. The
* upgrade of table pg_yb_catalog_version to per-database catalog
* version mode does not change the catalog version of database
* template1 but will set the initial per-database catalog version
* value to 1 for all other databases. Set catalog version to 1
* except for database template1 to avoid unnecessary catalog cache
* refresh.
* Note that we assume there are no DDL statements running during
* YSQL upgrade and in particular we do not support concurrent DDL
* statements when switching from global catalog version mode to
* per-database catalog version mode. As of 2023-08-07, this is not
* enforced and therefore if a concurrent DDL statement is executed:
* (1) if this DDL statement also increments a table schema, we still
* have the table schema version mismatch check as a safety net to
* reject stale read/write RPCs;
* (2) if this DDL statement only increments the catalog version,
* then stale read/write RPCs are possible which can lead to wrong
* results;
*/
elog(LOG, "change to per-db mode");
if (MyDatabaseId != TemplateDbOid)
{
yb_last_known_catalog_cache_version = 1;
YbUpdateCatalogCacheVersion(1);
}
}
/*
* YB does write operation buffering to reduce the number of RPCs.
* That is, PG backend can buffer several write operations and send
* them out in a single RPC. Here we dynamically switch from global
* catalog version mode to per-database catalog version mode, so
* flush the buffered write operations. Otherwise, we can end up
* having the first write operations in global catalog version mode,
* and the rest write operations in per-database catalog version.
* Mixing global and per-database catalog versions in a single RPC
* triggers a tserver SCHECK failure.
*/
YBFlushBufferedOperations();
return true;
}
/* We cannot enable per-db catalog version mode yet. */
return false;
}
static bool
YBCanEnableDBCatalogVersionMode()
{
/*
* Even when FLAGS_ysql_enable_db_catalog_version_mode is turned on we
* cannot simply enable per-database catalog mode if the table
* pg_yb_catalog_version does not have one row for each database.
* Consider YSQL upgrade, it happens after cluster software upgrade and
* can take time. During YSQL upgrade we need to wait until the
* pg_yb_catalog_version table is updated to have one row per database.
* In addition, we do not want to switch to per-database catalog version
* mode at any moment to prevent the following case:
*
* (1) At time t1, pg_yb_catalog_version is prefetched and there is only
* one row in the table because the table has not been upgraded yet.
* (2) At time t2 > t1, pg_yb_catalog_version is transactionally upgraded
* to have one row per database.
* (3) At time t3 > t2, assume that we already switched to per-database
* catalog version mode, then we will try to find the row of MyDatabaseId
* from the pg_yb_catalog_version data prefetched in step (1). That row
* would not exist because at time t1 pg_yb_catalog_version only had one
* row for template1. This is going to cause a user visible exception.
*
* Therefore after the pg_yb_catalog_version is upgraded, we may continue
* to remain on global catalog version mode until we are not doing
* prefetching.
*/
if (YBCIsSysTablePrefetchingStarted())
return false;
if (yb_test_stay_in_global_catalog_version_mode)
return false;
/*
* We assume that the table pg_yb_catalog_version has either exactly
* one row in global catalog version mode, or one row per database in
* per-database catalog version mode. It is unexpected if it has more
* than one rows but not exactly one row per database. During YSQL
* upgrade, the pg_yb_catalog_version is transactionally updated
* to have one row per database.
*/
return YbCatalogVersionTableInPerdbMode();
}
/*
* Used to determine whether we should preload certain catalog tables.
*/
bool YbNeedAdditionalCatalogTables()
{
return *YBCGetGFlags()->ysql_catalog_preload_additional_tables ||
IS_NON_EMPTY_STR_FLAG(YBCGetGFlags()->ysql_catalog_preload_additional_table_list);
}
void
YBReportFeatureUnsupported(const char *msg)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("%s", msg)));
}
static const char*
FetchUniqueConstraintName(Oid relation_id)
{
const char* name = NULL;
Relation rel = RelationIdGetRelation(relation_id);
if (!rel->rd_index && rel->rd_pkindex != InvalidOid)
{
Relation pkey = RelationIdGetRelation(rel->rd_pkindex);
name = pstrdup(RelationGetRelationName(pkey));
RelationClose(pkey);
}
else
name = pstrdup(RelationGetRelationName(rel));
RelationClose(rel);
return name;
}
/*
* GetStatusMsgAndArgumentsByCode - get error message arguments out of the
* status codes
*
* We already have cases when DocDB returns status with SQL code and
* relation Oid, but without error message, assuming the message is generated
* on Postgres side, with relation name retrieved by Oid. We have to keep
* the functionality for backward compatibility.
*
* Same approach can be used for similar cases, when status is originated from
* DocDB: by known SQL code the function may set or amend the error message and
* message arguments.
*/
void
GetStatusMsgAndArgumentsByCode(const uint32_t pg_err_code,
uint16_t txn_err_code, YBCStatus s,
const char **msg_buf, size_t *msg_nargs,
const char ***msg_args, const char **detail_buf,
size_t *detail_nargs, const char ***detail_args)
{
const char *status_msg = YBCMessageAsCString(s);
size_t status_nargs;
const char **status_args = YBCStatusArguments(s, &status_nargs);
// Initialize message and detail buffers with default values
*msg_buf = status_msg;
*msg_nargs = status_nargs;
*msg_args = status_args;
*detail_buf = NULL;
*detail_nargs = 0;
*detail_args = NULL;
switch(pg_err_code)
{
case ERRCODE_T_R_SERIALIZATION_FAILURE:
if(YBCIsTxnConflictError(txn_err_code))
{
*msg_buf = "could not serialize access due to concurrent update";
*msg_nargs = 0;
*msg_args = NULL;
*detail_buf = status_msg;
*detail_nargs = status_nargs;
*detail_args = status_args;
}
else if(YBCIsTxnAbortedError(txn_err_code))
{
*msg_buf = "current transaction is expired or aborted";
*msg_nargs = 0;
*msg_args = NULL;
*detail_buf = status_msg;
*detail_nargs = status_nargs;
*detail_args = status_args;
}
break;
case ERRCODE_UNIQUE_VIOLATION:
*msg_buf = "duplicate key value violates unique constraint \"%s\"";
*msg_nargs = 1;
*msg_args = (const char **) palloc(sizeof(const char *));
(*msg_args)[0] = FetchUniqueConstraintName(YBCStatusRelationOid(s));
break;
case ERRCODE_T_R_DEADLOCK_DETECTED:
if (YBCIsTxnDeadlockError(txn_err_code)) {
*msg_buf = "deadlock detected";
*msg_nargs = 0;
*msg_args = NULL;
*detail_buf = status_msg;
*detail_nargs = status_nargs;
*detail_args = status_args;
}
break;
default:
break;
}
}
void
HandleYBStatusIgnoreNotFound(YBCStatus status, bool *not_found)
{
if (!status)
return;
if (YBCStatusIsNotFound(status))
{
*not_found = true;
YBCFreeStatus(status);
return;
}
*not_found = false;
HandleYBStatus(status);
}
void
HandleYBStatusWithCustomErrorForNotFound(YBCStatus status,
const char *message_for_not_found)
{
bool not_found = false;
HandleYBStatusIgnoreNotFound(status, ¬_found);
if (not_found)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("%s", message_for_not_found)));
}
void
HandleYBTableDescStatus(YBCStatus status, YBCPgTableDesc table)
{
if (!status)
return;
HandleYBStatus(status);
}
static const char*
GetDebugQueryString()
{
return debug_query_string;
}
/*
* Ensure we've defined the correct postgres Oid values. This function only
* contains compile-time assertions. It would have been made 'static' but it is
* not called anywhere and making it 'static' caused compiler warning which
* broke the build.
*/
void
YBCheckDefinedOids()
{
static_assert(kInvalidOid == InvalidOid, "Oid mismatch");
static_assert(kByteArrayOid == BYTEAOID, "Oid mismatch");
}
/*
* Holds the RPC/Storage execution stats for the session. A handle to this
* struct is passed down to pggate which record updates to the stats as they
* happen. This model helps avoid making copies of the stats and passing it
* back/forth.
*/
typedef struct YbSessionStats
{
YBCPgExecStatsState current_state;
YBCPgExecStats latest_snapshot;
} YbSessionStats;
static YbSessionStats yb_session_stats = {0};
void
YBInitPostgresBackend(
const char *program_name,
const char *db_name,
const char *user_name,
uint64_t *session_id)
{
HandleYBStatus(YBCInit(program_name, palloc, cstring_to_text_with_len));
/*
* Enable "YB mode" for PostgreSQL so that we will initiate a connection
* to the YugaByte cluster right away from every backend process. We only
* do this if this env variable is set, so we can still run the regular
* PostgreSQL "make check".
*/
if (YBIsEnabledInPostgresEnvVar())
{
const YBCPgTypeEntity *type_table;
int count;
YbGetTypeTable(&type_table, &count);
YBCPgCallbacks callbacks;
callbacks.GetCurrentYbMemctx = &GetCurrentYbMemctx;
callbacks.GetDebugQueryString = &GetDebugQueryString;
callbacks.WriteExecOutParam = &YbWriteExecOutParam;
callbacks.UnixEpochToPostgresEpoch = &YbUnixEpochToPostgresEpoch;
callbacks.ConstructArrayDatum = &YbConstructArrayDatum;
callbacks.CheckUserMap = &check_usermap;
callbacks.PgstatReportWaitStart = &yb_pgstat_report_wait_start;
YBCPgAshConfig ash_config;
ash_config.metadata = &MyProc->yb_ash_metadata;
ash_config.is_metadata_set = &MyProc->yb_is_ash_metadata_set;
ash_config.yb_enable_ash = &yb_enable_ash;
YBCInitPgGate(type_table, count, callbacks, session_id, &ash_config);
YBCInstallTxnDdlHook();
if (yb_ash_enable_infra)
YbAshInstallHooks();
/*
* For each process, we create one YBC session for PostgreSQL to use
* when accessing YugaByte storage.
*
* TODO: do we really need to DB name / username here?
*/
HandleYBStatus(YBCPgInitSession(db_name ? db_name : user_name,
&yb_session_stats.current_state));
YBCSetTimeout(StatementTimeout, NULL);
/*
* Upon completion of the first heartbeat to the local tserver, retrieve
* and store the session ID in shared memory, so that entities
* associated with a session ID (like txn IDs) can be transitively
* mapped to PG backends.
*/
yb_pgstat_add_session_info(YBCPgGetSessionID());
if (yb_ash_enable_infra)
YbAshSetSessionId(YBCPgGetSessionID());
}
}
void
YBOnPostgresBackendShutdown()
{
YBCDestroyPgGate();
}
void
YBCRecreateTransaction()
{
if (!IsYugaByteEnabled())
return;
HandleYBStatus(YBCPgRecreateTransaction());
}
void
YBCRestartTransaction()
{
if (!IsYugaByteEnabled())
return;
HandleYBStatus(YBCPgRestartTransaction());
}
void
YBCCommitTransaction()
{
if (!IsYugaByteEnabled())
return;
HandleYBStatus(YBCPgCommitTransaction());
}
void
YBCAbortTransaction()
{
if (!IsYugaByteEnabled())
return;
if (YBTransactionsEnabled())
HandleYBStatus(YBCPgAbortTransaction());
}
void
YBCSetActiveSubTransaction(SubTransactionId id)
{
HandleYBStatus(YBCPgSetActiveSubTransaction(id));
}
void
YBCRollbackToSubTransaction(SubTransactionId id)
{
HandleYBStatus(YBCPgRollbackToSubTransaction(id));
}
bool
YBIsPgLockingEnabled()
{
return !YBTransactionsEnabled();
}
static bool yb_connected_to_template_db = false;
void
YbSetConnectedToTemplateDb()
{
yb_connected_to_template_db = true;
}
bool
YbIsConnectedToTemplateDb()
{
return yb_connected_to_template_db;
}
Oid
GetTypeId(int attrNum, TupleDesc tupleDesc)
{
switch (attrNum)
{
case SelfItemPointerAttributeNumber:
return TIDOID;
case ObjectIdAttributeNumber:
return OIDOID;
case MinTransactionIdAttributeNumber:
return XIDOID;
case MinCommandIdAttributeNumber:
return CIDOID;
case MaxTransactionIdAttributeNumber:
return XIDOID;
case MaxCommandIdAttributeNumber:
return CIDOID;
case TableOidAttributeNumber:
return OIDOID;
default:
if (attrNum > 0 && attrNum <= tupleDesc->natts)
return TupleDescAttr(tupleDesc, attrNum - 1)->atttypid;
else
return InvalidOid;
}
}
const char*
YBPgTypeOidToStr(Oid type_id) {
switch (type_id) {
case BOOLOID: return "BOOL";
case BYTEAOID: return "BYTEA";
case CHAROID: return "CHAR";
case NAMEOID: return "NAME";
case INT8OID: return "INT8";
case INT2OID: return "INT2";