-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcompression_dml.c
More file actions
2460 lines (2216 loc) · 69.8 KB
/
Copy pathcompression_dml.c
File metadata and controls
2460 lines (2216 loc) · 69.8 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
/*
* This file and its contents are licensed under the Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <postgres.h>
#include <access/genam.h>
#include <access/sdir.h>
#include <access/tableam.h>
#include <access/valid.h>
#include <catalog/pg_am.h>
#include <nodes/nodeFuncs.h>
#include <optimizer/optimizer.h>
#include <parser/parse_coerce.h>
#include <parser/parse_relation.h>
#include <parser/parsetree.h>
#include <utils/datum.h>
#include <utils/lsyscache.h>
#include <utils/relcache.h>
#include <utils/snapmgr.h>
#include <utils/typcache.h>
#include <compat/compat.h>
#include "foreach_ptr.h"
#include <chunk_insert_state.h>
#include <compression/arrow_c_data_interface.h>
#include <compression/compression.h>
#include <compression/compression_dml.h>
#include <compression/create.h>
#include <compression/sparse_index_bloom1.h>
#include <compression/wal_utils.h>
#include <continuous_aggs/insert.h>
#include <expression_utils.h>
#include <indexing.h>
#include <nodes/columnar_scan/vector_dict.h>
#include <nodes/columnar_scan/vector_predicates.h>
#include <nodes/modify_hypertable.h>
#include <ts_catalog/array_utils.h>
/*
* Context for tracking continuous aggregate invalidation during direct batch delete.
* When batches are deleted without decompression, we need to track the
* time range covered by deleted batches to properly invalidate any
* continuous aggregates.
*/
typedef struct InvalidationContext
{
int32 hypertable_id;
Oid chunk_relid;
Oid time_type_oid;
AttrNumber min_time_attno; /* compressed chunk column for time min */
AttrNumber max_time_attno; /* compressed chunk column for time max */
} InvalidationContext;
typedef BatchQualSummary(BatchMatcher)(RowDecompressor *decompressor, ScanKeyData *scankeys,
int num_scankeys, tuple_filtering_constraints *constraints,
bool check_full_match, bool *skip_current_tuple);
static struct decompress_batches_stats
decompress_batches_scan(Relation in_rel, Relation out_rel, Relation index_rel, Snapshot snapshot,
bool *skip_current_tuple, bool delete_only, List *is_nulls,
InvalidationContext *invalidation_ctx, CachedDecompressionState *cdst,
TupleTableSlot *insert_slot);
static BatchQualSummary batch_matches(RowDecompressor *decompressor, ScanKeyData *scankeys,
int num_scankeys, tuple_filtering_constraints *constraints,
bool check_full_match, bool *skip_current_tuple);
static BatchQualSummary batch_matches_vectorized(RowDecompressor *decompressor,
ScanKeyData *scankeys, int num_scankeys,
tuple_filtering_constraints *constraints,
bool check_full_match, bool *skip_current_tuple);
static void process_predicates(Chunk *ch, CompressionSettings *settings, List *predicates,
ScanKeyData **mem_scankeys, int *num_mem_scankeys,
List **heap_filters, List **index_filters, List **is_null,
List **bloom_filters);
static Relation find_matching_index(Relation comp_chunk_rel, List **index_filters,
List **heap_filters);
static tuple_filtering_constraints *get_batch_keys_for_unique_constraints(Relation relation);
static BatchFilter *make_batchfilter(char *column_name, StrategyNumber strategy, Oid collation,
RegProcedure opcode, Const *value, bool is_null_check,
bool is_null, bool is_array_op);
static void report_error(TM_Result result);
static bool key_column_is_null(tuple_filtering_constraints *constraints, Relation chunk_rel,
Oid ht_relid, TupleTableSlot *slot);
static bool can_delete_without_decompression(ModifyHypertableState *ht_state,
CompressionSettings *settings, Chunk *chunk,
List *predicates);
static bool can_vectorize_constraint_checks(tuple_filtering_constraints *constraints,
CompressionSettings *settings, Relation chunk_rel,
Oid ht_relid, ScanKeyWithAttnos *mem_scankeys);
static void update_scankeys(ScanKeyWithAttnos *scankeys, TupleTableSlot *slot, int null_flags);
static void init_upsert_bloom_state(ChunkInsertState *cis);
static Bitmapset *get_arbiter_index_attnums(ChunkInsertState *cis);
static AttrNumber
TupleDescGetAttrNumber(TupleDesc desc, const char *name)
{
for (int i = 0; i < desc->natts; i++)
{
if (strcmp(name, NameStr(TupleDescAttr(desc, i)->attname)) == 0)
{
return TupleDescAttr(desc, i)->attnum;
}
}
return InvalidAttrNumber;
}
typedef struct MatchedBloom
{
char *column_name;
Bitmapset *attnums;
AttrNumber compressed_attnum;
int num_cols;
} MatchedBloom;
/*
* Pre-computed bloom filter check for UPDATE/DELETE batch pruning.
* The hash is computed once in process_predicates() and checked
* per batch in decompress_batches_scan() via bloom1_contains_hash().
*/
typedef struct BloomFilterCheck
{
AttrNumber bloom_attno; /* attnum of bloom metadata column in compressed chunk */
uint64 hash; /* pre-computed hash of the search value(s) */
int num_columns; /* number of columns in the bloom filter (for sort order) */
} BloomFilterCheck;
/*
* Comparator for list_sort(): order BloomFilterCheck by column count
* in descending order, assuming this reflects the selectivity order.
*/
static int
bloom_filter_check_cmp(const ListCell *a, const ListCell *b)
{
BloomFilterCheck *ca = lfirst(a);
BloomFilterCheck *cb = lfirst(b);
/* Descending order: more columns first */
return cb->num_columns - ca->num_columns;
}
/*
* Collects equality predicates during process_predicates() for the
* post-loop bloom matching pass. Type OIDs are resolved via
* get_atttype() at hash computation time.
*/
typedef struct EqualityPredicate
{
AttrNumber attno; /* column attno in uncompressed chunk */
Datum constvalue; /* the constant value from WHERE col = <value> */
} EqualityPredicate;
/*
* Get arbiter index column attnums from the arbiter index list.
*/
static Bitmapset *
get_arbiter_index_attnums(ChunkInsertState *cis)
{
Assert(cis != NULL);
Assert(cis->result_relation_info != NULL);
List *arbiterIndexes = cis->result_relation_info->ri_onConflictArbiterIndexes;
if (arbiterIndexes == NIL)
{
return NULL;
}
Oid arbiter_oid = linitial_oid(arbiterIndexes);
Relation index_rel = index_open(arbiter_oid, AccessShareLock);
Bitmapset *attnums = NULL;
for (int i = 0; i < index_rel->rd_index->indnkeyatts; i++)
{
AttrNumber attno = index_rel->rd_index->indkey.values[i];
if (!AttributeNumberIsValid(attno))
{
/* Expression index - can't use bloom optimization */
index_close(index_rel, AccessShareLock);
return NULL;
}
attnums = bms_add_member(attnums, attno);
}
index_close(index_rel, AccessShareLock);
return attnums;
}
/*
* Per-chunk initialization of UPSERT bloom state. Called once per chunk in
* init_decompress_state_for_insert(), inside the has_primary_or_unique_index block. The result is
* cached in CachedDecompressionState via ChunkInsertState in subspace_store.
*
* It assumes cdst->compression_settings is already looked up for the chunk.
*
* Discovers which bloom columns match arbiter index columns, that is, being a subset of the
* conflict columns. Builds the mapping from bloom columns to INSERT tuple attnums, and resolves
* bloom column names to compressed chunk attnums. The chosen bloom filter is stored in the
* CachedDecompressionState struct.
*/
static void
init_upsert_bloom_state(ChunkInsertState *cis)
{
Bitmapset *conflict_attnums = get_arbiter_index_attnums(cis);
CachedDecompressionState *cdst = cis->cached_decompression_state;
Assert(cdst != NULL);
if (cdst == NULL || conflict_attnums == NULL)
{
return;
}
CompressionSettings *settings = cdst->compression_settings;
Assert(settings != NULL);
if (settings == NULL || settings->fd.index == NULL)
{
return;
}
Oid compressed_relid = settings->fd.compress_relid;
SparseIndexSettings *parsed = ts_convert_to_sparse_index_settings(settings->fd.index);
Assert(parsed != NULL);
if (parsed == NULL)
{
return;
}
/* Map the bloom column names to hypertable attnums, because the bloom columns
* will be built based on the insert tuple attnums which are the hypertable attnums. */
TsBmsList per_column_attnos =
ts_resolve_columns_to_attnos_from_parsed_settings(parsed, cis->hypertable_relid);
Assert(list_length(per_column_attnos) == list_length(parsed->objects));
Assert(list_length(per_column_attnos) > 0);
MatchedBloom best_match = { .num_cols = 0 };
/** Parallel iteration over objects and their resolved attnums. */
ListCell *obj_cell;
ListCell *attno_cell;
forboth (obj_cell, parsed->objects, attno_cell, per_column_attnos)
{
SparseIndexSettingsObject *obj = lfirst(obj_cell);
Bitmapset *bloom_attnos = lfirst(attno_cell);
/* Check if bloom type */
List *type_values = ts_get_values_by_key_from_parsed_object(obj, "type");
if (type_values == NIL || strcmp((char *) linitial(type_values), "bloom") != 0)
{
continue;
}
/* Check if bloom columns are a subset of the conflict columns */
if (!bms_is_subset(bloom_attnos, conflict_attnums))
{
continue;
}
int num_cols = bms_num_members(bloom_attnos);
/* Only keep the best match (most columns) */
if (num_cols <= best_match.num_cols)
{
continue;
}
/* Get column name for this bloom */
List *column_names = ts_get_column_names_from_parsed_object(obj);
char *col_name =
compressed_column_metadata_name_list_v2(bloom1_column_prefix, column_names);
/* Verify bloom column exists in the compressed chunk */
AttrNumber compressed_attnum = get_attnum(compressed_relid, col_name);
if (!AttributeNumberIsValid(compressed_attnum))
{
continue;
}
/* New best match */
best_match.column_name = col_name;
best_match.attnums = bms_copy(bloom_attnos);
best_match.compressed_attnum = compressed_attnum;
best_match.num_cols = num_cols;
}
/* Create builder for the best match, having the largest number of columns */
if (best_match.num_cols > 0)
{
Oid type_oids[MAX_BLOOM_FILTER_COLUMNS];
cdst->bloom_column_name = best_match.column_name;
cdst->bloom_insert_attnums = best_match.attnums;
cdst->upsert_bloom_attnum = best_match.compressed_attnum;
int col_idx = 0;
int attnum = -1;
while ((attnum = bms_next_member(best_match.attnums, attnum)) >= 0)
{
type_oids[col_idx++] = get_atttype(cis->hypertable_relid, attnum);
}
if (ts_guc_enable_sparse_index_bloom)
{
cdst->bloom_hasher = bloom1_hasher_create(type_oids, best_match.num_cols);
}
}
ts_bmslist_free(per_column_attnos);
ts_free_sparse_index_settings(parsed);
}
void
init_decompress_state_for_insert(ChunkInsertState *cis, TupleTableSlot *slot)
{
if (!cis->chunk_compressed || cis->cached_decompression_state != NULL)
{
/*
* If the chunk is not compressed or the decompression state has
* already been initialized, there is nothing to do here.
*/
return;
}
CachedDecompressionState *cdst = NULL;
MemoryContext old_context = MemoryContextSwitchTo(cis->mctx);
cdst = palloc0(sizeof(CachedDecompressionState));
cis->cached_decompression_state = cdst;
cdst->has_primary_or_unique_index = ts_indexing_relation_has_primary_or_unique_index(cis->rel);
if (cdst->has_primary_or_unique_index)
{
tuple_filtering_constraints *constraints = get_batch_keys_for_unique_constraints(cis->rel);
if (constraints->covered)
{
constraints->on_conflict = cis->onConflictAction;
}
cdst->constraints = constraints;
CompressionSettings *compression_settings =
ts_compression_settings_get(RelationGetRelid(cis->rel));
Assert(compression_settings && OidIsValid(compression_settings->fd.compress_relid));
cdst->compression_settings = compression_settings;
Relation in_rel = relation_open(compression_settings->fd.compress_relid, RowExclusiveLock);
Bitmapset *columns_with_null_check = NULL;
Bitmapset *key_columns = constraints->key_columns;
Bitmapset *index_columns = NULL;
Relation index_rel = NULL;
if (ts_guc_enable_dml_decompression_tuple_filtering)
{
cdst->mem_scankeys.scankeys =
build_mem_scankeys_from_slot(cis->hypertable_relid,
compression_settings,
cis->rel,
constraints,
slot,
&cdst->mem_scankeys.num_scankeys,
&cdst->mem_scankeys.attnos);
cdst->constraints->vectorized_filtering =
can_vectorize_constraint_checks(constraints,
compression_settings,
cis->rel,
cis->hypertable_relid,
&cdst->mem_scankeys);
cdst->index_scankeys.scankeys =
build_index_scankeys_using_slot(cis->hypertable_relid,
in_rel,
cis->rel,
constraints->key_columns,
slot,
&index_rel,
&index_columns,
&cdst->index_scankeys.num_scankeys,
&cdst->index_scankeys.attnos);
if (cis->onConflictAction != ONCONFLICT_NONE)
{
init_upsert_bloom_state(cis);
}
}
if (index_rel)
{
/*
* Prepare the heap scan keys for all
* key columns not found in the index
*/
key_columns = bms_difference(constraints->key_columns, index_columns);
}
cdst->heap_scankeys.scankeys = build_heap_scankeys(cis->hypertable_relid,
in_rel,
cis->rel,
compression_settings,
key_columns,
&columns_with_null_check,
slot,
&cdst->heap_scankeys.num_scankeys,
&cdst->heap_scankeys.attnos);
if (index_rel)
{
cdst->index_relid = RelationGetRelid(index_rel);
columns_with_null_check = NULL;
index_close(index_rel, AccessShareLock);
}
cdst->columns_with_null_check = columns_with_null_check;
table_close(in_rel, NoLock);
}
MemoryContextSwitchTo(old_context);
}
static void
update_scankeys(ScanKeyWithAttnos *scankeys, TupleTableSlot *slot, int null_flags)
{
if (scankeys->num_scankeys == 0)
{
return;
}
for (int i = 0; i < scankeys->num_scankeys; i++)
{
bool isnull = false;
Datum value = slot_getattr(slot, scankeys->attnos[i], &isnull);
if (isnull)
{
scankeys->scankeys[i].sk_flags = null_flags;
scankeys->scankeys[i].sk_argument = UnassignedDatum;
}
else
{
scankeys->scankeys[i].sk_flags = 0;
scankeys->scankeys[i].sk_argument = value;
}
}
}
void
decompress_batches_for_insert(ChunkInsertState *cis, TupleTableSlot *slot)
{
/*
* This is supposed to be called with the actual tuple that is being
* inserted, so it cannot be empty.
*/
Assert(!TTS_EMPTY(slot));
Relation out_rel = cis->rel;
CachedDecompressionState *cdst = cis->cached_decompression_state;
Assert(cdst != NULL);
if (!cdst->has_primary_or_unique_index)
{
/*
* If there are no unique constraints there is nothing to do here.
*/
return;
}
if (!ts_guc_enable_dml_decompression)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("inserting into compressed chunk with unique constraints disabled"),
errhint("Set timescaledb.enable_dml_decompression to TRUE.")));
}
if (key_column_is_null(cdst->constraints, cis->rel, cis->hypertable_relid, slot))
{
/* When any key column is NULL and NULLs are distinct there is no
* decompression to be done as the tuple will not conflict with any
* existing tuples.
*/
return;
}
Assert(cdst->compression_settings->fd.relid == RelationGetRelid(out_rel));
Relation in_rel =
relation_open(cdst->compression_settings->fd.compress_relid, RowExclusiveLock);
/* the scan keys used for in memory tests of the decompressed tuples */
bool skip_current_tuple = false;
struct decompress_batches_stats stats = { 0 };
Relation index_rel = NULL;
if (OidIsValid(cdst->index_relid))
{
index_rel = index_open(cdst->index_relid, AccessShareLock);
}
update_scankeys(&cdst->index_scankeys, slot, SK_ISNULL | SK_SEARCHNULL);
update_scankeys(&cdst->heap_scankeys, slot, SK_ISNULL | SK_SEARCHNULL);
update_scankeys(&cdst->mem_scankeys, slot, SK_ISNULL);
if (ts_guc_debug_compression_path_info)
{
elog(INFO,
"Using %s scan with scan keys: index %d, heap %d, memory %d. ",
OidIsValid(cdst->index_relid) ? "index" : "table",
cdst->index_scankeys.num_scankeys,
cdst->heap_scankeys.num_scankeys,
cdst->mem_scankeys.num_scankeys);
}
/*
* Using latest snapshot to scan the heap since we are doing this to build
* the index on the uncompressed chunks in order to do speculative insertion
* which is always built from all tuples (even in higher levels of isolation).
*/
PushActiveSnapshot(GetLatestSnapshot());
stats = decompress_batches_scan(in_rel,
out_rel,
index_rel,
GetActiveSnapshot(),
&skip_current_tuple,
false,
NIL,
NULL /* no CAgg invalidation for inserts */,
cdst,
slot);
if (index_rel)
{
index_close(index_rel, AccessShareLock);
}
PopActiveSnapshot();
if (skip_current_tuple)
{
cis->skip_current_tuple = true;
}
cis->counters->batches_deleted += stats.batches_deleted;
cis->counters->batches_filtered_decompressed += stats.batches_filtered_decompressed;
cis->counters->batches_decompressed += stats.batches_decompressed;
cis->counters->tuples_decompressed += stats.tuples_decompressed;
cis->counters->batches_scanned += stats.batches_scanned;
cis->counters->batches_checked_by_bloom += stats.batches_checked_by_bloom;
cis->counters->batches_pruned_by_bloom += stats.batches_pruned_by_bloom;
cis->counters->batches_without_bloom += stats.batches_without_bloom;
cis->counters->batches_bloom_false_positives += stats.batches_bloom_false_positives;
cis->counters->batches_filtered_compressed += stats.batches_filtered_compressed;
CommandCounterIncrement();
table_close(in_rel, NoLock);
}
/*
* This method will:
* 1. Evaluate WHERE clauses and check if SEGMENT BY columns
* are specified or not.
* 2. Build scan keys for SEGMENT BY columns.
* 3. Move scanned rows to staging area.
* 4. Update catalog table to change status of moved chunk.
*
* Returns true if it decompresses any data.
*/
static bool
decompress_batches_for_update_delete(ModifyHypertableState *ht_state, Chunk *chunk,
List *predicates, EState *estate, bool has_joins)
{
/* process each chunk with its corresponding predicates */
List *heap_filters = NIL;
List *index_filters = NIL;
List *is_null = NIL;
ListCell *lc = NULL;
Relation chunk_rel;
Relation comp_chunk_rel;
Relation matching_index_rel = NULL;
BatchFilter *filter;
ScanKeyData *scankeys = NULL;
Bitmapset *null_columns = NULL;
int num_scankeys = 0;
ScanKeyData *index_scankeys = NULL;
int num_index_scankeys = 0;
struct decompress_batches_stats stats = { 0 };
int num_mem_scankeys = 0;
ScanKeyData *mem_scankeys = NULL;
List *bloom_filters = NIL;
CompressionSettings *settings = ts_compression_settings_get(chunk->table_id);
bool delete_only = ht_state->mt->operation == CMD_DELETE && !has_joins &&
can_delete_without_decompression(ht_state, settings, chunk, predicates);
InvalidationContext invalidation_ctx = { 0 };
/*
* Set up CAgg invalidation context if we're doing direct batch delete
* on a hypertable with continuous aggregates.
*/
if (delete_only && ht_state->has_continuous_aggregate)
{
const Dimension *time_dim = hyperspace_get_open_dimension(ht_state->ht->space, 0);
const char *time_col_name = NameStr(time_dim->fd.column_name);
AttrNumber chunk_time_attno = get_attnum(chunk->table_id, time_col_name);
invalidation_ctx.hypertable_id = ht_state->ht->fd.id;
invalidation_ctx.chunk_relid = chunk->table_id;
invalidation_ctx.time_type_oid = time_dim->fd.column_type;
if (ts_array_is_member(settings->fd.segmentby, time_col_name))
{
/*
* Time column is segmentby: every row in the batch shares the same
* value, so use the segmentby column's compressed-tuple attno for
* both bounds. Segmentby columns don't have _ts_meta_min/max
* sparse-index columns to look up.
*/
AttrNumber compressed_attno = get_attnum(settings->fd.compress_relid, time_col_name);
invalidation_ctx.min_time_attno = compressed_attno;
invalidation_ctx.max_time_attno = compressed_attno;
}
else
{
invalidation_ctx.min_time_attno =
compressed_column_metadata_attno(settings,
chunk->table_id,
chunk_time_attno,
settings->fd.compress_relid,
"min");
invalidation_ctx.max_time_attno =
compressed_column_metadata_attno(settings,
chunk->table_id,
chunk_time_attno,
settings->fd.compress_relid,
"max");
}
}
process_predicates(chunk,
settings,
predicates,
&mem_scankeys,
&num_mem_scankeys,
&heap_filters,
&index_filters,
&is_null,
&bloom_filters);
chunk_rel = table_open(chunk->table_id, RowExclusiveLock);
comp_chunk_rel = table_open(settings->fd.compress_relid, RowExclusiveLock);
if (index_filters)
{
matching_index_rel = find_matching_index(comp_chunk_rel, &index_filters, &heap_filters);
}
if (heap_filters)
{
scankeys = build_update_delete_scankeys(comp_chunk_rel,
heap_filters,
&num_scankeys,
&null_columns,
&delete_only);
}
if (matching_index_rel)
{
index_scankeys =
build_index_scankeys(matching_index_rel, index_filters, &num_index_scankeys);
}
CachedDecompressionState temp_cdst = { 0 };
temp_cdst.index_scankeys.scankeys = index_scankeys;
temp_cdst.index_scankeys.num_scankeys = num_index_scankeys;
temp_cdst.heap_scankeys.scankeys = scankeys;
temp_cdst.heap_scankeys.num_scankeys = num_scankeys;
temp_cdst.mem_scankeys.scankeys = mem_scankeys;
temp_cdst.mem_scankeys.num_scankeys = num_mem_scankeys;
temp_cdst.constraints = NULL;
temp_cdst.columns_with_null_check = null_columns;
temp_cdst.bloom_filters = bloom_filters;
PushActiveSnapshot(GetTransactionSnapshot());
stats = decompress_batches_scan(comp_chunk_rel,
chunk_rel,
matching_index_rel,
GetActiveSnapshot(),
NULL,
delete_only,
is_null,
ht_state->has_continuous_aggregate ? &invalidation_ctx : NULL,
&temp_cdst,
NULL);
/* close the selected index */
if (matching_index_rel)
{
index_close(matching_index_rel, AccessShareLock);
}
PopActiveSnapshot();
/*
* tuples from compressed chunk has been decompressed and moved
* to staging area, thus mark this chunk as partially compressed
*/
if (stats.batches_decompressed > 0)
{
ts_chunk_set_partial(chunk);
}
table_close(chunk_rel, NoLock);
table_close(comp_chunk_rel, NoLock);
foreach (lc, heap_filters)
{
filter = lfirst(lc);
pfree(filter);
}
foreach (lc, index_filters)
{
filter = lfirst(lc);
pfree(filter);
}
list_free_deep(bloom_filters);
ht_state->batches_deleted += stats.batches_deleted;
ht_state->batches_filtered_decompressed += stats.batches_filtered_decompressed;
ht_state->batches_decompressed += stats.batches_decompressed;
ht_state->tuples_decompressed += stats.tuples_decompressed;
ht_state->tuples_deleted += stats.tuples_deleted;
ht_state->batches_scanned += stats.batches_scanned;
ht_state->batches_checked_by_bloom += stats.batches_checked_by_bloom;
ht_state->batches_pruned_by_bloom += stats.batches_pruned_by_bloom;
ht_state->batches_without_bloom += stats.batches_without_bloom;
ht_state->batches_bloom_false_positives += stats.batches_bloom_false_positives;
ht_state->batches_filtered_compressed += stats.batches_filtered_compressed;
return stats.batches_decompressed > 0;
}
typedef struct DecompressBatchScanData
{
TableScanDesc scan;
IndexScanDesc index_scan;
} DecompressBatchScanData;
typedef struct DecompressBatchScanData *DecompressBatchScanDesc;
static DecompressBatchScanDesc
decompress_batch_beginscan(Relation in_rel, Relation index_rel, Snapshot snapshot, int num_scankeys,
ScanKeyData *scankeys)
{
DecompressBatchScanDesc scan;
scan = (DecompressBatchScanDesc) palloc(sizeof(DecompressBatchScanData));
if (index_rel)
{
scan->index_scan =
index_beginscan_compat(in_rel, index_rel, snapshot, NULL, num_scankeys, 0);
index_rescan(scan->index_scan, scankeys, num_scankeys, NULL, 0);
scan->scan = NULL;
}
else
{
scan->scan = table_beginscan(in_rel, snapshot, num_scankeys, scankeys);
scan->index_scan = NULL;
}
return scan;
}
static bool
decompress_batch_scan_getnext_slot(DecompressBatchScanDesc scan, ScanDirection direction,
struct TupleTableSlot *slot)
{
if (scan == NULL)
{
return false;
}
else if (scan->index_scan)
{
return index_getnext_slot(scan->index_scan, direction, slot);
}
else if (scan->scan)
{
return table_scan_getnextslot(scan->scan, direction, slot);
}
else
{
return false;
}
}
static void
decompress_batch_endscan(DecompressBatchScanDesc scan)
{
if (scan == NULL)
{
return;
}
else if (scan->index_scan)
{
index_endscan(scan->index_scan);
}
else if (scan->scan)
{
table_endscan(scan->scan);
}
pfree(scan);
}
/*
* This method will:
* 1.Scan the index created with SEGMENT BY columns or the entire compressed chunk
* 2.Fetch matching rows and decompress the row
* 3.Delete this row from compressed chunk
* 4.Insert decompressed rows to uncompressed chunk
*
* Returns whether we decompressed anything.
*
*/
static struct decompress_batches_stats
decompress_batches_scan(Relation in_rel, Relation out_rel, Relation index_rel, Snapshot snapshot,
bool *skip_current_tuple, bool delete_only, List *is_nulls,
InvalidationContext *invalidation_ctx, CachedDecompressionState *cdst,
TupleTableSlot *insert_slot)
{
HeapTuple compressed_tuple;
BulkWriter writer;
RowDecompressor decompressor;
bool decompressor_initialized = false;
bool valid = false;
TM_Result result;
DecompressBatchScanDesc scan = NULL;
ScanKeyData *index_scankeys = cdst->index_scankeys.scankeys;
int num_index_scankeys = cdst->index_scankeys.num_scankeys;
ScanKeyData *heap_scankeys = cdst->heap_scankeys.scankeys;
int num_heap_scankeys = cdst->heap_scankeys.num_scankeys;
ScanKeyData *mem_scankeys = cdst->mem_scankeys.scankeys;
int num_mem_scankeys = cdst->mem_scankeys.num_scankeys;
tuple_filtering_constraints *constraints = cdst->constraints;
Bitmapset *null_columns = cdst->columns_with_null_check;
BatchMatcher *batch_matcher =
constraints && constraints->vectorized_filtering ? batch_matches_vectorized : batch_matches;
AttrNumber meta_count_attno = InvalidAttrNumber;
struct decompress_batches_stats stats = { 0 };
/* TODO: Optimization by reusing the index scan while working on a single chunk */
if (index_rel)
{
scan = decompress_batch_beginscan(in_rel,
index_rel,
snapshot,
num_index_scankeys,
index_scankeys);
}
else
{
scan = decompress_batch_beginscan(in_rel, NULL, snapshot, num_heap_scankeys, heap_scankeys);
}
TupleTableSlot *slot = table_slot_create(in_rel, NULL);
while (decompress_batch_scan_getnext_slot(scan, ForwardScanDirection, slot))
{
stats.batches_scanned++;
/* Deconstruct the tuple */
Assert(slot->tts_ops->get_heap_tuple);
compressed_tuple = slot->tts_ops->get_heap_tuple(slot);
if (index_rel && num_heap_scankeys)
{
/* filter tuple based on compress_orderby columns */
valid = false;
#if PG16_LT
HeapKeyTest(compressed_tuple,
RelationGetDescr(in_rel),
num_heap_scankeys,
heap_scankeys,
valid);
#else
valid = HeapKeyTest(compressed_tuple,
RelationGetDescr(in_rel),
num_heap_scankeys,
heap_scankeys);
#endif
if (!valid)
{
stats.batches_filtered_compressed++;
continue;
}
}
int attrno = bms_next_member(null_columns, -1);
int pos = 0;
bool is_null_condition = 0;
bool seg_col_is_null = false;
bool complete_batch_delete;
valid = true;
/*
* Since the heap scan API does not support SK_SEARCHNULL we have to check
* for NULL values manually when those are part of the constraints.
*/
for (; attrno >= 0; attrno = bms_next_member(null_columns, attrno))
{
is_null_condition = is_nulls && list_nth_int(is_nulls, pos);
seg_col_is_null = slot_attisnull(slot, attrno);
if ((seg_col_is_null && !is_null_condition) || (!seg_col_is_null && is_null_condition))
{
/*
* if segment by column in the scanned tuple has non null value
* and IS NULL is specified, OR segment by column has null value
* and IS NOT NULL is specified then skip this tuple
*/
valid = false;
break;
}
pos++;
}
if (!valid)
{
stats.batches_filtered_compressed++;
continue;
}
/* To track false positives */
bool bloom_passed = false;
/*
* Bloom filter pruning for UPDATE/DELETE. Pre-computed hashes
* are checked against bloom metadata via slot_getattr().
*/
if (cdst->bloom_filters != NIL)
{
bool bloom_pruned = false;
foreach_ptr(BloomFilterCheck, check, cdst->bloom_filters)
{
bool isnull;
Datum bloom_datum = slot_getattr(slot, check->bloom_attno, &isnull);
stats.batches_checked_by_bloom++;
if (!isnull && !bloom1_contains_hash(bloom_datum, check->hash))
{
bloom_pruned = true;
break;
}
if (isnull)
{
stats.batches_without_bloom++;
}
}
if (bloom_pruned)
{
stats.batches_pruned_by_bloom++;
stats.batches_filtered_compressed++;
continue;
}
bloom_passed = true;
}
if (!decompressor_initialized)
{
decompressor = build_decompressor(RelationGetDescr(in_rel), RelationGetDescr(out_rel));
decompressor_initialized = true;
writer = bulk_writer_build(out_rel, 0);
meta_count_attno = TupleDescGetAttrNumber(decompressor.in_desc,
COMPRESSION_COLUMN_METADATA_COUNT_NAME);
Assert(meta_count_attno != InvalidAttrNumber);
}
heap_deform_tuple(compressed_tuple,
decompressor.in_desc,
decompressor.compressed_datums,
decompressor.compressed_is_nulls);
/* Bloom pre-filtering for UPSERT conflict detection */
if (insert_slot != NULL && cdst->bloom_hasher != NULL)
{
Datum bloom_datum =
decompressor.compressed_datums[AttrNumberGetAttrOffset(cdst->upsert_bloom_attnum)];
bool bloom_isnull =
decompressor
.compressed_is_nulls[AttrNumberGetAttrOffset(cdst->upsert_bloom_attnum)];
if (!bloom_isnull)
{
NullableDatum values[MAX_BLOOM_FILTER_COLUMNS];
int col_idx = 0;
int attnum = -1;
while ((attnum = bms_next_member(cdst->bloom_insert_attnums, attnum)) >= 0)
{
values[col_idx].value =
slot_getattr(insert_slot, attnum, &values[col_idx].isnull);
col_idx++;
}
uint64 hash = cdst->bloom_hasher->hash_values(cdst->bloom_hasher, values);
stats.batches_checked_by_bloom++;
if (!bloom1_contains_hash(bloom_datum, hash))