-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcreate.c
More file actions
2465 lines (2188 loc) · 75 KB
/
Copy pathcreate.c
File metadata and controls
2465 lines (2188 loc) · 75 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/heapam.h>
#include <access/reloptions.h>
#include <access/tupdesc.h>
#include <access/xact.h>
#include <catalog/index.h>
#include <catalog/indexing.h>
#include <catalog/objectaccess.h>
#include <catalog/pg_am_d.h>
#include <catalog/pg_constraint.h>
#include <catalog/pg_constraint_d.h>
#include <catalog/pg_type.h>
#include <catalog/toasting.h>
#include <commands/alter.h>
#include <commands/defrem.h>
#include <commands/tablecmds.h>
#include <commands/tablespace.h>
#include <common/md5.h>
#include <executor/spi.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <parser/parse_type.h>
#include <storage/lmgr.h>
#include <tcop/utility.h>
#include <utils/array.h>
#include <utils/builtins.h>
#include <utils/datum.h>
#include <utils/guc.h>
#include <utils/rel.h>
#include <utils/syscache.h>
#include <utils/typcache.h>
#include "compat/compat.h"
#include "bgw_policy/policies_v2.h"
#include "chunk.h"
#include "chunk_index.h"
#include "compression.h"
#include "compression/compression_storage.h"
#include "compression/sparse_index_bloom1.h"
#include "create.h"
#include "custom_type_cache.h"
#include "dimension.h"
#include "foreach_ptr.h"
#include "guc.h"
#include "hypertable_cache.h"
#include "jsonb_utils.h"
#include "trigger.h"
#include "ts_catalog/array_utils.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/compression_settings.h"
#include "ts_catalog/continuous_agg.h"
#include "utils.h"
#include "with_clause/alter_table_with_clause.h"
#include "with_clause/create_table_with_clause.h"
#include "bgw_policy/compression_api.h"
static const char *sparse_index_types[] = { "min", "max" };
#ifdef USE_ASSERT_CHECKING
static bool
is_sparse_index_type(const char *type)
{
for (size_t i = 0; i < sizeof(sparse_index_types) / sizeof(sparse_index_types[0]); i++)
{
if (strcmp(sparse_index_types[i], type) == 0)
{
return true;
}
}
if (strcmp(bloom1_column_prefix, type) == 0)
{
return true;
}
if (ts_guc_read_legacy_bloom1_v1 && strcmp("bloom1", type) == 0)
{
return true;
}
return false;
}
#endif
static void validate_hypertable_for_compression(Hypertable *ht);
static List *build_columndefs(CompressionSettings *settings, Oid src_reloid);
static ColumnDef *build_columndef_singlecolumn(const char *colname, Oid typid);
static void compression_settings_set_manually_for_create(Hypertable *ht,
CompressionSettings *settings,
WithClauseResult *with_clause_options);
static void compression_settings_set_manually_for_alter(Hypertable *ht,
CompressionSettings *settings,
WithClauseResult *with_clause_options);
static void create_default_composite_bloom(IndexInfo *index_info, Hypertable *ht,
CompressionSettings *settings,
JsonbParseState *parse_state,
TsBmsList *sparse_index_columns, bool *has_object);
static char *
compression_column_segment_metadata_name(const char *type, int16 column_index)
{
Assert(is_sparse_index_type(type));
char *buf = palloc(sizeof(char) * NAMEDATALEN);
Assert(column_index > 0);
int ret =
snprintf(buf, NAMEDATALEN, COMPRESSION_COLUMN_METADATA_PATTERN_V1, type, column_index);
if (ret < 0 || ret >= NAMEDATALEN)
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR), errmsg("bad segment metadata column name")));
}
return buf;
}
/*
* Validate that compression settings don't exceed PostgreSQL's INDEX_MAX_KEYS limit.
*
* Compression creates an implicit index on the compressed chunk with:
* - 1 index key per segmentby column
* - 2 index keys per orderby column (for min/max metadata)
*/
static void
validate_compression_index_key_limit(CompressionSettings *settings)
{
int num_segmentby_keys = ts_array_length(settings->fd.segmentby);
int num_orderby_keys = 2 * ts_array_length(settings->fd.orderby);
if ((num_segmentby_keys + num_orderby_keys) > INDEX_MAX_KEYS)
{
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_COLUMNS),
errmsg("too many segmentby and orderby columns"),
errdetail("Combined segmentby keys (%d) and orderby keys (%d) cannot exceed %d",
num_segmentby_keys,
num_orderby_keys,
INDEX_MAX_KEYS)));
}
}
char *
column_segment_min_name(int16 column_index)
{
return compression_column_segment_metadata_name("min", column_index);
}
char *
column_segment_max_name(int16 column_index)
{
return compression_column_segment_metadata_name("max", column_index);
}
/*
* Get metadata name for a given column name and metadata type, format version 2.
* We can't reference the attribute numbers, because they can change after
* drop/restore if we had any dropped columns.
* We might have to truncate the column names to fit into the NAMEDATALEN here,
* in this case we disambiguate them with their md5 hash.
*/
char *
compressed_column_metadata_name_v2(const char *metadata_type, const char **column_names,
int num_columns)
{
Assert(is_sparse_index_type(metadata_type));
Assert(strlen(metadata_type) <= 6);
Assert(column_names != NULL);
Assert(num_columns > 0);
Assert(num_columns <= MAX_BLOOM_FILTER_COLUMNS);
int len = 0;
/* Use a separate buffer for the hash computation */
StringInfoData buf = { 0 }, hash_buf = { 0 };
initStringInfo(&buf);
initStringInfo(&hash_buf);
for (int i = 0; i < num_columns; i++)
{
Assert(column_names[i] != NULL);
#ifdef USE_ASSERT_CHECKING
int col_len = strlen(column_names[i]);
#endif
Assert(col_len > 0 && col_len < NAMEDATALEN);
if (i > 0)
{
appendStringInfoChar(&buf, '_');
/* The separator for hash purposes needs to be something
* that is not valid in Postgres, hence the zero byte */
appendStringInfoChar(&hash_buf, '\0');
}
appendStringInfo(&buf, "%s", column_names[i]);
appendBinaryStringInfo(&hash_buf, column_names[i], strlen(column_names[i]));
}
len = buf.len;
/*
* We have to fit the name into NAMEDATALEN - 1 which is 63 bytes:
* 12 (_ts_meta_v2_) + 6 (metadata_type) + [1 (_) + x (column_name)]x num_columns + 1 (_) + 4
* (hash) = 63; x = 63 - 24 = 39.
*
* Fix for bug #9578: we need to differentiate between ('a_b', 'c') and ('a', 'b_c') composite
* column names, for this reason we always go through the hash path for composite column names.
*/
char *result;
if (len > 39 || num_columns > 1)
{
const char *errstr = NULL;
char hash[33];
Ensure(pg_md5_hash(hash_buf.data, hash_buf.len, hash, &errstr), "md5 computation failure");
result = psprintf("_ts_meta_v2_%.6s_%.4s_%.39s", metadata_type, hash, buf.data);
}
else
{
result = psprintf("_ts_meta_v2_%.6s_%.39s", metadata_type, buf.data);
}
Assert(strlen(result) < NAMEDATALEN);
return result;
}
char *
compressed_column_metadata_name_list_v2(const char *metadata_type, List *column_names_list)
{
int num_column_names = list_length(column_names_list);
Ensure(num_column_names > 0, "list of column names must be non-empty");
Ensure(num_column_names <= MAX_BLOOM_FILTER_COLUMNS,
"list of column names must be less than or equal to %d, got %d",
MAX_BLOOM_FILTER_COLUMNS,
num_column_names);
const char *column_names[MAX_BLOOM_FILTER_COLUMNS];
ListCell *cell = NULL;
int i = 0;
foreach (cell, column_names_list)
{
column_names[i] = (const char *) lfirst(cell);
i++;
}
return compressed_column_metadata_name_v2(metadata_type, column_names, num_column_names);
}
int
compressed_column_metadata_attno(const CompressionSettings *settings, Oid chunk_reloid,
AttrNumber chunk_attno, Oid compressed_reloid,
char const *metadata_type)
{
Assert(is_sparse_index_type(metadata_type));
char *attname = get_attname(chunk_reloid, chunk_attno, /* missing_ok = */ false);
int16 orderby_pos = ts_array_position(settings->fd.orderby, attname);
if (orderby_pos != 0 &&
(strcmp(metadata_type, "min") == 0 || strcmp(metadata_type, "max") == 0))
{
char *metadata_name = compression_column_segment_metadata_name(metadata_type, orderby_pos);
return get_attnum(compressed_reloid, metadata_name);
}
char *metadata_name =
compressed_column_metadata_name_v2(metadata_type, (const char **) &attname, 1);
return get_attnum(compressed_reloid, metadata_name);
}
/*
* The heuristic for whether we should use the bloom filter sparse index.
*/
static bool
should_create_bloom_sparse_index(Oid atttypid, TypeCacheEntry *type, Oid src_reloid)
{
/*
* The index must be enabled by the GUC.
*/
if (!ts_guc_enable_sparse_index_bloom)
{
return false;
}
/*
* The type must be hashable. For some types we use our own hash functions
* which have better characteristics.
*/
FmgrInfo *finfo = NULL;
if (bloom1_get_hash_function(atttypid, &finfo) == NULL)
{
return false;
}
/*
* For time types, we expect:
* 1) range queries, not equality,
* 2) correlation with the orderby columns, e.g. creation time correlates
* with the update time that is used as orderby.
* This makes minmax indexes more suitable than bloom filters.
*/
if (atttypid == TIMESTAMPTZOID || atttypid == TIMESTAMPOID || atttypid == TIMEOID ||
atttypid == TIMETZOID || atttypid == DATEOID)
{
return false;
}
/*
* For fractional arithmetic types, equality queries are unlikely.
*/
if (atttypid == FLOAT4OID || atttypid == FLOAT8OID || atttypid == NUMERICOID)
{
return false;
}
/*
* Bloom filters for 1k elements with 2% false positive rate require about
* one byte per element, so there's no point in using them for smaller data
* types that typically compress to less than that.
*/
if (type->typlen > 0 && type->typlen < 4)
{
return false;
}
return true;
}
/*
* Create a column definition for a sparse index column. The attributes passed is a
* List of Form_pg_attribute elements. Min and max indices only use
* the first element. Bloom filters may use multiple columns.
*/
static ColumnDef *
create_sparse_index_column_def(List *attributes, const char *metadata_type)
{
Assert(is_sparse_index_type(metadata_type));
ColumnDef *column_def = NULL;
List *column_names = NIL;
/* At least one valid attribute must be present */
Assert(attributes != NULL);
Assert(list_length(attributes) > 0);
Assert(list_length(attributes) <= MAX_BLOOM_FILTER_COLUMNS);
const bool is_bloom = strcmp(metadata_type, bloom1_column_prefix) == 0;
{
/* Populate the column names array */
ListCell *cell = NULL;
int i = 0;
foreach (cell, attributes)
{
Form_pg_attribute attr = (Form_pg_attribute) lfirst(cell);
Ensure(i < MAX_BLOOM_FILTER_COLUMNS,
"too many columns for bloom filter, got %d, max %d, name: %s",
i + 1,
MAX_BLOOM_FILTER_COLUMNS,
NameStr(attr->attname));
column_names = lappend(column_names, NameStr(attr->attname));
i++;
}
}
if (is_bloom)
{
/*
* The types must be hashable. For some types we use our own hash functions
* which have better characteristics.
*/
ListCell *cell = NULL;
foreach (cell, attributes)
{
Form_pg_attribute attr = (Form_pg_attribute) lfirst(cell);
FmgrInfo *finfo = NULL;
if (bloom1_get_hash_function(attr->atttypid, &finfo) == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("invalid bloom filter column type %s, name: %s",
format_type_be(attr->atttypid),
NameStr(attr->attname)),
errdetail("Could not identify a hashing function for the type.")));
}
}
column_def =
makeColumnDef(compressed_column_metadata_name_list_v2(metadata_type, column_names),
ts_custom_type_cache_get(CUSTOM_TYPE_BLOOM1)->type_oid,
/* typmod = */ -1,
/* collation = */ 0);
/*
* We have our custom compression for bloom filters, and the
* result is almost incompressible with lz4 (~2%), so disable it.
*/
column_def->storage = TYPSTORAGE_EXTERNAL;
/* Composite bloom filters are more selective, try to store them inline. */
if (list_length(column_names) > 1)
{
column_def->storage = TYPSTORAGE_MAIN;
}
}
else /* either min or max */
{
Form_pg_attribute attr = (Form_pg_attribute) lfirst(list_head(attributes));
TypeCacheEntry *type = lookup_type_cache(attr->atttypid, TYPECACHE_LT_OPR);
/*
* a comparison operator if required for min max operations
*/
if (!OidIsValid(type->lt_opr))
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("invalid minmax column type %s", format_type_be(attr->atttypid)),
errdetail("Could not identify a less-than operator for the type.")));
}
column_def =
makeColumnDef(compressed_column_metadata_name_list_v2(metadata_type, column_names),
attr->atttypid,
attr->atttypmod,
attr->attcollation);
if (attr->attstorage != TYPSTORAGE_PLAIN)
{
column_def->storage = TYPSTORAGE_MAIN;
}
}
return column_def;
}
/*
* return the columndef list for compressed hypertable.
* we do this by getting the source hypertable's attrs,
* 1. validate the segmentby cols and orderby cols exists in this list and
* 2. create the columndefs for the new compressed hypertable
* segmentby_cols have same datatype as the original table
* all other cols have COMPRESSEDDATA_TYPE type
*/
static List *
build_columndefs(CompressionSettings *settings, Oid src_reloid)
{
Oid compresseddata_oid = ts_custom_type_cache_get(CUSTOM_TYPE_COMPRESSED_DATA)->type_oid;
ArrayType *segmentby = settings->fd.segmentby;
List *compressed_column_defs = NIL;
List *segmentby_column_defs = NIL;
Jsonb *sparse_cfg = settings->fd.index;
SparseIndexSettings *parsed_settings =
sparse_cfg ? ts_convert_to_sparse_index_settings(sparse_cfg) : NULL;
Bitmapset *all_composite_bloom_obj_ids = NULL;
List *per_column_settings = ts_get_per_column_compression_settings(parsed_settings);
Relation rel = table_open(src_reloid, AccessShareLock);
TupleDesc tupdesc = rel->rd_att;
int num_sparse_index_objects =
parsed_settings != NULL ? list_length(parsed_settings->objects) : 0;
List **composite_attr_lists = NULL;
if (num_sparse_index_objects > 0)
{
/* Allocate an array of Lists that contain Form_pg_attribute elements for each sparse index
* configuration object. Minmax and single bloom filter configuration objects will have a
* single element list.
*/
composite_attr_lists = palloc0(sizeof(List *) * num_sparse_index_objects);
}
for (int attoffset = 0; attoffset < tupdesc->natts; attoffset++)
{
Form_pg_attribute attr = TupleDescAttr(tupdesc, attoffset);
if (attr->attisdropped)
{
continue;
}
if (strncmp(NameStr(attr->attname),
COMPRESSION_COLUMN_METADATA_PREFIX,
strlen(COMPRESSION_COLUMN_METADATA_PREFIX)) == 0)
{
ereport(ERROR,
(errcode(ERRCODE_RESERVED_NAME),
errmsg("cannot convert tables with reserved column prefix '%s'",
COMPRESSION_COLUMN_METADATA_PREFIX)));
}
bool is_segmentby = ts_array_is_member(segmentby, NameStr(attr->attname));
if (is_segmentby)
{
segmentby_column_defs = lappend(segmentby_column_defs,
makeColumnDef(NameStr(attr->attname),
attr->atttypid,
attr->atttypmod,
attr->attcollation));
continue;
}
PerColumnCompressionSettings *per_column_setting =
per_column_settings ?
ts_get_per_column_compression_settings_by_column_name(per_column_settings,
NameStr(attr->attname)) :
NULL;
if (per_column_setting != NULL && composite_attr_lists != NULL)
{
if (per_column_setting->minmax_obj_id != -1 &&
per_column_setting->minmax_obj_id < num_sparse_index_objects)
{
/* Minmax index configuration objects will have a single element list */
Assert(list_length(composite_attr_lists[per_column_setting->minmax_obj_id]) == 0);
composite_attr_lists[per_column_setting->minmax_obj_id] =
lappend(composite_attr_lists[per_column_setting->minmax_obj_id], attr);
}
if (per_column_setting->single_bloom_obj_id != -1 &&
per_column_setting->single_bloom_obj_id < num_sparse_index_objects)
{
/* Single bloom filter configuration objects will have a single element list */
Assert(list_length(composite_attr_lists[per_column_setting->single_bloom_obj_id]) ==
0);
composite_attr_lists[per_column_setting->single_bloom_obj_id] =
lappend(composite_attr_lists[per_column_setting->single_bloom_obj_id], attr);
}
if (per_column_setting->composite_bloom_index_obj_ids != NULL)
{
/* The bitmapset tells which sparse index configuration objects the current
* column participates in. Iterate over the bitmapset and add an entry
* to the composite_attr_lists. */
int i = -1;
while ((i = bms_next_member(per_column_setting->composite_bloom_index_obj_ids,
i)) >= 0)
{
composite_attr_lists[i] = lappend(composite_attr_lists[i], attr);
}
/* capture all composite bloom index objects */
all_composite_bloom_obj_ids =
bms_union(all_composite_bloom_obj_ids,
per_column_setting->composite_bloom_index_obj_ids);
}
}
/*
* This is either an orderby or a normal compressed column. We want to
* have metadata for some of them. Put the metadata columns before the
* respective compressed column, because they are accessed before
* decompression.
*/
const bool is_orderby = ts_array_is_member(settings->fd.orderby, NameStr(attr->attname));
if (is_orderby)
{
int index = ts_array_position(settings->fd.orderby, NameStr(attr->attname));
TypeCacheEntry *type = lookup_type_cache(attr->atttypid, TYPECACHE_LT_OPR);
/*
* We must be able to create the metadata for the orderby columns,
* because it is required for sorting.
*/
if (!OidIsValid(type->lt_opr))
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_FUNCTION),
errmsg("invalid ordering column type %s", format_type_be(attr->atttypid)),
errdetail("Could not identify a less-than operator for the type.")));
}
/* segment_meta min and max columns */
ColumnDef *def = makeColumnDef(column_segment_min_name(index),
attr->atttypid,
attr->atttypmod,
attr->attcollation);
def->storage = TYPSTORAGE_PLAIN;
compressed_column_defs = lappend(compressed_column_defs, def);
def = makeColumnDef(column_segment_max_name(index),
attr->atttypid,
attr->atttypmod,
attr->attcollation);
def->storage = TYPSTORAGE_PLAIN;
compressed_column_defs = lappend(compressed_column_defs, def);
}
else if (per_column_setting != NULL && composite_attr_lists != NULL)
{
/* check sparse index columndefs is applicable */
bool is_bloom = per_column_setting->single_bloom_obj_id != -1;
bool is_minmax = per_column_setting->minmax_obj_id != -1;
/*
* We allow only one sparse index per column. Columns used in the ORDER BY
* clause implicitly have a minmax index and adding a bloom filter on them is not
* allowed.
*
* The parser is expected to enforce this constraint earlier, but we check again
* here as a safeguard.
*/
Ensure((!is_bloom || !is_minmax),
"Should not create bloom filter for minmax column \"%s\"",
NameStr(attr->attname));
/* build sparse index columndefs if applicable */
if (is_bloom)
{
if (!ts_guc_enable_sparse_index_bloom)
{
ereport(WARNING,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("Creating bloom sparse index is disabled"),
errhint("Either set \"enable_sparse_index_bloom\" to true or remove "
"the bloom filter indexes from \"sparse_index\" configuration "
"of the hypertable.")));
}
/*
* Add bloom filter sparse index for this column.
*/
ColumnDef *bloom_column_def =
create_sparse_index_column_def(composite_attr_lists[per_column_setting
->single_bloom_obj_id],
bloom1_column_prefix);
compressed_column_defs = lappend(compressed_column_defs, bloom_column_def);
}
else if (is_minmax)
{
/*
* Add minmax sparse index for this column.
*/
ColumnDef *def =
create_sparse_index_column_def(composite_attr_lists[per_column_setting
->minmax_obj_id],
"min");
compressed_column_defs = lappend(compressed_column_defs, def);
def = create_sparse_index_column_def(composite_attr_lists[per_column_setting
->minmax_obj_id],
"max");
compressed_column_defs = lappend(compressed_column_defs, def);
}
}
compressed_column_defs = lappend(compressed_column_defs,
makeColumnDef(NameStr(attr->attname),
compresseddata_oid,
/* typmod = */ -1,
/* collOid = */ InvalidOid));
}
/* add the composite bloom columns */
if (composite_attr_lists != NULL && per_column_settings != NULL)
{
/* iterate over the all_composite_bloom_obj_ids bitmapset */
int i = -1;
while ((i = bms_next_member(all_composite_bloom_obj_ids, i)) >= 0)
{
Assert(i < num_sparse_index_objects);
Assert(composite_attr_lists[i] != NULL);
List *attr_list = composite_attr_lists[i];
if (attr_list != NULL)
{
ColumnDef *def = create_sparse_index_column_def(attr_list, bloom1_column_prefix);
compressed_column_defs = lappend(compressed_column_defs, def);
}
}
}
/*
* Add the metadata columns. Count is always accessed, so put it first.
*/
List *all_column_defs = list_make1(makeColumnDef(COMPRESSION_COLUMN_METADATA_COUNT_NAME,
INT4OID,
-1 /* typemod */,
0 /*collation*/));
/*
* Then, put all segmentby columns. They are likely to be used in filters
* before decompression.
*/
all_column_defs = list_concat(all_column_defs, segmentby_column_defs);
/*
* Then, put all the compressed columns.
*/
all_column_defs = list_concat(all_column_defs, compressed_column_defs);
table_close(rel, AccessShareLock);
return all_column_defs;
}
/* use this api for the case when you add a single column to a table that already has
* compression setup
* such as ALTER TABLE xyz ADD COLUMN .....
*/
static ColumnDef *
build_columndef_singlecolumn(const char *colname, Oid typid)
{
Oid compresseddata_oid = ts_custom_type_cache_get(CUSTOM_TYPE_COMPRESSED_DATA)->type_oid;
if (strncmp(colname,
COMPRESSION_COLUMN_METADATA_PREFIX,
strlen(COMPRESSION_COLUMN_METADATA_PREFIX)) == 0)
{
ereport(ERROR,
(errcode(ERRCODE_RESERVED_NAME),
errmsg("cannot convert tables with reserved column prefix '%s'",
COMPRESSION_COLUMN_METADATA_PREFIX)));
}
return makeColumnDef(colname, compresseddata_oid, -1 /*typmod*/, 0 /*collation*/);
}
/*
* Create compress chunk for specific table.
*
* If table_id is InvalidOid, create a new table.
*
*/
Chunk *
create_compress_chunk(Hypertable *compress_ht, Chunk *src_chunk, Oid table_id,
bool skip_segmentby_default, CompressionSettings *settings)
{
Catalog *catalog = ts_catalog_get();
CatalogSecurityContext sec_ctx;
Chunk *compress_chunk;
int namelen;
Oid tablespace_oid;
bool settings_provided = (settings != NULL);
Assert(compress_ht->space->num_dimensions == 0);
/* Create a new catalog entry for chunk based on uncompressed chunk */
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
compress_chunk =
ts_chunk_create_base(ts_catalog_table_next_seq_id(catalog, CHUNK), 0, RELKIND_RELATION);
ts_catalog_restore_user(&sec_ctx);
compress_chunk->fd.hypertable_id = compress_ht->fd.id;
compress_chunk->hypertable_relid = compress_ht->main_table_relid;
namestrcpy(&compress_chunk->fd.schema_name, INTERNAL_SCHEMA_NAME);
if (OidIsValid(table_id))
{
Relation table_rel = table_open(table_id, AccessShareLock);
strncpy(NameStr(compress_chunk->fd.table_name),
RelationGetRelationName(table_rel),
NAMEDATALEN);
table_close(table_rel, AccessShareLock);
}
else
{
/* Fail if we overflow the name limit */
namelen = snprintf(NameStr(compress_chunk->fd.table_name),
NAMEDATALEN,
"compress%s_%d_chunk",
NameStr(compress_ht->fd.associated_table_prefix),
compress_chunk->fd.id);
if (namelen >= NAMEDATALEN)
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("invalid name \"%s\" for compressed chunk",
NameStr(compress_chunk->fd.table_name)),
errdetail("The associated table prefix is too long.")));
}
}
/* Insert chunk */
ts_chunk_insert_lock(compress_chunk, RowExclusiveLock);
/* Create the actual table relation for the chunk
* Note that we have to pick the tablespace here as the compressed ht doesn't have dimensions
* on which to base this decision. We simply pick the same tablespace as the uncompressed chunk
* for now.
*/
tablespace_oid = get_rel_tablespace(src_chunk->table_id);
if (!settings_provided)
{
settings = ts_compression_settings_get(src_chunk->hypertable_relid);
/*
* On hypertables created with CREATE TABLE ... WITH we enable compression
* by default but do not create CompressionSettings immediately assuming
* that we have more information available when the first compression
* is actually triggered allowing us to generate better compression
* settings.
*/
if (!settings)
{
settings = ts_compression_settings_create(src_chunk->hypertable_relid,
InvalidOid,
NULL,
NULL,
NULL,
NULL,
NULL);
}
Hypertable *ht = ts_hypertable_get_by_id(src_chunk->fd.hypertable_id);
compression_settings_set_defaults(ht,
settings,
ts_alter_table_with_clause_parse(NIL),
skip_segmentby_default);
}
if (OidIsValid(table_id))
{
compress_chunk->table_id = table_id;
}
else
{
List *column_defs = build_columndefs(settings, src_chunk->table_id);
compress_chunk->table_id = compression_chunk_create(src_chunk,
compress_chunk,
column_defs,
tablespace_oid,
settings);
}
if (!OidIsValid(compress_chunk->table_id))
{
elog(ERROR, "could not create columnstore chunk table");
}
/* Materialize current compression settings for this chunk */
if (!settings_provided)
{
ts_compression_settings_materialize(settings,
src_chunk->table_id,
compress_chunk->table_id);
}
else
{
settings->fd.compress_relid = compress_chunk->table_id;
ts_compression_settings_update(settings);
}
/* if the src chunk is not in the default tablespace, the compressed indexes
* should also be in a non-default tablespace. IN the usual case, this is inferred
* from the hypertable's and chunk's tablespace info. We do not propagate
* attach_tablespace settings to the compressed hypertable. So we have to explicitly
* pass the tablespace information here
*/
ts_chunk_index_create_all(compress_chunk->fd.hypertable_id,
compress_chunk->hypertable_relid,
compress_chunk->fd.id,
compress_chunk->table_id,
tablespace_oid);
return compress_chunk;
}
/* Add the hypertable time column to the end of the orderby list if
* it's not already in the orderby or segmentby. */
static OrderBySettings
add_time_to_order_by_if_not_included(OrderBySettings obs, ArrayType *segmentby, Hypertable *ht)
{
const Dimension *time_dim;
const char *time_col_name;
bool found = false;
time_dim = hyperspace_get_open_dimension(ht->space, 0);
if (!time_dim)
{
return obs;
}
time_col_name = get_attname(ht->main_table_relid, time_dim->column_attno, false);
if (ts_array_is_member(obs.orderby, time_col_name))
{
found = true;
}
if (ts_array_is_member(segmentby, time_col_name))
{
found = true;
}
if (!found)
{
/* Add time DESC NULLS FIRST to order by settings */
obs.orderby = ts_array_add_element_text(obs.orderby, pstrdup(time_col_name));
obs.orderby_desc = ts_array_add_element_bool(obs.orderby_desc, true);
obs.orderby_nullsfirst = ts_array_add_element_bool(obs.orderby_nullsfirst, true);
}
return obs;
}
/* returns list of constraints that need to be cloned on the compressed hypertable
* This is limited to foreign key constraints now
*/
static void
validate_existing_constraints(Hypertable *ht, CompressionSettings *settings)
{
Relation pg_constr;
SysScanDesc scan;
ScanKeyData scankey;
HeapTuple tuple;
ArrayType *arr;
Assert(ht->main_table_relid == settings->fd.relid);
pg_constr = table_open(ConstraintRelationId, AccessShareLock);
ScanKeyInit(&scankey,
Anum_pg_constraint_conrelid,
BTEqualStrategyNumber,
F_OIDEQ,
ObjectIdGetDatum(settings->fd.relid));
scan = systable_beginscan(pg_constr, ConstraintRelidTypidNameIndexId, true, NULL, 1, &scankey);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
Form_pg_constraint form = (Form_pg_constraint) GETSTRUCT(tuple);
/*
* We check primary, unique, and exclusion constraints.
*/
if (form->contype == CONSTRAINT_CHECK || form->contype == CONSTRAINT_TRIGGER
#if PG17_GE
|| form->contype == CONSTRAINT_NOTNULL
/* CONSTRAINT_NOTNULL introduced in PG17, see b0e96f311985 */
#endif
)
{
continue;
}
else if (form->contype == CONSTRAINT_EXCLUSION)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("constraint %s is not supported for converting to columnstore",
NameStr(form->conname)),
errhint("Exclusion constraints are not supported on hypertables that are "
"converted to columnstore.")));
}
else
{
int j, numkeys;
int16 *attnums;
bool is_null;
/* Extract the conkey array, ie, attnums of PK's columns */
Datum adatum = heap_getattr(tuple,
Anum_pg_constraint_conkey,
RelationGetDescr(pg_constr),
&is_null);
if (is_null)
{
Oid oid = heap_getattr(tuple,
Anum_pg_constraint_oid,
RelationGetDescr(pg_constr),
&is_null);
elog(ERROR, "null conkey for constraint %u", oid);
}
arr = DatumGetArrayTypeP(adatum); /* ensure not toasted */
numkeys = ts_array_length(arr);
attnums = (int16 *) ARR_DATA_PTR(arr);
for (j = 0; j < numkeys; j++)
{
const char *attname = get_attname(settings->fd.relid, attnums[j], false);
/* is colno a segment-by or order_by column */
if (!form->conindid && (settings->fd.segmentby && settings->fd.orderby) &&
!ts_array_is_member(settings->fd.segmentby, attname) &&
!ts_array_is_member(settings->fd.orderby, attname))
{
ereport(WARNING,
(errmsg("column \"%s\" should be used for segmenting or ordering",
attname)));
}
}
}
}
systable_endscan(scan);
table_close(pg_constr, AccessShareLock);
}
/*
* Validate existing indexes on the hypertable. Note that there can be indexes
* that do not have a corresponding constraint.
*
* We pass in a list of indexes that we should ignore since these are checked
* by the constraint checking above.
*/
static void
validate_existing_indexes(Hypertable *ht, CompressionSettings *settings)
{
Relation pg_index;
HeapTuple htup;
ScanKeyData skey;
SysScanDesc indscan;
ScanKeyInit(&skey,
Anum_pg_index_indrelid,
BTEqualStrategyNumber,
F_OIDEQ,