forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompression.c
More file actions
3553 lines (3051 loc) · 102 KB
/
Copy pathcompression.c
File metadata and controls
3553 lines (3051 loc) · 102 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/attmap.h>
#include <access/attnum.h>
#include <access/detoast.h>
#include <access/htup_details.h>
#include <access/skey.h>
#include <access/tupdesc.h>
#include <catalog/heap.h>
#include <catalog/indexing.h>
#include <catalog/pg_am.h>
#include <common/base64.h>
#include <funcapi.h>
#include <libpq/pqformat.h>
#include <storage/predicate.h>
#include <utils/datum.h>
#include <utils/elog.h>
#include <utils/lsyscache.h>
#include <utils/palloc.h>
#include <utils/rel.h>
#include <utils/snapmgr.h>
#include <utils/syscache.h>
#include <utils/typcache.h>
#include "compat/compat.h"
#include "algorithms/array.h"
#include "algorithms/bool_compress.h"
#include "algorithms/deltadelta.h"
#include "algorithms/dictionary.h"
#include "algorithms/gorilla.h"
#include "algorithms/null.h"
#include "algorithms/uuid_compress.h"
#include "batch_metadata_builder.h"
#include "chunk_insert_state.h"
#include "compression.h"
#include "compression/sparse_index_bloom1.h"
#include "continuous_aggs/insert.h"
#include "create.h"
#include "custom_type_cache.h"
#include "debug_assert.h"
#include "debug_point.h"
#include "guc.h"
#include "nodes/modify_hypertable.h"
#include "ts_catalog/array_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/compression_settings.h"
#include "ts_stats/ts_stats_record.h"
#include <nodes/columnar_scan/vector_quals.h>
/*
* Timing parameters for truncate locking heuristics.
* These are the same as used by Postgres for truncate locking during lazy vacuum.
* https://github.com/postgres/postgres/blob/4a0650d359c5981270039eeb634c3b7427aa0af5/src/backend/access/heap/vacuumlazy.c#L82
*/
#define COMPRESS_TRUNCATE_LOCK_WAIT_INTERVAL 50 /* ms */
#define COMPRESS_TRUNCATE_LOCK_TIMEOUT 5000 /* ms */
StaticAssertDecl(GLOBAL_MAX_ROWS_PER_COMPRESSION >= TARGET_COMPRESSED_BATCH_SIZE,
"max row numbers must be harmonized");
StaticAssertDecl(GLOBAL_MAX_ROWS_PER_COMPRESSION <= INT16_MAX,
"dictionary compression uses signed int16 indexes");
static const CompressionAlgorithmDefinition definitions[_END_COMPRESSION_ALGORITHMS] = {
[COMPRESSION_ALGORITHM_ARRAY] = ARRAY_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_DICTIONARY] = DICTIONARY_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_GORILLA] = GORILLA_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_DELTADELTA] = DELTA_DELTA_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_BOOL] = BOOL_COMPRESS_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_NULL] = NULL_COMPRESS_ALGORITHM_DEFINITION,
[COMPRESSION_ALGORITHM_UUID] = UUID_COMPRESS_ALGORITHM_DEFINITION,
};
static NameData compression_algorithm_name[] = {
[_INVALID_COMPRESSION_ALGORITHM] = { "INVALID" },
[COMPRESSION_ALGORITHM_ARRAY] = { "ARRAY" },
[COMPRESSION_ALGORITHM_DICTIONARY] = { "DICTIONARY" },
[COMPRESSION_ALGORITHM_GORILLA] = { "GORILLA" },
[COMPRESSION_ALGORITHM_DELTADELTA] = { "DELTADELTA" },
[COMPRESSION_ALGORITHM_BOOL] = { "BOOL" },
[COMPRESSION_ALGORITHM_NULL] = { "NULL" },
[COMPRESSION_ALGORITHM_UUID] = { "UUID" },
};
Name
compression_get_algorithm_name(CompressionAlgorithm alg)
{
return &compression_algorithm_name[alg];
}
static Compressor *
compressor_for_type(Oid type)
{
CompressionAlgorithm algorithm = compression_get_default_algorithm(type);
if (algorithm >= _END_COMPRESSION_ALGORITHMS)
{
elog(ERROR, "invalid compression algorithm %d", algorithm);
}
return definitions[algorithm].compressor_for_type(type);
}
DecompressionInitializer
tsl_get_decompression_iterator_init(CompressionAlgorithm algorithm, bool reverse)
{
if (algorithm >= _END_COMPRESSION_ALGORITHMS)
{
elog(ERROR, "invalid compression algorithm %d", algorithm);
}
if (reverse)
{
return definitions[algorithm].iterator_init_reverse;
}
else
{
return definitions[algorithm].iterator_init_forward;
}
}
DecompressAllFunction
tsl_get_decompress_all_function(CompressionAlgorithm algorithm, Oid type)
{
if (algorithm >= _END_COMPRESSION_ALGORITHMS)
{
elog(ERROR, "invalid compression algorithm %d", algorithm);
}
if (type != TEXTOID && type != BOOLOID && type != UUIDOID &&
(algorithm == COMPRESSION_ALGORITHM_DICTIONARY || algorithm == COMPRESSION_ALGORITHM_ARRAY))
{
/* Bulk decompression of array and dictionary is only supported for
* text, bool and uuid */
return NULL;
}
return definitions[algorithm].decompress_all;
}
static Tuplesortstate *compress_chunk_sort_relation(CompressionSettings *settings, Relation in_rel);
static void row_compressor_process_ordered_slot(RowCompressor *row_compressor, TupleTableSlot *slot,
BulkWriter *writer);
static void row_compressor_update_group(RowCompressor *row_compressor, TupleTableSlot *row);
static bool row_compressor_new_row_is_in_new_group(RowCompressor *row_compressor,
TupleTableSlot *row);
static void create_per_compressed_column(RowDecompressor *decompressor, bool internal_error);
static void row_compressor_append_row(RowCompressor *row_compressor, TupleTableSlot *row);
static void row_compressor_flush(RowCompressor *row_compressor, BulkWriter *writer,
bool changed_groups);
static int find_segmentby_candidates(CompressionSettings *settings, TupleDesc in_desc,
ColumnAnalysis *candidates);
static void process_segmentby_candidate_value(ColumnAnalysis *ca, Datum val, bool is_null);
static ArrayType *analyze_segmentby_candidates(ColumnAnalysis *candidates, int n_candidates);
static ArrayType *analyze_and_get_segmentby(CompressionSettings *settings,
RowCompressor *compressor);
static void compressor_apply_segmentby_and_rebuild(RowCompressor *old_compressor,
BulkWriter *old_bulk_writer);
/********************
** compress_chunk **
********************/
static CompressedDataHeader *
get_compressed_data_header(Datum data)
{
CompressedDataHeader *header = (CompressedDataHeader *) PG_DETOAST_DATUM(data);
if (header->compression_algorithm >= _END_COMPRESSION_ALGORITHMS)
{
elog(ERROR, "invalid compression algorithm %d", header->compression_algorithm);
}
return header;
}
/* Truncate the relation WITHOUT applying triggers. This is the
* main difference with ExecuteTruncate. Triggers aren't applied
* because the data remains, just in compressed form. Also don't
* restart sequences. Use the transactional branch through ExecuteTruncate.
*/
static void
truncate_relation(Oid table_oid)
{
List *fks = heap_truncate_find_FKs(list_make1_oid(table_oid));
/* Take an access exclusive lock now. Note that this may very well
* be a lock upgrade. */
Relation rel = table_open(table_oid, AccessExclusiveLock);
Oid toast_relid;
/* Chunks should never have fks into them, but double check */
if (fks != NIL)
{
elog(ERROR, "found a FK into a chunk while truncating");
}
CheckTableForSerializableConflictIn(rel);
#if PG16_LT
RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence);
#else
RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
#endif
toast_relid = rel->rd_rel->reltoastrelid;
table_close(rel, NoLock);
if (OidIsValid(toast_relid))
{
rel = table_open(toast_relid, AccessExclusiveLock);
#if PG16_LT
RelationSetNewRelfilenode(rel, rel->rd_rel->relpersistence);
#else
RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
#endif
table_close(rel, NoLock);
}
ReindexParams params = { 0 };
ReindexParams *options = ¶ms;
reindex_relation_compat(NULL, table_oid, REINDEX_REL_PROCESS_TOAST, options);
rel = table_open(table_oid, AccessExclusiveLock);
CommandCounterIncrement();
table_close(rel, NoLock);
}
/* Handle the all rows deletion of a given relation */
static void
RelationDeleteAllRows(Relation rel, Snapshot snap)
{
TupleTableSlot *slot = table_slot_create(rel, NULL);
TableScanDesc scan = table_beginscan(rel, snap, 0, NULL);
while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
{
simple_table_tuple_delete(rel, &(slot->tts_tid), snap);
}
table_endscan(scan);
ExecDropSingleTupleTableSlot(slot);
}
/*
* Delete the relation WITHOUT applying triggers. This will be used when
* `enable_delete_after_compression = true` instead of truncating the relation.
* Also don't restart sequences.
*/
static void
delete_relation_rows(Oid table_oid)
{
Relation rel = table_open(table_oid, RowExclusiveLock);
Snapshot snap = RegisterSnapshot(GetLatestSnapshot());
/*
* Delete the rows in the table. heap_delete also deletes any out-of-line
* TOAST values via heap_toast_delete, so the TOAST relation does not need
* a separate pass; doing one would re-visit those TOAST tuples in the
* same command and fail with "tuple already updated by self".
*/
RelationDeleteAllRows(rel, snap);
table_close(rel, NoLock);
UnregisterSnapshot(snap);
}
/*
* Use reltuples as an estimate for the number of rows that will get compressed. This value
* might be way off the mark in case analyze hasn't happened in quite a while on this input
* chunk. But that's the best guesstimate to start off with.
*
* We will report progress for every 10% of reltuples compressed. If rel or reltuples is not valid
* or it's just too low then we just assume reporting every 100K tuples for now.
*/
#define RELTUPLES_REPORT_DEFAULT 100000
static int64
calculate_reltuples_to_report(float4 reltuples)
{
int64 report_reltuples = RELTUPLES_REPORT_DEFAULT;
if (reltuples > 0)
{
report_reltuples = (int64) (0.1 * reltuples);
/* either analyze has not been done or table doesn't have a lot of rows */
if (report_reltuples < RELTUPLES_REPORT_DEFAULT)
{
report_reltuples = RELTUPLES_REPORT_DEFAULT;
}
}
return report_reltuples;
}
CompressionStats
compress_chunk(Oid in_table, Oid out_table, int insert_options)
{
int n_keys;
ListCell *lc;
ScanDirection indexscan_direction = NoMovementScanDirection;
Relation matched_index_rel = NULL;
TupleTableSlot *slot;
IndexScanDesc index_scan;
HeapTuple in_table_tp = NULL, index_tp = NULL;
Form_pg_attribute in_table_attr_tp, index_attr_tp;
CompressionStats cstat;
CompressionSettings *settings = ts_compression_settings_get_by_compress_relid(out_table);
int64 report_reltuples;
/* We want to prevent other compressors from compressing this table,
* and we want to prevent INSERTs or UPDATEs which could mess up our compression.
* We may as well allow readers to keep reading the uncompressed data while
* we are compressing, so we only take an ExclusiveLock instead of AccessExclusive.
*/
Relation in_rel = table_open(in_table, ExclusiveLock);
/* We are _just_ INSERTing into the out_table so in principle we could take
* a RowExclusive lock, and let other operations read and write this table
* as we work. However, we currently compress each table as a oneshot, so
* we're taking the stricter lock to prevent accidents.
*
* Putting RowExclusiveMode behind a GUC so we can try this out with
* rollups during compression.
*/
int out_rel_lockmode = ExclusiveLock;
if (ts_guc_enable_rowlevel_compression_locking)
{
out_rel_lockmode = RowExclusiveLock;
}
Relation out_rel = relation_open(out_table, out_rel_lockmode);
BulkWriter writer = bulk_writer_build(out_rel, insert_options);
/* Sanity check we are dealing with relations */
Ensure(in_rel->rd_rel->relkind == RELKIND_RELATION, "compress_chunk called on non-relation");
Ensure(out_rel->rd_rel->relkind == RELKIND_RELATION, "compress_chunk called on non-relation");
PushActiveSnapshot(GetTransactionSnapshot());
/* Before calling row compressor relation should be segmented and sorted as configured
* by compress_segmentby and compress_orderby.
* Cost of sorting can be mitigated if we find an existing BTREE index defined for
* uncompressed chunk otherwise expensive tuplesort will come into play.
*
* The following code is trying to find an existing index that
* matches the configuration so that we can skip sequential scan and
* tuplesort.
*
*/
if (ts_guc_enable_compression_indexscan)
{
List *in_rel_index_oids = RelationGetIndexList(in_rel);
foreach (lc, in_rel_index_oids)
{
Oid index_oid = lfirst_oid(lc);
Relation index_rel = index_open(index_oid, AccessShareLock);
IndexInfo *index_info = BuildIndexInfo(index_rel);
if (index_info->ii_Predicate != 0)
{
/*
* Can't use partial indexes for compression because they refer
* only to a subset of all rows.
*/
index_close(index_rel, AccessShareLock);
continue;
}
int previous_direction = NoMovementScanDirection;
int current_direction = NoMovementScanDirection;
n_keys =
ts_array_length(settings->fd.segmentby) + ts_array_length(settings->fd.orderby);
if (n_keys <= index_info->ii_NumIndexKeyAttrs && index_info->ii_Am == BTREE_AM_OID)
{
int i;
for (i = 0; i < n_keys; i++)
{
const char *attname;
int16 position;
bool is_orderby_asc = true;
bool is_null_first = false;
if (i < ts_array_length(settings->fd.segmentby))
{
position = i + 1;
attname = ts_array_get_element_text(settings->fd.segmentby, position);
}
else
{
position = i - ts_array_length(settings->fd.segmentby) + 1;
attname = ts_array_get_element_text(settings->fd.orderby, position);
is_orderby_asc =
!ts_array_get_element_bool(settings->fd.orderby_desc, position);
is_null_first =
ts_array_get_element_bool(settings->fd.orderby_nullsfirst, position);
}
int16 att_num = get_attnum(in_table, attname);
int16 option = index_rel->rd_indoption[i];
bool index_orderby_asc = ((option & INDOPTION_DESC) == 0);
bool index_null_first = ((option & INDOPTION_NULLS_FIRST) != 0);
if (att_num == 0 || index_info->ii_IndexAttrNumbers[i] != att_num)
{
break;
}
in_table_tp = SearchSysCacheAttNum(in_table, att_num);
if (!HeapTupleIsValid(in_table_tp))
{
elog(ERROR,
"table \"%s\" does not have column \"%s\"",
get_rel_name(in_table),
attname);
}
index_tp = SearchSysCacheAttNum(index_oid, i + 1);
if (!HeapTupleIsValid(index_tp))
{
elog(ERROR,
"index \"%s\" does not have column \"%s\"",
get_rel_name(index_oid),
attname);
}
in_table_attr_tp = (Form_pg_attribute) GETSTRUCT(in_table_tp);
index_attr_tp = (Form_pg_attribute) GETSTRUCT(index_tp);
if (index_orderby_asc == is_orderby_asc && index_null_first == is_null_first &&
in_table_attr_tp->attcollation == index_attr_tp->attcollation)
{
current_direction = ForwardScanDirection;
}
else if (index_orderby_asc != is_orderby_asc &&
index_null_first != is_null_first &&
in_table_attr_tp->attcollation == index_attr_tp->attcollation)
{
current_direction = BackwardScanDirection;
}
else
{
current_direction = NoMovementScanDirection;
break;
}
ReleaseSysCache(in_table_tp);
in_table_tp = NULL;
ReleaseSysCache(index_tp);
index_tp = NULL;
if (previous_direction == NoMovementScanDirection)
{
previous_direction = current_direction;
}
else if (previous_direction != current_direction)
{
break;
}
}
if (n_keys == i && (previous_direction == current_direction &&
current_direction != NoMovementScanDirection))
{
matched_index_rel = index_rel;
indexscan_direction = current_direction;
break;
}
else
{
if (HeapTupleIsValid(in_table_tp))
{
ReleaseSysCache(in_table_tp);
in_table_tp = NULL;
}
if (HeapTupleIsValid(index_tp))
{
ReleaseSysCache(index_tp);
index_tp = NULL;
}
index_close(index_rel, AccessShareLock);
}
}
else
{
index_close(index_rel, AccessShareLock);
}
}
}
RowCompressor row_compressor;
Assert(settings->fd.compress_relid == RelationGetRelid(out_rel));
row_compressor_init(&row_compressor,
settings,
RelationGetDescr(in_rel),
RelationGetDescr(out_rel));
if (matched_index_rel != NULL)
{
int64 nrows_processed = 0;
elog(ts_guc_debug_compression_path_info ? INFO : DEBUG1,
"using index \"%s\" to scan rows for converting to columnstore",
get_rel_name(matched_index_rel->rd_id));
index_scan =
index_beginscan_compat(in_rel, matched_index_rel, GetActiveSnapshot(), NULL, 0, 0);
slot = table_slot_create(in_rel, NULL);
index_rescan(index_scan, NULL, 0, NULL, 0);
report_reltuples = calculate_reltuples_to_report(in_rel->rd_rel->reltuples);
while (index_getnext_slot(index_scan, indexscan_direction, slot))
{
row_compressor_process_ordered_slot(&row_compressor, slot, &writer);
if ((++nrows_processed % report_reltuples) == 0)
{
elog(DEBUG2,
"converted " INT64_FORMAT " rows to columnstore from \"%s\"",
nrows_processed,
RelationGetRelationName(in_rel));
}
}
if (row_compressor.rows_compressed_into_current_value > 0)
{
row_compressor_flush(&row_compressor, &writer, true);
}
elog(DEBUG1,
"finished converting " INT64_FORMAT " rows to columnstore from \"%s\"",
nrows_processed,
RelationGetRelationName(in_rel));
ExecDropSingleTupleTableSlot(slot);
index_endscan(index_scan);
index_close(matched_index_rel, AccessShareLock);
}
else
{
elog(ts_guc_debug_compression_path_info ? INFO : DEBUG1,
"using tuplesort to scan rows from \"%s\" for converting to columnstore",
RelationGetRelationName(in_rel));
Tuplesortstate *sorted_rel = compress_chunk_sort_relation(settings, in_rel);
row_compressor_append_sorted_rows(&row_compressor, sorted_rel, in_rel, &writer);
tuplesort_end(sorted_rel);
}
row_compressor_close(&row_compressor);
bulk_writer_close(&writer);
if (ts_guc_enable_delete_after_compression)
{
ereport(NOTICE,
(errcode(ERRCODE_WARNING_DEPRECATED_FEATURE),
errmsg("timescaledb.enable_delete_after_compression is deprecated and will be "
"removed in a future version. Please use "
"timescaledb.compress_truncate_behaviour instead.")));
delete_relation_rows(in_table);
DEBUG_WAITPOINT("compression_done_after_delete_uncompressed");
}
else
{
int lock_retry = 0;
switch (ts_guc_compress_truncate_behaviour)
{
case COMPRESS_TRUNCATE_ONLY:
DEBUG_WAITPOINT("compression_done_before_truncate_uncompressed");
truncate_relation(in_table);
DEBUG_WAITPOINT("compression_done_after_truncate_uncompressed");
break;
case COMPRESS_TRUNCATE_OR_DELETE:
DEBUG_WAITPOINT("compression_done_before_truncate_or_delete_uncompressed");
while (true)
{
if (ConditionalLockRelation(in_rel, AccessExclusiveLock))
{
truncate_relation(in_table);
break;
}
/*
* Check for interrupts while trying to (re-)acquire the exclusive
* lock.
*/
CHECK_FOR_INTERRUPTS();
if (++lock_retry >
(COMPRESS_TRUNCATE_LOCK_TIMEOUT / COMPRESS_TRUNCATE_LOCK_WAIT_INTERVAL))
{
/*
* We failed to establish the lock in the specified number of
* retries. This means we give up truncating and fallback to delete
*/
delete_relation_rows(in_table);
break;
}
(void) WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
COMPRESS_TRUNCATE_LOCK_WAIT_INTERVAL,
WAIT_EVENT_VACUUM_TRUNCATE);
ResetLatch(MyLatch);
}
DEBUG_WAITPOINT("compression_done_after_truncate_or_delete_uncompressed");
break;
case COMPRESS_TRUNCATE_DISABLED:
delete_relation_rows(in_table);
DEBUG_WAITPOINT("compression_done_after_delete_uncompressed");
break;
}
}
table_close(out_rel, NoLock);
table_close(in_rel, NoLock);
PopActiveSnapshot();
cstat.rowcnt_pre_compression = row_compressor.rowcnt_pre_compression;
cstat.rowcnt_post_compression = row_compressor.num_compressed_rows;
if ((insert_options & HEAP_INSERT_FROZEN) == HEAP_INSERT_FROZEN)
{
cstat.rowcnt_frozen = row_compressor.num_compressed_rows;
}
else
{
cstat.rowcnt_frozen = 0;
}
return cstat;
}
Tuplesortstate *
compression_create_tuplesort_state(CompressionSettings *settings, Relation rel, bool random_access)
{
TupleDesc tupdesc = RelationGetDescr(rel);
int num_segmentby = ts_array_length(settings->fd.segmentby);
int num_orderby = ts_array_length(settings->fd.orderby);
int n_keys = num_segmentby + num_orderby;
AttrNumber *sort_keys = palloc(sizeof(*sort_keys) * n_keys);
Oid *sort_operators = palloc(sizeof(*sort_operators) * n_keys);
Oid *sort_collations = palloc(sizeof(*sort_collations) * n_keys);
bool *nulls_first = palloc(sizeof(*nulls_first) * n_keys);
int n;
for (n = 0; n < n_keys; n++)
{
const char *attname;
int position;
if (n < num_segmentby)
{
position = n + 1;
attname = ts_array_get_element_text(settings->fd.segmentby, position);
}
else
{
position = n - num_segmentby + 1;
attname = ts_array_get_element_text(settings->fd.orderby, position);
}
compress_chunk_populate_sort_info_for_column(settings,
RelationGetRelid(rel),
attname,
&sort_keys[n],
&sort_operators[n],
&sort_collations[n],
&nulls_first[n]);
}
/* Make a copy of the tuple descriptor so that it is allocated on the same
* memory context as the tuple sort instead of pointing into the relcache
* entry that could be blown away. */
return tuplesort_begin_heap(CreateTupleDescCopy(tupdesc),
n_keys,
sort_keys,
sort_operators,
sort_collations,
nulls_first,
maintenance_work_mem,
NULL,
random_access);
}
static Tuplesortstate *
compress_chunk_sort_relation(CompressionSettings *settings, Relation in_rel)
{
PushActiveSnapshot(GetLatestSnapshot());
Tuplesortstate *tuplesortstate;
TableScanDesc scan;
TupleTableSlot *slot;
tuplesortstate = compression_create_tuplesort_state(settings, in_rel, false);
scan = table_beginscan(in_rel, GetActiveSnapshot(), 0, NULL);
slot = table_slot_create(in_rel, NULL);
while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
{
if (!TTS_EMPTY(slot))
{
/* This may not be the most efficient way to do things.
* Since we use begin_heap() the tuplestore expects tupleslots,
* so ISTM that the options are this or maybe putdatum().
*/
tuplesort_puttupleslot(tuplesortstate, slot);
}
}
table_endscan(scan);
ExecDropSingleTupleTableSlot(slot);
tuplesort_performsort(tuplesortstate);
PopActiveSnapshot();
return tuplesortstate;
}
void
compress_chunk_populate_sort_info_for_column(const CompressionSettings *settings, Oid table,
const char *attname, AttrNumber *att_nums,
Oid *sort_operator, Oid *collation, bool *nulls_first)
{
HeapTuple tp;
Form_pg_attribute att_tup;
TypeCacheEntry *tentry;
tp = SearchSysCacheAttName(table, attname);
if (!HeapTupleIsValid(tp))
{
elog(ERROR, "table \"%s\" does not have column \"%s\"", get_rel_name(table), attname);
}
att_tup = (Form_pg_attribute) GETSTRUCT(tp);
/* Other validation checks beyond just existence of a valid comparison operator could be useful
*/
*att_nums = att_tup->attnum;
*collation = att_tup->attcollation;
tentry = lookup_type_cache(att_tup->atttypid, TYPECACHE_LT_OPR | TYPECACHE_GT_OPR);
if (ts_array_is_member(settings->fd.segmentby, attname))
{
*nulls_first = false;
*sort_operator = tentry->lt_opr;
}
else
{
Assert(ts_array_is_member(settings->fd.orderby, attname));
int position = ts_array_position(settings->fd.orderby, attname);
*nulls_first = ts_array_get_element_bool(settings->fd.orderby_nullsfirst, position);
if (ts_array_get_element_bool(settings->fd.orderby_desc, position))
{
*sort_operator = tentry->gt_opr;
}
else
{
*sort_operator = tentry->lt_opr;
}
}
if (!OidIsValid(*sort_operator))
{
elog(ERROR,
"no valid sort operator for column \"%s\" of type \"%s\"",
attname,
format_type_be(att_tup->atttypid));
}
ReleaseSysCache(tp);
}
/*
* Find segment by index on compressed chunk needed when doing index scans
* over compressed data
*/
Oid
get_compressed_chunk_index(ResultRelInfo *resultRelInfo, const CompressionSettings *settings)
{
int num_segmentby_columns = ts_array_length(settings->fd.segmentby);
int num_orderby_columns = ts_array_length(settings->fd.orderby);
for (int i = 0; i < resultRelInfo->ri_NumIndices; i++)
{
bool matches = true;
Relation index_relation = resultRelInfo->ri_IndexRelationDescs[i];
IndexInfo *index_info = resultRelInfo->ri_IndexRelationInfo[i];
/* The index must include all segment by columns and at least two metadata columns.
* Default index we build includes all segmentby columns and metadata columns (min and max,
* in that order) for all orderby columns.*/
if (index_info->ii_NumIndexKeyAttrs != num_segmentby_columns + (num_orderby_columns * 2))
{
continue;
}
for (int j = 0; j < num_segmentby_columns - 1; j++)
{
AttrNumber attno = index_relation->rd_index->indkey.values[j];
const char *attname = get_attname(index_relation->rd_index->indrelid, attno, false);
if (!ts_array_is_member(settings->fd.segmentby, attname))
{
matches = false;
break;
}
}
if (!matches)
{
continue;
}
return RelationGetRelid(index_relation);
}
return InvalidOid;
}
static void
build_column_map(const CompressionSettings *settings, const TupleDesc in_desc,
const TupleDesc out_desc, PerColumn **pcolumns, int16 **pmap,
List **pmetadata_builders)
{
Oid compressed_data_type_oid = ts_custom_type_cache_get(CUSTOM_TYPE_COMPRESSED_DATA)->type_oid;
PerColumn *columns = palloc0(sizeof(PerColumn) * in_desc->natts);
int16 *map = palloc0(sizeof(int16) * in_desc->natts);
List *metadata_builders = NIL;
SparseIndexSettings *parsed_settings = NULL;
if (settings && settings->fd.index)
{
parsed_settings = ts_convert_to_sparse_index_settings(settings->fd.index);
}
if (parsed_settings != NULL && ts_guc_enable_composite_bloom_indexes)
{
ListCell *lc;
foreach (lc, parsed_settings->objects)
{
SparseIndexSettingsObject *obj = lfirst(lc);
List *column_names = ts_get_column_names_from_parsed_object(obj);
int num_columns = list_length(column_names);
if (num_columns < 2)
{
continue;
}
Oid type_oids[MAX_BLOOM_FILTER_COLUMNS];
AttrNumber attnums[MAX_BLOOM_FILTER_COLUMNS];
int col_idx = 0;
ListCell *name_cell;
foreach (name_cell, column_names)
{
const char *col_name = (const char *) lfirst(name_cell);
AttrNumber attnum = get_attnum(settings->fd.relid, col_name);
Ensure(AttributeNumberIsValid(attnum), "could not find column '%s'", col_name);
attnums[col_idx] = attnum;
type_oids[col_idx] = get_atttype(settings->fd.relid, attnum);
col_idx++;
}
const char *bloom_col_name =
compressed_column_metadata_name_list_v2(bloom1_column_prefix, column_names);
AttrNumber bloom_attr_number = get_attnum(settings->fd.compress_relid, bloom_col_name);
if (!AttributeNumberIsValid(bloom_attr_number))
{
continue;
}
int bloom_attr_offset = AttrNumberGetAttrOffset(bloom_attr_number);
metadata_builders = lappend(metadata_builders,
batch_metadata_builder_bloom1_create(num_columns,
type_oids,
attnums,
bloom_attr_offset));
}
}
ts_free_sparse_index_settings(parsed_settings);
if (settings != NULL && OidIsValid(settings->fd.compress_relid))
{
for (int i = 0; i < in_desc->natts; i++)
{
Form_pg_attribute attr = TupleDescAttr(in_desc, i);
if (attr->attisdropped)
{
continue;
}
PerColumn *column = &columns[AttrNumberGetAttrOffset(attr->attnum)];
AttrNumber compressed_colnum =
get_attnum(settings->fd.compress_relid, NameStr(attr->attname));
Form_pg_attribute compressed_column_attr =
TupleDescAttr(out_desc, AttrNumberGetAttrOffset(compressed_colnum));
map[AttrNumberGetAttrOffset(attr->attnum)] = AttrNumberGetAttrOffset(compressed_colnum);
bool is_segmentby = ts_array_is_member(settings->fd.segmentby, NameStr(attr->attname));
bool is_orderby = ts_array_is_member(settings->fd.orderby, NameStr(attr->attname));
if (!is_segmentby)
{
if (compressed_column_attr->atttypid != compressed_data_type_oid)
{
elog(ERROR,
"expected column '%s' to be a compressed data type",
NameStr(attr->attname));
}
AttrNumber segment_min_attr_number =
compressed_column_metadata_attno(settings,
settings->fd.relid,
attr->attnum,
settings->fd.compress_relid,
"min");
AttrNumber segment_max_attr_number =
compressed_column_metadata_attno(settings,
settings->fd.relid,
attr->attnum,
settings->fd.compress_relid,
"max");
int16 segment_min_attr_offset = segment_min_attr_number - 1;
int16 segment_max_attr_offset = segment_max_attr_number - 1;
bool has_minmax_metadata = false;
if (segment_min_attr_number != InvalidAttrNumber ||
segment_max_attr_number != InvalidAttrNumber)
{
has_minmax_metadata = true;
Ensure(segment_min_attr_number != InvalidAttrNumber,
"could not find the min metadata column");
Ensure(segment_max_attr_number != InvalidAttrNumber,
"could not find the min metadata column");
metadata_builders =
lappend(metadata_builders,
batch_metadata_builder_minmax_create(attr->atttypid,
attr->attcollation,
attr->attnum,
segment_min_attr_offset,
segment_max_attr_offset));
}
const AttrNumber bloom_attr_number =
compressed_column_metadata_attno(settings,
settings->fd.relid,
attr->attnum,
settings->fd.compress_relid,
bloom1_column_prefix);
if (AttributeNumberIsValid(bloom_attr_number))
{
Oid type_oid = attr->atttypid;
AttrNumber attnum = attr->attnum;
const int bloom_attr_offset = AttrNumberGetAttrOffset(bloom_attr_number);
metadata_builders =
lappend(metadata_builders,
batch_metadata_builder_bloom1_create(1,
&type_oid,
&attnum,
bloom_attr_offset));
}
const AttrNumber first_attr_number =
compressed_column_metadata_attno(settings,
settings->fd.relid,
attr->attnum,
settings->fd.compress_relid,
"first");
const AttrNumber last_attr_number =
compressed_column_metadata_attno(settings,
settings->fd.relid,
attr->attnum,
settings->fd.compress_relid,
"last");
bool has_firstlast_metadata = false;
if (AttributeNumberIsValid(first_attr_number) &&
AttributeNumberIsValid(last_attr_number))
{
has_firstlast_metadata = true;
const int16 first_attr_offset = AttrNumberGetAttrOffset(first_attr_number);
const int16 last_attr_offset = AttrNumberGetAttrOffset(last_attr_number);
metadata_builders =
lappend(metadata_builders,
batch_metadata_builder_firstlast_create(attr->atttypid,
attr->attnum,
first_attr_offset,
last_attr_offset));
}
Ensure(!is_orderby || has_minmax_metadata || has_firstlast_metadata,
"orderby columns must have sparse index metadata");
*column = (PerColumn){
.compressor = compressor_for_type(attr->atttypid),
.segmentby_column_index = -1,
};
}
else