forked from apache/cloudberry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaocsam_handler.c
More file actions
2498 lines (2136 loc) · 71.3 KB
/
aocsam_handler.c
File metadata and controls
2498 lines (2136 loc) · 71.3 KB
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
/*--------------------------------------------------------------------------
*
* aocsam_handler.c
* Append only columnar access methods handler
*
* Portions Copyright (c) 2023, HashData Technology Limited.
* Portions Copyright (c) 2009-2010, Greenplum Inc.
* Portions Copyright (c) 2012-Present VMware, Inc. or its affiliates.
*
*
* IDENTIFICATION
* src/backend/access/aocs/aocsam_handler.c
*
*--------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/aomd.h"
#include "access/appendonlywriter.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/tableam.h"
#include "access/tsmapi.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/heap.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_appendonly.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "cdb/cdbaocsam.h"
#include "cdb/cdbvars.h"
#include "commands/defrem.h"
#include "commands/progress.h"
#include "commands/vacuum.h"
#include "executor/executor.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "pgstat.h"
#include "storage/lmgr.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/faultinjector.h"
#include "utils/lsyscache.h"
#include "utils/pg_rusage.h"
#include "utils/guc.h"
#define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID)
extern BlockNumber system_nextsampleblock(SampleScanState *node, BlockNumber nblocks);
/*
* Used for bitmapHeapScan. Also look at the comment in cdbaocsam.h regarding
* AOCSScanDescIdentifier.
*
* In BitmapHeapScans, it is needed to keep track of two distict fetch
* descriptors. One for direct fetches, and another one for recheck fetches. The
* distinction allows for a different set of columns to be populated in each
* case. During initialiazation of this structure, it is required to populate
* the proj array accordingly. It is later, during the actual fetching of the
* tuple, that the corresponding fetch descriptor will be lazily initialized.
*
* Finally, in this struct, state between next_block and next_tuple calls is
* kept, in order to minimize the work that is done in the latter.
*/
typedef struct AOCSBitmapScanData
{
TableScanDescData rs_base; /* AM independent part of the descriptor */
enum AOCSScanDescIdentifier descIdentifier;
Snapshot appendOnlyMetaDataSnapshot;
enum
{
NO_RECHECK,
RECHECK
} whichDesc;
struct {
struct AOCSFetchDescData *bitmapFetch;
bool *proj;
} bitmapScanDesc[2];
int rs_cindex; /* current tuple's index tbmres->offset or -1 */
} *AOCSBitmapScan;
typedef struct AOCODMLState
{
Oid relationOid;
AOCSInsertDesc insertDesc;
AOCSDeleteDesc deleteDesc;
AOCSUniqueCheckDesc uniqueCheckDesc;
/*
* CBDB_PARALLEL
* head: the Head of multiple segment files insertion list.
* insertMultiFiles: number of seg files to be inserted into.
* used_segment_files: used to avoid used files when asking
* for a new segment file.
*/
dlist_head head;
int insertMultiFiles;
List* used_segment_files;
} AOCODMLState;
static void reset_state_cb(void *arg);
/*
* GPDB_12_MERGE_FIXME: This is a temporary state of things. A locally stored
* state is needed currently because there is no viable place to store this
* information outside of the table access method. Ideally the caller should be
* responsible for initializing a state and passing it over using the table
* access method api.
*
* Until this is in place, the local state is not to be accessed directly but
* only via the *_dml_state functions.
* It contains:
* a quick look up member for the common case
* a hash table which keeps per relation information
* a memory context that should be long lived enough and is
* responsible for reseting the state via its reset cb
*/
static struct AOCOLocal
{
AOCODMLState *last_used_state;
HTAB *dmlDescriptorTab;
MemoryContext stateCxt;
MemoryContextCallback cb;
} aocoLocal = {
.last_used_state = NULL,
.dmlDescriptorTab = NULL,
.stateCxt = NULL,
.cb = {
.func = reset_state_cb,
.arg = NULL
},
};
/*
* There are two cases that we are called from, during context destruction
* after a successful completion and after a transaction abort. Only in the
* second case we should not have cleaned up the DML state and the entries in
* the hash table. We need to reset our global state. The actual clean up is
* taken care elsewhere.
*/
static void
reset_state_cb(void *arg)
{
aocoLocal.dmlDescriptorTab = NULL;
aocoLocal.last_used_state = NULL;
aocoLocal.stateCxt = NULL;
}
static void
init_dml_local_state(void)
{
HASHCTL hash_ctl;
if (!aocoLocal.dmlDescriptorTab)
{
Assert(aocoLocal.stateCxt == NULL);
aocoLocal.stateCxt = AllocSetContextCreate(
CurrentMemoryContext,
"AppendOnly DML State Context",
ALLOCSET_SMALL_SIZES);
MemoryContextRegisterResetCallback(
aocoLocal.stateCxt,
&aocoLocal.cb);
memset(&hash_ctl, 0, sizeof(hash_ctl));
hash_ctl.keysize = sizeof(Oid);
hash_ctl.entrysize = sizeof(AOCODMLState);
hash_ctl.hcxt = aocoLocal.stateCxt;
aocoLocal.dmlDescriptorTab =
hash_create("AppendOnly DML state", 128, &hash_ctl,
HASH_CONTEXT | HASH_ELEM | HASH_BLOBS);
}
}
/*
* Create and insert a state entry for a relation. The actual descriptors will
* be created lazily when/if needed.
*
* Should be called exactly once per relation.
*/
static inline AOCODMLState *
enter_dml_state(const Oid relationOid)
{
AOCODMLState *state;
bool found;
Assert(aocoLocal.dmlDescriptorTab);
state = (AOCODMLState *) hash_search(
aocoLocal.dmlDescriptorTab,
&relationOid,
HASH_ENTER,
&found);
state->insertDesc = NULL;
state->deleteDesc = NULL;
state->uniqueCheckDesc = NULL;
state->insertMultiFiles = 0;
state->used_segment_files = NIL;
dlist_init(&state->head);
Assert(!found);
aocoLocal.last_used_state = state;
return state;
}
/*
* Retrieve the state information for a relation.
* It is required that the state has been created before hand.
*/
static inline AOCODMLState *
find_dml_state(const Oid relationOid)
{
AOCODMLState *state;
Assert(aocoLocal.dmlDescriptorTab);
if (aocoLocal.last_used_state &&
aocoLocal.last_used_state->relationOid == relationOid)
return aocoLocal.last_used_state;
state = (AOCODMLState *) hash_search(
aocoLocal.dmlDescriptorTab,
&relationOid,
HASH_FIND,
NULL);
Assert(state);
aocoLocal.last_used_state = state;
return state;
}
/*
* Remove the state information for a relation.
* It is required that the state has been created before hand.
*
* Should be called exactly once per relation.
*/
static inline AOCODMLState *
remove_dml_state(const Oid relationOid)
{
AOCODMLState *state;
Assert(aocoLocal.dmlDescriptorTab);
state = (AOCODMLState *) hash_search(
aocoLocal.dmlDescriptorTab,
&relationOid,
HASH_REMOVE,
NULL);
if (!state)
return NULL;
if (aocoLocal.last_used_state &&
aocoLocal.last_used_state->relationOid == relationOid)
aocoLocal.last_used_state = NULL;
return state;
}
/*
* Although the operation param is superfluous at the momment, the signature of
* the function is such for balance between the init and finish.
*
* This function should be called exactly once per relation.
*/
void
aoco_dml_init(Relation relation, CmdType operation)
{
init_dml_local_state();
(void) enter_dml_state(RelationGetRelid(relation));
}
/*
* This function should be called exactly once per relation.
*/
void
aoco_dml_finish(Relation relation, CmdType operation)
{
AOCODMLState *state;
bool had_delete_desc = false;
state = remove_dml_state(RelationGetRelid(relation));
if (!state)
return;
if (state->deleteDesc)
{
aocs_delete_finish(state->deleteDesc);
state->deleteDesc = NULL;
/*
* Bump up the modcount. If we inserted something (meaning that
* this was an UPDATE), we can skip this, as the insertion bumped
* up the modcount already.
*/
if (!state->insertDesc)
AORelIncrementModCount(relation);
had_delete_desc = true;
}
if (state->insertDesc)
{
Assert(state->insertDesc->aoi_rel == relation);
aocs_insert_finish(state->insertDesc, &state->head);
state->insertDesc = NULL;
state->insertMultiFiles = 0;
pfree(state->used_segment_files);
state->used_segment_files = NIL;
}
if (state->uniqueCheckDesc)
{
/* clean up the block directory */
AppendOnlyBlockDirectory_End_forUniqueChecks(state->uniqueCheckDesc->blockDirectory);
pfree(state->uniqueCheckDesc->blockDirectory);
state->uniqueCheckDesc->blockDirectory = NULL;
/*
* If this fetch is a part of an UPDATE, then we have been reusing the
* visimapDelete used by the delete half of the UPDATE, which would have
* already been cleaned up above. Clean up otherwise.
*/
if (!had_delete_desc)
{
AppendOnlyVisimap_Finish_forUniquenessChecks(state->uniqueCheckDesc->visimap);
pfree(state->uniqueCheckDesc->visimap);
}
state->uniqueCheckDesc->visimap = NULL;
state->uniqueCheckDesc->visiMapDelete = NULL;
pfree(state->uniqueCheckDesc);
state->uniqueCheckDesc = NULL;
}
}
/*
* Retrieve the insertDescriptor for a relation. Initialize it if needed.
*/
static AOCSInsertDesc
get_insert_descriptor(const Relation relation)
{
AOCODMLState *state;
AOCSInsertDesc next = NULL;
MemoryContext oldcxt;
state = find_dml_state(RelationGetRelid(relation));
oldcxt = MemoryContextSwitchTo(aocoLocal.stateCxt);
if (state->insertDesc == NULL)
{
/*
* CBDB_PARALLEL:
* Should not enable insertMultiFiles if the table is created by own transaction
* or in utility mode.
*/
if (Gp_role != GP_ROLE_UTILITY &&
gp_appendonly_insert_files > 1 &&
!ShouldUseReservedSegno(relation, CHOOSE_MODE_WRITE))
state->insertMultiFiles = gp_appendonly_insert_files;
state->insertDesc = aocs_insert_init(relation,
ChooseSegnoForWrite(relation));
state->used_segment_files = list_make1_int(state->insertDesc->cur_segno);
dlist_init(&state->head);
dlist_push_tail(&state->head, &state->insertDesc->node);
}
/* switch insertDesc */
if (state->insertMultiFiles && state->insertDesc->range == gp_appendonly_insert_files_tuples_range)
{
state->insertDesc->range = 0;
if (list_length(state->used_segment_files) < state->insertMultiFiles)
{
next = aocs_insert_init(relation, ChooseSegnoForWriteMultiFile(relation, state->used_segment_files));
dlist_push_tail(&state->head, &next->node);
state->used_segment_files = lappend_int(state->used_segment_files, next->cur_segno);
}
if (!dlist_has_next(&state->head, &state->insertDesc->node))
next = (AOCSInsertDesc)dlist_container(AOCSInsertDescData, node, dlist_head_node(&state->head));
else
next = (AOCSInsertDesc)dlist_container(AOCSInsertDescData, node, dlist_next_node(&state->head, &state->insertDesc->node));
state->insertDesc = next;
}
/*
* If we have a unique index, insert a placeholder block directory row to
* entertain uniqueness checks from concurrent inserts. See
* AppendOnlyBlockDirectory_InsertPlaceholder() for details.
*
* Note: For AOCO tables, we need to only insert a placeholder block
* directory row for the 1st non-dropped column. This is because
* during a uniqueness check, only the first non-dropped column's block
* directory entry is consulted. (See AppendOnlyBlockDirectory_CoversTuple())
*/
if (relationHasUniqueIndex(relation) && !state->insertDesc->placeholderInserted)
{
int firstNonDroppedColumn = -1;
int64 firstRowNum;
DatumStreamWrite *dsw;
BufferedAppend *bufferedAppend;
int64 fileOffset;
AOCSInsertDesc insertDesc;
for(int i = 0; i < relation->rd_att->natts; i++)
{
if (!relation->rd_att->attrs[i].attisdropped) {
firstNonDroppedColumn = i;
break;
}
}
Assert(firstNonDroppedColumn != -1);
insertDesc = state->insertDesc;
dsw = insertDesc->ds[firstNonDroppedColumn];
firstRowNum = dsw->blockFirstRowNum;
bufferedAppend = &dsw->ao_write.bufferedAppend;
fileOffset = BufferedAppendNextBufferPosition(bufferedAppend);
AppendOnlyBlockDirectory_InsertPlaceholder(&insertDesc->blockDirectory,
firstRowNum,
fileOffset,
firstNonDroppedColumn);
insertDesc->placeholderInserted = true;
}
MemoryContextSwitchTo(oldcxt);
return state->insertDesc;
}
/*
* Retrieve the deleteDescriptor for a relation. Initialize it if needed.
*/
static AOCSDeleteDesc
get_delete_descriptor(const Relation relation, bool forUpdate)
{
AOCODMLState *state;
state = find_dml_state(RelationGetRelid(relation));
if (state->deleteDesc == NULL)
{
/*
* GPDB_12_MERGE_FIXME: Can we perform this check earlier on?
* Example during init? Idealy should be called on master node first,
* that way we will avoid the dispatch.
*/
MemoryContext oldcxt;
if (IsolationUsesXactSnapshot())
{
if (forUpdate)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("updates on append-only tables are not supported in serializable transactions")));
else
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("deletes on append-only tables are not supported in serializable transactions")));
}
oldcxt = MemoryContextSwitchTo(aocoLocal.stateCxt);
state->deleteDesc = aocs_delete_init(relation);
MemoryContextSwitchTo(oldcxt);
}
return state->deleteDesc;
}
static AOCSUniqueCheckDesc
get_or_create_unique_check_desc(Relation relation, Snapshot snapshot)
{
AOCODMLState *state = find_dml_state(RelationGetRelid(relation));
if (!state->uniqueCheckDesc)
{
MemoryContext oldcxt;
AOCSUniqueCheckDesc uniqueCheckDesc;
oldcxt = MemoryContextSwitchTo(aocoLocal.stateCxt);
uniqueCheckDesc = palloc0(sizeof(AOCSUniqueCheckDescData));
/* Initialize the block directory */
uniqueCheckDesc->blockDirectory = palloc0(sizeof(AppendOnlyBlockDirectory));
AppendOnlyBlockDirectory_Init_forUniqueChecks(uniqueCheckDesc->blockDirectory,
relation,
relation->rd_att->natts, /* numColGroups */
snapshot);
/*
* If this is part of an UPDATE, we need to reuse the visimapDelete
* support structure from the delete half of the update. This is to
* avoid spurious conflicts when the key's previous and new value are
* identical. Using it ensures that we can recognize any tuples deleted
* by us prior to this insert, within this command.
*
* Note: It is important that we reuse the visimapDelete structure and
* not the visimap structure. This is because, when a uniqueness check
* is performed as part of an UPDATE, visimap changes aren't persisted
* yet (they are persisted at dml_finish() time, see
* AppendOnlyVisimapDelete_Finish()). So, if we use the visimap
* structure, we would not necessarily see all the changes.
*/
if (state->deleteDesc)
{
uniqueCheckDesc->visiMapDelete = &state->deleteDesc->visiMapDelete;
uniqueCheckDesc->visimap = NULL;
}
else
{
/* COPY/INSERT: Initialize the visimap */
uniqueCheckDesc->visimap = palloc0(sizeof(AppendOnlyVisimap));
AppendOnlyVisimap_Init_forUniqueCheck(uniqueCheckDesc->visimap,
relation,
snapshot);
}
state->uniqueCheckDesc = uniqueCheckDesc;
MemoryContextSwitchTo(oldcxt);
}
return state->uniqueCheckDesc;
}
/*
* AO_COLUMN access method uses virtual tuples
*/
static const TupleTableSlotOps *
aoco_slot_callbacks(Relation relation)
{
return &TTSOpsVirtual;
}
struct ExtractcolumnContext
{
bool *cols;
AttrNumber natts;
bool found;
};
static bool
extractcolumns_walker(Node *node, struct ExtractcolumnContext *ecCtx)
{
if (node == NULL)
return false;
if (IsA(node, Var))
{
Var *var = (Var *)node;
if (IS_SPECIAL_VARNO(var->varno))
return false;
if (var->varattno > 0 && var->varattno <= ecCtx->natts)
{
ecCtx->cols[var->varattno -1] = true;
ecCtx->found = true;
}
/*
* If all attributes are included,
* set all entries in mask to true.
*/
else if (var->varattno == 0)
{
for (AttrNumber attno = 0; attno < ecCtx->natts; attno++)
ecCtx->cols[attno] = true;
ecCtx->found = true;
return true;
}
return false;
}
return expression_tree_walker(node, extractcolumns_walker, (void *)ecCtx);
}
bool
extractcolumns_from_node(Node *expr, bool *cols, AttrNumber natts)
{
struct ExtractcolumnContext ecCtx;
ecCtx.cols = cols;
ecCtx.natts = natts;
ecCtx.found = false;
extractcolumns_walker(expr, &ecCtx);
return ecCtx.found;
}
static TableScanDesc
aoco_beginscan_extractcolumns(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key,
ParallelTableScanDesc parallel_scan,
PlanState *ps, uint32 flags)
{
AOCSScanDesc aoscan;
AttrNumber natts = RelationGetNumberOfAttributes(rel);
List *targetlist = ps->plan->targetlist;
List *qual = ps->plan->qual;
bool *cols;
bool found = false;
cols = palloc0((natts + 1) * sizeof(*cols));
found |= extractcolumns_from_node((Node *)targetlist, cols, natts);
found |= extractcolumns_from_node((Node *)qual, cols, natts);
/*
* In some cases (for example, count(*)), targetlist and qual may be null,
* extractcolumns_walker will return immediately, so no columns are specified.
* We always scan the first column.
*/
if (!found)
cols[0] = true;
aoscan = aocs_beginscan(rel,
snapshot,
parallel_scan,
cols,
flags);
pfree(cols);
if (gp_enable_predicate_pushdown)
ps->qual = aocs_predicate_pushdown_prepare(aoscan, qual, ps->qual, ps->ps_ExprContext, ps);
return (TableScanDesc)aoscan;
}
static TableScanDesc
aoco_beginscan_extractcolumns_bm(Relation rel, Snapshot snapshot,
List *targetlist, List *qual,
List *bitmapqualorig,
uint32 flags)
{
AOCSBitmapScan aocsBitmapScan;
AttrNumber natts = RelationGetNumberOfAttributes(rel);
bool *proj;
bool *projRecheck;
bool found;
aocsBitmapScan = palloc0(sizeof(*aocsBitmapScan));
aocsBitmapScan->descIdentifier = AOCSBITMAPSCANDATA;
aocsBitmapScan->rs_base.rs_rd = rel;
aocsBitmapScan->rs_base.rs_snapshot = snapshot;
aocsBitmapScan->rs_base.rs_flags = flags;
proj = palloc0(natts * sizeof(*proj));
projRecheck = palloc0(natts * sizeof(*projRecheck));
if (snapshot == SnapshotAny)
aocsBitmapScan->appendOnlyMetaDataSnapshot = GetTransactionSnapshot();
else
aocsBitmapScan->appendOnlyMetaDataSnapshot = snapshot;
found = extractcolumns_from_node((Node *)targetlist, proj, natts);
found |= extractcolumns_from_node((Node *)qual, proj, natts);
memcpy(projRecheck, proj, natts * sizeof(*projRecheck));
if (extractcolumns_from_node((Node *)bitmapqualorig, projRecheck, natts))
{
/*
* At least one column needs to be projected in non-recheck case.
* Otherwise, the AO_COLUMN fetch code may skip visimap checking because
* there are no columns to be scanned and we may get wrong results.
*/
if (!found)
proj[0] = true;
}
else if (!found)
{
/* XXX can we have no columns to project at all? */
proj[0] = projRecheck[0] = true;
}
aocsBitmapScan->bitmapScanDesc[NO_RECHECK].proj = proj;
aocsBitmapScan->bitmapScanDesc[RECHECK].proj = projRecheck;
return (TableScanDesc)aocsBitmapScan;
}
/*
* This function intentionally ignores key and nkeys
*/
static TableScanDesc
aoco_beginscan(Relation relation,
Snapshot snapshot,
int nkeys, struct ScanKeyData *key,
ParallelTableScanDesc pscan,
uint32 flags)
{
AOCSScanDesc aoscan;
aoscan = aocs_beginscan(relation,
snapshot,
pscan,
NULL,
flags);
return (TableScanDesc) aoscan;
}
static void
aoco_endscan(TableScanDesc scan)
{
AOCSScanDesc aocsScanDesc;
AOCSBitmapScan aocsBitmapScan;
aocsScanDesc = (AOCSScanDesc) scan;
if (aocsScanDesc->descIdentifier == AOCSSCANDESCDATA)
{
aocs_endscan(aocsScanDesc);
return;
}
Assert(aocsScanDesc->descIdentifier == AOCSBITMAPSCANDATA);
aocsBitmapScan = (AOCSBitmapScan) scan;
if (aocsBitmapScan->bitmapScanDesc[NO_RECHECK].bitmapFetch)
aocs_fetch_finish(aocsBitmapScan->bitmapScanDesc[NO_RECHECK].bitmapFetch);
if (aocsBitmapScan->bitmapScanDesc[RECHECK].bitmapFetch)
aocs_fetch_finish(aocsBitmapScan->bitmapScanDesc[RECHECK].bitmapFetch);
pfree(aocsBitmapScan->bitmapScanDesc[NO_RECHECK].proj);
pfree(aocsBitmapScan->bitmapScanDesc[RECHECK].proj);
}
static void
aoco_rescan(TableScanDesc scan, ScanKey key,
bool set_params, bool allow_strat,
bool allow_sync, bool allow_pagemode)
{
AOCSScanDesc aoscan = (AOCSScanDesc) scan;
if (aoscan->descIdentifier == AOCSSCANDESCDATA)
aocs_rescan(aoscan);
}
static bool
aoco_getnextslot(TableScanDesc scan, ScanDirection direction, TupleTableSlot *slot)
{
AOCSScanDesc aoscan = (AOCSScanDesc)scan;
ExecClearTuple(slot);
if (aocs_getnext(aoscan, direction, slot))
{
ExecStoreVirtualTuple(slot);
pgstat_count_heap_getnext(aoscan->rs_base.rs_rd);
return true;
}
return false;
}
static uint32
aoco_scan_flags(Relation rel)
{
return SCAN_SUPPORT_COLUMN_ORIENTED_SCAN;
}
static Size
aoco_parallelscan_estimate(Relation rel)
{
return sizeof(ParallelBlockTableScanDescData);
}
/*
* AOCO only uses part fields of ParallelBlockTableScanDesc.
*/
static Size
aoco_parallelscan_initialize(Relation rel, ParallelTableScanDesc pscan)
{
ParallelBlockTableScanDesc bpscan = (ParallelBlockTableScanDesc) pscan;
bpscan->base.phs_relid = RelationGetRelid(rel);
bpscan->phs_nblocks = 0; /* init, will be updated later by table_parallelscan_initialize */
pg_atomic_init_u64(&bpscan->phs_nallocated, 0);
/* we don't need phs_mutex and phs_startblock in ao, though, init them. */
SpinLockInit(&bpscan->phs_mutex);
bpscan->phs_startblock = InvalidBlockNumber;
return sizeof(ParallelBlockTableScanDescData);
}
static void
aoco_parallelscan_reinitialize(Relation rel, ParallelTableScanDesc pscan)
{
ParallelBlockTableScanDesc bpscan = (ParallelBlockTableScanDesc) pscan;
pg_atomic_write_u64(&bpscan->phs_nallocated, 0);
}
static IndexFetchTableData *
aoco_index_fetch_begin(Relation rel)
{
IndexFetchAOCOData *aocoscan = palloc0(sizeof(IndexFetchAOCOData));
aocoscan->xs_base.rel = rel;
/* aocoscan other variables are initialized lazily on first fetch */
return &aocoscan->xs_base;
}
static void
aoco_index_fetch_reset(IndexFetchTableData *scan)
{
/*
* Unlike Heap, we don't release the resources (fetch descriptor and its
* members) here because it is more like a global data structure shared
* across scans, rather than an iterator to yield a granularity of data.
*
* Additionally, should be aware of that no matter whether allocation or
* release on fetch descriptor, it is considerably expensive.
*/
return;
}
static void
aoco_index_fetch_end(IndexFetchTableData *scan)
{
IndexFetchAOCOData *aocoscan = (IndexFetchAOCOData *) scan;
if (aocoscan->aocofetch)
{
aocs_fetch_finish(aocoscan->aocofetch);
pfree(aocoscan->aocofetch);
aocoscan->aocofetch = NULL;
}
if (aocoscan->proj)
{
pfree(aocoscan->proj);
aocoscan->proj = NULL;
}
pfree(aocoscan);
}
static bool
aoco_index_fetch_tuple(struct IndexFetchTableData *scan,
ItemPointer tid,
Snapshot snapshot,
TupleTableSlot *slot,
bool *call_again, bool *all_dead)
{
IndexFetchAOCOData *aocoscan = (IndexFetchAOCOData *) scan;
bool found = false;
if (!aocoscan->aocofetch)
{
Snapshot appendOnlyMetaDataSnapshot;
int natts;
/* Initiallize the projection info, assumes the whole row */
Assert(!aocoscan->proj);
natts = RelationGetNumberOfAttributes(scan->rel);
aocoscan->proj = palloc(natts * sizeof(*aocoscan->proj));
MemSet(aocoscan->proj, true, natts * sizeof(*aocoscan->proj));
appendOnlyMetaDataSnapshot = snapshot;
if (appendOnlyMetaDataSnapshot == SnapshotAny)
{
/*
* the append-only meta data should never be fetched with
* SnapshotAny as bogus results are returned.
*/
appendOnlyMetaDataSnapshot = GetTransactionSnapshot();
}
aocoscan->aocofetch = aocs_fetch_init(aocoscan->xs_base.rel,
snapshot,
appendOnlyMetaDataSnapshot,
aocoscan->proj);
}
/*
* There is no reason to expect changes on snapshot between tuple
* fetching calls after fech_init is called, treat it as a
* programming error in case of occurrence.
*/
Assert(aocoscan->aocofetch->snapshot == snapshot);
ExecClearTuple(slot);
if (aocs_fetch(aocoscan->aocofetch, (AOTupleId *) tid, slot))
{
ExecStoreVirtualTuple(slot);
found = true;
}
/*
* Currently, we don't determine this parameter. By contract, it is to be
* set to true iff we can determine that this row is dead to all
* transactions. Failure to set this will lead to use of a garbage value
* in certain code, such as that for unique index checks.
* This is typically used for HOT chains, which we don't support.
*/
if (all_dead)
*all_dead = false;
/* Currently, we don't determine this parameter. By contract, it is to be
* set to true iff there is another tuple for the tid, so that we can prompt
* the caller to call index_fetch_tuple() again for the same tid.
* This is typically used for HOT chains, which we don't support.
*/
if (call_again)
*call_again = false;
return found;
}
/*
* Check if a visible tuple exists given the tid and a snapshot. This is
* currently used to determine uniqueness checks.
*
* We determine existence simply by checking if a *visible* block directory
* entry covers the given tid.
*
* There is no need to fetch the tuple (we actually can't reliably do so as
* we might encounter a placeholder row in the block directory)
*
* If no visible block directory entry exists, we are done. If it does, we need
* to further check the visibility of the tuple itself by consulting the visimap.
* Now, the visimap check can be skipped if the tuple was found to have been
* inserted by a concurrent in-progress transaction, in which case we return
* true and have the xwait machinery kick in.
*/
static bool
aoco_index_unique_check(Relation rel,
ItemPointer tid,
Snapshot snapshot,
bool *all_dead)
{
AOCSUniqueCheckDesc uniqueCheckDesc;
AOTupleId *aoTupleId = (AOTupleId *) tid;
bool visible;
#ifdef USE_ASSERT_CHECKING
int segmentFileNum = AOTupleIdGet_segmentFileNum(aoTupleId);
int64 rowNum = AOTupleIdGet_rowNum(aoTupleId);
Assert(segmentFileNum != InvalidFileSegNumber);
Assert(rowNum != InvalidAORowNum);
/*
* Since this can only be called in the context of a unique index check, the
* snapshots that are supplied can only be non-MVCC snapshots: SELF and DIRTY.
*/
Assert(snapshot->snapshot_type == SNAPSHOT_SELF ||
snapshot->snapshot_type == SNAPSHOT_DIRTY);
#endif
/*
* Currently, we don't determine this parameter. By contract, it is to be
* set to true iff we can determine that this row is dead to all
* transactions. Failure to set this will lead to use of a garbage value
* in certain code, such as that for unique index checks.
* This is typically used for HOT chains, which we don't support.
*/
if (all_dead)
*all_dead = false;
/*
* FIXME: for when we want CREATE UNIQUE INDEX CONCURRENTLY to work
* Unique constraint violation checks with SNAPSHOT_SELF are currently
* required to support CREATE UNIQUE INDEX CONCURRENTLY. Currently, the
* sole placeholder row inserted at first insert might not be visible to
* the snapshot, if it was already updated by its actual first row. So,
* we would need to flush a placeholder row at the beginning of each new
* in-memory minipage. Currently, CREATE INDEX CONCURRENTLY isn't
* supported, so we assume such a check satisfies SNAPSHOT_SELF.
*/
if (snapshot->snapshot_type == SNAPSHOT_SELF)
return true;
uniqueCheckDesc = get_or_create_unique_check_desc(rel, snapshot);
/* First, scan the block directory */
if (!AppendOnlyBlockDirectory_UniqueCheck(uniqueCheckDesc->blockDirectory,
aoTupleId,
snapshot))
return false;