forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compression.c
3294 lines (2867 loc) · 99.3 KB
/
compression.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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/tableam.h>
#include <access/htup_details.h>
#include <access/multixact.h>
#include <access/valid.h>
#include <access/xact.h>
#include <catalog/heap.h>
#include <catalog/index.h>
#include <catalog/namespace.h>
#include <catalog/pg_am.h>
#include <catalog/pg_attribute.h>
#include <catalog/pg_type.h>
#include <common/base64.h>
#include <executor/nodeIndexscan.h>
#include <executor/tuptable.h>
#include <libpq/pqformat.h>
#include <miscadmin.h>
#include <nodes/nodeFuncs.h>
#include <nodes/execnodes.h>
#include <nodes/pg_list.h>
#include <nodes/print.h>
#include <parser/parsetree.h>
#include <parser/parse_coerce.h>
#include <storage/lmgr.h>
#include <storage/predicate.h>
#include <utils/builtins.h>
#include <utils/datum.h>
#include <utils/fmgroids.h>
#include <utils/lsyscache.h>
#include <utils/memutils.h>
#include <utils/portal.h>
#include <utils/rel.h>
#include <utils/relcache.h>
#include <utils/snapmgr.h>
#include <utils/syscache.h>
#include <utils/tuplesort.h>
#include <utils/typcache.h>
#include <replication/message.h>
#include "compat/compat.h"
#include "array.h"
#include "chunk.h"
#include "compression.h"
#include "create.h"
#include "custom_type_cache.h"
#include "debug_assert.h"
#include "debug_point.h"
#include "deltadelta.h"
#include "dictionary.h"
#include "gorilla.h"
#include "guc.h"
#include "nodes/chunk_dispatch/chunk_insert_state.h"
#include "nodes/hypertable_modify.h"
#include "indexing.h"
#include "segment_meta.h"
#include "ts_catalog/array_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/compression_settings.h"
#include "ts_catalog/compression_chunk_size.h"
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,
};
#if PG14_GE
/* The prefix of a logical replication message which is inserted into the
* replication stream right before decompression inserts are happening
*/
#define DECOMPRESSION_MARKER_START "::timescaledb-decompression-start"
/* The prefix of a logical replication message which is inserted into the
* replication stream right after all decompression inserts have finished
*/
#define DECOMPRESSION_MARKER_END "::timescaledb-decompression-end"
#endif
static inline void
write_logical_replication_msg_decompression_start()
{
#if PG14_GE
if (ts_guc_enable_decompression_logrep_markers && XLogLogicalInfoActive())
{
LogLogicalMessage(DECOMPRESSION_MARKER_START, "", 0, true);
}
#endif
}
static inline void
write_logical_replication_msg_decompression_end()
{
#if PG14_GE
if (ts_guc_enable_decompression_logrep_markers && XLogLogicalInfoActive())
{
LogLogicalMessage(DECOMPRESSION_MARKER_END, "", 0, true);
}
#endif
}
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);
}
DecompressionIterator *(*tsl_get_decompression_iterator_init(CompressionAlgorithm algorithm,
bool reverse))(Datum, Oid)
{
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 &&
(algorithm == COMPRESSION_ALGORITHM_DICTIONARY || algorithm == COMPRESSION_ALGORITHM_ARRAY))
{
/* Bulk decompression of array and dictionary is only supported for text. */
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,
CommandId mycid);
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 row_compressor_append_row(RowCompressor *row_compressor, TupleTableSlot *row);
static void row_compressor_flush(RowCompressor *row_compressor, CommandId mycid,
bool changed_groups);
static int create_segment_filter_scankey(RowDecompressor *decompressor,
char *segment_filter_col_name, StrategyNumber strategy,
ScanKeyData *scankeys, int num_scankeys,
Bitmapset **null_columns, Datum value, bool is_null_check);
static void create_per_compressed_column(RowDecompressor *decompressor);
/********************
** 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
Assert(rel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED);
table_close(rel, NoLock);
}
#if PG14_LT
int options = 0;
#else
ReindexParams params = { 0 };
ReindexParams *options = ¶ms;
#endif
reindex_relation(table_oid, REINDEX_REL_PROCESS_TOAST, options);
rel = table_open(table_oid, AccessExclusiveLock);
CommandCounterIncrement();
table_close(rel, NoLock);
}
/*
* 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(Relation rel)
{
int64 report_reltuples = RELTUPLES_REPORT_DEFAULT;
if (rel != NULL && rel->rd_rel->reltuples > 0)
{
report_reltuples = (int64) (0.1 * rel->rd_rel->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;
int indexscan_direction = NoMovementScanDirection;
Relation matched_index_rel = NULL;
TupleTableSlot *slot;
IndexScanDesc index_scan;
CommandId mycid = GetCurrentCommandId(true);
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(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.
*/
Relation out_rel = relation_open(out_table, ExclusiveLock);
/* 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");
TupleDesc in_desc = RelationGetDescr(in_rel);
TupleDesc out_desc = RelationGetDescr(out_rel);
/* 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;
/* Reset sequence is used for resetting the sequence without
* having to fetch the existing sequence for an individual
* sequence group. If we are rolling up an uncompressed chunk
* into an existing compressed chunk, we have to fetch
* sequence numbers for each batch of the segment using
* the respective index. In normal compression, this is
* not necessary because we start segment numbers from zero.
* We distinguish these cases by insert_options being zero for rollups.
*
* Sequence numbers are planned to be removed in the near future,
* which will render this flag obsolete.
*/
bool reset_sequence = insert_options > 0;
row_compressor_init(settings,
&row_compressor,
in_rel,
out_rel,
out_desc->natts,
true /*need_bistate*/,
reset_sequence,
insert_options);
if (matched_index_rel != NULL)
{
int64 nrows_processed = 0;
/*
* even though we log the information below, this debug info
* is still used for INFO messages to clients and our tests.
*/
if (ts_guc_debug_compression_path_info)
{
elog(INFO,
"compress_chunk_indexscan_start matched index \"%s\"",
get_rel_name(matched_index_rel->rd_id));
}
elog(LOG,
"using index \"%s\" to scan rows for compression",
get_rel_name(matched_index_rel->rd_id));
index_scan = index_beginscan(in_rel, matched_index_rel, GetTransactionSnapshot(), 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);
while (index_getnext_slot(index_scan, indexscan_direction, slot))
{
row_compressor_process_ordered_slot(&row_compressor, slot, mycid);
if ((++nrows_processed % report_reltuples) == 0)
elog(LOG,
"compressed " INT64_FORMAT " rows from \"%s\"",
nrows_processed,
RelationGetRelationName(in_rel));
}
if (row_compressor.rows_compressed_into_current_value > 0)
row_compressor_flush(&row_compressor, mycid, true);
elog(LOG,
"finished compressing " INT64_FORMAT " rows from \"%s\"",
nrows_processed,
RelationGetRelationName(in_rel));
ExecDropSingleTupleTableSlot(slot);
index_endscan(index_scan);
index_close(matched_index_rel, AccessShareLock);
}
else
{
/*
* even though we log the information below, this debug info
* is still used for INFO messages to clients and our tests.
*/
if (ts_guc_debug_compression_path_info)
{
elog(INFO, "compress_chunk_tuplesort_start");
}
elog(LOG,
"using tuplesort to scan rows from \"%s\" for compression",
RelationGetRelationName(in_rel));
Tuplesortstate *sorted_rel = compress_chunk_sort_relation(settings, in_rel);
row_compressor_append_sorted_rows(&row_compressor, sorted_rel, in_desc, in_rel);
tuplesort_end(sorted_rel);
}
row_compressor_close(&row_compressor);
DEBUG_WAITPOINT("compression_done_before_truncate_uncompressed");
truncate_relation(in_table);
table_close(out_rel, NoLock);
table_close(in_rel, NoLock);
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;
}
static Tuplesortstate *
compress_chunk_sort_relation(CompressionSettings *settings, Relation in_rel)
{
TupleDesc tupDesc = RelationGetDescr(in_rel);
Tuplesortstate *tuplesortstate;
TableScanDesc scan;
TupleTableSlot *slot;
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(in_rel),
attname,
&sort_keys[n],
&sort_operators[n],
&sort_collations[n],
&nulls_first[n]);
}
tuplesortstate = tuplesort_begin_heap(tupDesc,
n_keys,
sort_keys,
sort_operators,
sort_collations,
nulls_first,
maintenance_work_mem,
NULL,
false /*=randomAccess*/);
scan = table_beginscan(in_rel, GetLatestSnapshot(), 0, (ScanKey) 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);
return tuplesortstate;
}
void
compress_chunk_populate_sort_info_for_column(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 for setting the correct sequence number if
* we are trying to roll up chunks while compressing
*/
Oid
get_compressed_chunk_index(ResultRelInfo *resultRelInfo, CompressionSettings *settings)
{
int num_segmentby_columns = ts_array_length(settings->fd.segmentby);
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 sequence number */
if (index_info->ii_NumIndexKeyAttrs != num_segmentby_columns + 1)
continue;
for (int j = 0; j < index_info->ii_NumIndexKeyAttrs - 1; j++)
{
const char *attname =
get_attname(index_relation->rd_id, AttrOffsetGetAttrNumber(j), false);
if (!ts_array_is_member(settings->fd.segmentby, attname))
{
matches = false;
break;
}
}
if (!matches)
continue;
/* Check last index column is sequence number */
const char *attname =
get_attname(index_relation->rd_id, index_info->ii_NumIndexKeyAttrs, false);
if (strncmp(attname, COMPRESSION_COLUMN_METADATA_SEQUENCE_NUM_NAME, NAMEDATALEN) == 0)
return index_relation->rd_id;
}
return InvalidOid;
}
static int32
index_scan_sequence_number(Relation table_rel, Oid index_oid, ScanKeyData *scankey,
int num_scankeys)
{
int32 result = 0;
bool is_null;
Relation index_rel = index_open(index_oid, AccessShareLock);
IndexScanDesc index_scan =
index_beginscan(table_rel, index_rel, GetTransactionSnapshot(), num_scankeys, 0);
index_scan->xs_want_itup = true;
index_rescan(index_scan, scankey, num_scankeys, NULL, 0);
if (index_getnext_tid(index_scan, BackwardScanDirection))
{
result = index_getattr(index_scan->xs_itup,
index_scan->xs_itupdesc
->natts, /* Last attribute of the index is sequence number. */
index_scan->xs_itupdesc,
&is_null);
if (is_null)
result = 0;
}
index_endscan(index_scan);
index_close(index_rel, AccessShareLock);
return result;
}
static int32
table_scan_sequence_number(Relation table_rel, int16 seq_num_column_num, ScanKeyData *scankey,
int num_scankeys)
{
int32 max_seq_num = 0;
TupleTableSlot *slot;
TableScanDesc scan;
slot = table_slot_create(table_rel, NULL);
scan = table_beginscan(table_rel, GetLatestSnapshot(), num_scankeys, scankey);
while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
{
bool is_null;
Datum seq_num = slot_getattr(slot, seq_num_column_num, &is_null);
if (!is_null)
{
int32 curr_seq_num = DatumGetInt32(seq_num);
if (max_seq_num < curr_seq_num)
max_seq_num = curr_seq_num;
}
}
table_endscan(scan);
ExecDropSingleTupleTableSlot(slot);
return max_seq_num;
}
/* Scan compressed chunk to get the sequence number for current group.
* This is necessary to do when merging chunks. If the chunk is empty,
* scan will always return 0 and the sequence number will start from
* SEQUENCE_NUM_GAP.
*/
static int32
get_sequence_number_for_current_group(Relation table_rel, Oid index_oid,
int16 *uncompressed_col_to_compressed_col,
PerColumn *per_column, int n_input_columns,
int16 seq_num_column_num)
{
/* If there is a suitable index, use index scan otherwise fallback to heap scan. */
bool is_index_scan = OidIsValid(index_oid);
int i, num_scankeys = 0;
int32 result = 0;
for (i = 0; i < n_input_columns; i++)
{
if (per_column[i].segmentby_column_index < 1)
continue;
num_scankeys++;
}
MemoryContext scan_ctx = AllocSetContextCreate(CurrentMemoryContext,
"get max sequence number scan",
ALLOCSET_DEFAULT_SIZES);
MemoryContext old_ctx;
old_ctx = MemoryContextSwitchTo(scan_ctx);
ScanKeyData *scankey = NULL;
if (num_scankeys > 0)
{
scankey = palloc0(sizeof(ScanKeyData) * num_scankeys);
for (i = 0; i < n_input_columns; i++)
{
if (per_column[i].segmentby_column_index < 1)
continue;
PerColumn col = per_column[i];
int16 attno = is_index_scan ?
col.segmentby_column_index :
AttrOffsetGetAttrNumber(uncompressed_col_to_compressed_col[i]);
if (col.segment_info->is_null)
{
ScanKeyEntryInitialize(&scankey[col.segmentby_column_index - 1],
SK_ISNULL | SK_SEARCHNULL,
attno,
InvalidStrategy, /* no strategy */
InvalidOid, /* no strategy subtype */
InvalidOid, /* no collation */
InvalidOid, /* no reg proc for this */
(Datum) 0); /* constant */
}
else
{
ScanKeyEntryInitializeWithInfo(&scankey[col.segmentby_column_index - 1],
0, /* flags */
attno,
BTEqualStrategyNumber,
InvalidOid, /* No strategy subtype. */
col.segment_info->collation,
&col.segment_info->eq_fn,
col.segment_info->val);
}
}
}
if (is_index_scan)
{
/* Index scan should always use at least one scan key to get the sequence number. */
Assert(num_scankeys > 0);
result = index_scan_sequence_number(table_rel, index_oid, scankey, num_scankeys);
}
else
{
/* Table scan can work without scan keys. */
result = table_scan_sequence_number(table_rel, seq_num_column_num, scankey, num_scankeys);
}
MemoryContextSwitchTo(old_ctx);
MemoryContextDelete(scan_ctx);
return result + SEQUENCE_NUM_GAP;
}
static void
build_column_map(CompressionSettings *settings, Relation uncompressed_table,
Relation compressed_table, PerColumn **pcolumns, int16 **pmap)
{
Oid compressed_data_type_oid = ts_custom_type_cache_get(CUSTOM_TYPE_COMPRESSED_DATA)->type_oid;
TupleDesc out_desc = RelationGetDescr(compressed_table);
TupleDesc in_desc = RelationGetDescr(uncompressed_table);
PerColumn *columns = palloc0(sizeof(PerColumn) * in_desc->natts);
int16 *map = palloc0(sizeof(int16) * in_desc->natts);
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(compressed_table->rd_id, 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,
uncompressed_table->rd_id,
attr->attnum,
compressed_table->rd_id,
"min");
AttrNumber segment_max_attr_number =
compressed_column_metadata_attno(settings,
uncompressed_table->rd_id,
attr->attnum,
compressed_table->rd_id,
"max");
int16 segment_min_attr_offset = segment_min_attr_number - 1;
int16 segment_max_attr_offset = segment_max_attr_number - 1;
SegmentMetaMinMaxBuilder *segment_min_max_builder = NULL;
if (segment_min_attr_number != InvalidAttrNumber ||
segment_max_attr_number != InvalidAttrNumber)
{
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");
segment_min_max_builder =
segment_meta_min_max_builder_create(attr->atttypid, attr->attcollation);
}
Ensure(!is_orderby || segment_min_max_builder != NULL,
"orderby columns must have minmax metadata");
*column = (PerColumn){
.compressor = compressor_for_type(attr->atttypid),
.min_metadata_attr_offset = segment_min_attr_offset,
.max_metadata_attr_offset = segment_max_attr_offset,
.min_max_metadata_builder = segment_min_max_builder,
.segmentby_column_index = -1,
};
}
else
{
if (attr->atttypid != compressed_column_attr->atttypid)
elog(ERROR,
"expected segment by column \"%s\" to be same type as uncompressed column",
NameStr(attr->attname));
int16 index = ts_array_position(settings->fd.segmentby, NameStr(attr->attname));
*column = (PerColumn){
.segment_info = segment_info_new(attr),
.segmentby_column_index = index,
.min_metadata_attr_offset = -1,
.max_metadata_attr_offset = -1,
};
}
}
*pcolumns = columns;
*pmap = map;
}
/********************
** row_compressor **
********************/
void
row_compressor_init(CompressionSettings *settings, RowCompressor *row_compressor,
Relation uncompressed_table, Relation compressed_table,
int16 num_columns_in_compressed_table, bool need_bistate, bool reset_sequence,
int insert_options)
{
Name count_metadata_name = DatumGetName(
DirectFunctionCall1(namein, CStringGetDatum(COMPRESSION_COLUMN_METADATA_COUNT_NAME)));
Name sequence_num_metadata_name = DatumGetName(
DirectFunctionCall1(namein,
CStringGetDatum(COMPRESSION_COLUMN_METADATA_SEQUENCE_NUM_NAME)));
AttrNumber count_metadata_column_num =
get_attnum(compressed_table->rd_id, NameStr(*count_metadata_name));
AttrNumber sequence_num_column_num =
get_attnum(compressed_table->rd_id, NameStr(*sequence_num_metadata_name));
if (count_metadata_column_num == InvalidAttrNumber)
elog(ERROR,
"missing metadata column '%s' in compressed table",
COMPRESSION_COLUMN_METADATA_COUNT_NAME);
if (sequence_num_column_num == InvalidAttrNumber)
elog(ERROR,
"missing metadata column '%s' in compressed table",
COMPRESSION_COLUMN_METADATA_SEQUENCE_NUM_NAME);
*row_compressor = (RowCompressor){
.per_row_ctx = AllocSetContextCreate(CurrentMemoryContext,
"compress chunk per-row",
ALLOCSET_DEFAULT_SIZES),
.compressed_table = compressed_table,
.bistate = need_bistate ? GetBulkInsertState() : NULL,
.resultRelInfo = ts_catalog_open_indexes(compressed_table),
.n_input_columns = RelationGetDescr(uncompressed_table)->natts,
.count_metadata_column_offset = AttrNumberGetAttrOffset(count_metadata_column_num),
.sequence_num_metadata_column_offset = AttrNumberGetAttrOffset(sequence_num_column_num),
.compressed_values = palloc(sizeof(Datum) * num_columns_in_compressed_table),
.compressed_is_null = palloc(sizeof(bool) * num_columns_in_compressed_table),
.rows_compressed_into_current_value = 0,
.rowcnt_pre_compression = 0,
.num_compressed_rows = 0,