-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathchunk_column_stats.c
More file actions
1621 lines (1388 loc) · 45.2 KB
/
Copy pathchunk_column_stats.c
File metadata and controls
1621 lines (1388 loc) · 45.2 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 Apache License 2.0.
* Please see the included NOTICE for copyright information and
* LICENSE-APACHE for a copy of the license.
*/
#include <postgres.h>
#include <access/attnum.h>
#include <access/htup.h>
#include <access/htup_details.h>
#include <access/skey.h>
#include <access/stratnum.h>
#include <access/tupdesc.h>
#include <catalog/pg_collation.h>
#include <executor/spi.h>
#include <executor/tuptable.h>
#include <funcapi.h>
#include <nodes/makefuncs.h>
#include <optimizer/optimizer.h>
#include <parser/parse_coerce.h>
#include <parser/parse_collate.h>
#include <parser/parse_expr.h>
#include <parser/parse_relation.h>
#include <rewrite/rewriteManip.h>
#include <storage/lmgr.h>
#include <storage/lockdefs.h>
#include <utils/datum.h>
#include <utils/syscache.h>
#include "chunk.h"
#include "dimension_slice.h"
#include "guc.h"
#include "hypertable_cache.h"
#include "ts_catalog/catalog.h"
#include "chunk_column_stats.h"
/*
* Enable chunk column stats attributes
*/
enum Anum_enable_chunk_column_stats
{
Anum_enable_chunk_column_stats_id = 1,
Anum_enable_chunk_column_stats_enabled,
_Anum_enable_chunk_column_stats_max,
};
#define Natts_enable_chunk_column_stats (_Anum_enable_chunk_column_stats_max - 1)
TS_FUNCTION_INFO_V1(ts_chunk_column_stats_enable);
/*
* Disable chunk column stats attributes
*/
enum Anum_disable_chunk_column_stats
{
Anum_disable_chunk_column_stats_hypertable_id = 1,
Anum_disable_chunk_column_stats_column_name,
Anum_disable_chunk_column_stats_disabled,
_Anum_disable_chunk_column_stats_max,
};
#define Natts_disable_chunk_column_stats (_Anum_disable_chunk_column_stats_max - 1)
TS_FUNCTION_INFO_V1(ts_chunk_column_stats_disable);
/*
* Create a datum to be returned by ts_chunk_column_stats_enable DDL function
*/
static Datum
chunk_column_stats_enable_datum(FunctionCallInfo fcinfo, int32 id, bool enabled)
{
TupleDesc tupdesc;
HeapTuple tuple;
Datum values[Natts_enable_chunk_column_stats];
bool nulls[Natts_enable_chunk_column_stats] = { false };
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in "
"context that cannot accept type record")));
}
tupdesc = BlessTupleDesc(tupdesc);
Assert(tupdesc->natts == Natts_enable_chunk_column_stats);
values[AttrNumberGetAttrOffset(Anum_enable_chunk_column_stats_id)] = Int32GetDatum(id);
values[AttrNumberGetAttrOffset(Anum_enable_chunk_column_stats_enabled)] = BoolGetDatum(enabled);
tuple = heap_form_tuple(tupdesc, values, nulls);
return HeapTupleGetDatum(tuple);
}
/*
* Create a datum to be returned by ts_chunk_column_stats_disable DDL function
*/
static Datum
chunk_column_stats_disable_datum(FunctionCallInfo fcinfo, int32 hypertable_id, Name colname,
bool disabled)
{
TupleDesc tupdesc;
HeapTuple tuple;
Datum values[Natts_disable_chunk_column_stats];
bool nulls[Natts_disable_chunk_column_stats] = { false };
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in "
"context that cannot accept type record")));
}
tupdesc = BlessTupleDesc(tupdesc);
Assert(tupdesc->natts == Natts_disable_chunk_column_stats);
values[AttrNumberGetAttrOffset(Anum_disable_chunk_column_stats_hypertable_id)] =
Int32GetDatum(hypertable_id);
values[AttrNumberGetAttrOffset(Anum_disable_chunk_column_stats_column_name)] =
NameGetDatum(colname);
values[AttrNumberGetAttrOffset(Anum_disable_chunk_column_stats_disabled)] =
BoolGetDatum(disabled);
tuple = heap_form_tuple(tupdesc, values, nulls);
return HeapTupleGetDatum(tuple);
}
static int32
chunk_column_stats_insert_relation(const Relation rel, Form_chunk_column_stats info)
{
TupleDesc desc = RelationGetDescr(rel);
Datum values[Natts_chunk_column_stats] = { 0 };
bool nulls[Natts_chunk_column_stats] = { false };
CatalogSecurityContext sec_ctx;
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
info->id = ts_catalog_table_next_seq_id(ts_catalog_get(), CHUNK_COLUMN_STATS);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_id)] = Int32GetDatum(info->id);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_hypertable_id)] =
Int32GetDatum(info->hypertable_id);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_chunk_id)] =
Int32GetDatum(info->chunk_id);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_column_name)] =
NameGetDatum(&info->column_name);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_start)] =
Int64GetDatum(info->range_start);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_end)] =
Int64GetDatum(info->range_end);
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_valid)] = BoolGetDatum(info->valid);
if (info->chunk_id == INVALID_CHUNK_ID)
{
nulls[AttrNumberGetAttrOffset(Anum_chunk_column_stats_chunk_id)] = true;
}
ts_catalog_insert_values(rel, desc, values, nulls);
ts_catalog_restore_user(&sec_ctx);
return info->id;
}
static int32
chunk_column_stats_insert(Form_chunk_column_stats info)
{
Catalog *catalog = ts_catalog_get();
Relation rel;
int32 ccol_stats_id;
rel = table_open(catalog_get_table_id(catalog, CHUNK_COLUMN_STATS), RowExclusiveLock);
ccol_stats_id = chunk_column_stats_insert_relation(rel, info);
table_close(rel, RowExclusiveLock);
return ccol_stats_id;
}
static ScanTupleResult
chunk_column_stats_tuple_update(TupleInfo *ti, void *data)
{
bool should_free;
HeapTuple tuple = ts_scanner_fetch_heap_tuple(ti, false, &should_free);
FormData_chunk_column_stats *fd = (FormData_chunk_column_stats *) data;
Datum values[Natts_chunk_column_stats] = { 0 };
bool isnull[Natts_chunk_column_stats] = { 0 };
bool doReplace[Natts_chunk_column_stats] = { 0 };
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_start)] =
Int64GetDatum(fd->range_start);
doReplace[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_start)] = true;
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_end)] =
Int64GetDatum(fd->range_end);
doReplace[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_end)] = true;
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_valid)] = BoolGetDatum(fd->valid);
doReplace[AttrNumberGetAttrOffset(Anum_chunk_column_stats_valid)] = true;
HeapTuple new_tuple =
heap_modify_tuple(tuple, ts_scanner_get_tupledesc(ti), values, isnull, doReplace);
ts_catalog_update(ti->scanrel, new_tuple);
heap_freetuple(new_tuple);
if (should_free)
{
heap_freetuple(tuple);
}
return SCAN_DONE;
}
static int
chunk_column_stats_scan_internal(ScanKeyData *scankey, int nkeys, tuple_found_func tuple_found,
void *data, int limit, int dimension_index, LOCKMODE lockmode,
MemoryContext mctx)
{
Catalog *catalog = ts_catalog_get();
ScannerCtx scanctx = {
.table = catalog_get_table_id(catalog, CHUNK_COLUMN_STATS),
.index = catalog_get_index(catalog, CHUNK_COLUMN_STATS, dimension_index),
.nkeys = nkeys,
.limit = limit,
.scankey = scankey,
.data = data,
.tuple_found = tuple_found,
.lockmode = lockmode,
.scandirection = ForwardScanDirection,
.result_mctx = mctx,
};
return ts_scanner_scan(&scanctx);
}
int
ts_chunk_column_stats_update_by_id(int32 chunk_column_stats_id,
FormData_chunk_column_stats *fd_range)
{
ScanKeyData scankey[1];
ScanKeyInit(&scankey[0],
Anum_chunk_column_stats_id_idx_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(chunk_column_stats_id));
return chunk_column_stats_scan_internal(scankey,
1,
chunk_column_stats_tuple_update,
fd_range,
1,
CHUNK_COLUMN_STATS_ID_IDX,
RowExclusiveLock,
CurrentMemoryContext);
}
static void
ts_chunk_column_stats_validate(Form_chunk_column_stats info, const Oid hypertable_relid)
{
HeapTuple tuple;
Datum datum;
bool isnull;
Oid column_type;
/* Check that the column exists and has not been dropped */
tuple = SearchSysCacheAttName(hypertable_relid, NameStr(info->column_name));
if (!HeapTupleIsValid(tuple))
{
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_COLUMN),
errmsg("column \"%s\" does not exist", NameStr(info->column_name))));
}
datum = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_atttypid, &isnull);
Assert(!isnull);
column_type = DatumGetObjectId(datum);
ReleaseSysCache(tuple);
/* we only support a subset of data types for range calculations right now */
switch (column_type)
{
case INT2OID:
case INT4OID:
case INT8OID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
case DATEOID:
break;
default:
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("data type \"%s\" unsupported for range calculation",
format_type_be(column_type)),
errhint("Integer-like, timestamp-like data types supported currently")));
}
}
/*
* Track min/max range for a given column in a hypertable
*/
static Datum
ts_chunk_column_stats_add_internal(FunctionCallInfo fcinfo, Oid table_relid, Name colname,
bool if_not_exists)
{
Hypertable *ht;
Cache *hcache;
Datum retval = 0;
int32 ccol_stats_id = 0;
FormData_chunk_column_stats fd = { 0 };
Form_chunk_column_stats form;
bool enabled = true;
ts_hypertable_permissions_check(table_relid, GetUserId());
namestrcpy(&fd.column_name, NameStr(*colname));
LockRelationOid(table_relid, AccessShareLock);
ts_chunk_column_stats_validate(&fd, table_relid);
ht = ts_hypertable_cache_get_cache_and_entry(table_relid, CACHE_FLAG_NONE, &hcache);
/*
* Add an entry in the _timescaledb_catalog.chunk_column_stats table. We add
* a special entry in the catalog which contains the hypertable_id, the colname,
* an invalid id (for the chunk) and PG_INT64_MAX, PG_INT64_MIN as range values
* to indicate that ranges should be calculated for this column for chunks.
*
* We have a uniqueness check on ht_id, colname, chunk_id
*
* Check if the entry already exists, first.
*/
form = ts_chunk_column_stats_lookup(ht->fd.id, INVALID_CHUNK_ID, NameStr(*colname));
if (form != NULL)
{
if (!if_not_exists)
{
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("already enabled for column \"%s\"", NameStr(*colname))));
}
else
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("already enabled for column \"%s\", skipping", NameStr(*colname))));
/* return the existing id */
ccol_stats_id = form->id;
/* we still return true since it's already enabled */
enabled = true;
goto do_return;
}
}
fd.hypertable_id = ht->fd.id;
fd.chunk_id = INVALID_CHUNK_ID;
fd.range_start = PG_INT64_MIN;
fd.range_end = PG_INT64_MAX;
fd.valid = true;
ccol_stats_id = chunk_column_stats_insert(&fd);
/* refresh the ht entry to accommodate this new chunk_column_stats entry */
if (ht->range_space)
{
pfree(ht->range_space);
}
ht->range_space = ts_chunk_column_stats_range_space_scan(ht->fd.id,
ht->main_table_relid,
ts_cache_memory_ctx(hcache));
/*
* If the hypertable has chunks, to make it compatible
* we add artificial min/max range entries which will cover -inf / inf
* range for all these existing chunks.
*
* TODO: Maybe have a future version which calculates actual ranges for
* compressed chunks in this function itself? Or have an option to this
* function which specifies if we should calculate ranges for compressed
* chunks.
*/
if (ts_hypertable_has_chunks(ht->main_table_relid, AccessShareLock))
{
ListCell *lc;
List *chunk_id_list = ts_chunk_get_chunk_ids_by_hypertable_id(ht->fd.id);
Catalog *catalog = ts_catalog_get();
Relation rel;
rel = table_open(catalog_get_table_id(catalog, CHUNK_COLUMN_STATS), RowExclusiveLock);
foreach (lc, chunk_id_list)
{
/* other fields are set appropriately in fd above. Only change chunk_id */
fd.chunk_id = lfirst_int(lc);
chunk_column_stats_insert_relation(rel, &fd);
}
table_close(rel, RowExclusiveLock);
}
do_return:
/* return the id of the main entry for this dimension range */
fd.id = ccol_stats_id;
retval = chunk_column_stats_enable_datum(fcinfo, fd.id, enabled);
ts_cache_release(&hcache);
PG_RETURN_DATUM(retval);
}
/*
* Add min/max range tracking for a column in a hypertable.
*
* Arguments:
* 0. Relation ID of table
* 1. Column name
* 2. IF NOT EXISTS option (bool)
*/
Datum
ts_chunk_column_stats_enable(PG_FUNCTION_ARGS)
{
Oid hypertable_relid;
NameData colname;
bool if_not_exists;
TS_PREVENT_FUNC_IF_READ_ONLY();
if (!ts_guc_enable_chunk_skipping)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("chunk skipping functionality disabled, "
"enable it by first setting timescaledb.enable_chunk_skipping to on")));
}
if (PG_ARGISNULL(0))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("hypertable cannot be NULL")));
}
hypertable_relid = PG_GETARG_OID(0);
if (PG_ARGISNULL(1))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("column name cannot be NULL")));
}
namestrcpy(&colname, NameStr(*PG_GETARG_NAME(1)));
if_not_exists = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2);
return ts_chunk_column_stats_add_internal(fcinfo, hypertable_relid, &colname, if_not_exists);
}
/*
* Remove min/max range tracking for a column in a hypertable.
*
* Arguments:
* 0. Relation ID of hypertable
* 1. Column name
* 2. IF NOT EXISTS option (bool)
*/
Datum
ts_chunk_column_stats_disable(PG_FUNCTION_ARGS)
{
Oid hypertable_relid;
NameData colname;
bool if_not_exists;
Hypertable *ht;
Cache *hcache;
Datum retval = 0;
int delete_count = 0;
TS_PREVENT_FUNC_IF_READ_ONLY();
if (!ts_guc_enable_chunk_skipping)
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("chunk skipping functionality disabled, "
"enable it by first setting timescaledb.enable_chunk_skipping to on")));
}
if (PG_ARGISNULL(0))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("hypertable cannot be NULL")));
}
hypertable_relid = PG_GETARG_OID(0);
if (PG_ARGISNULL(1))
{
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("column name cannot be NULL")));
}
namestrcpy(&colname, NameStr(*PG_GETARG_NAME(1)));
if_not_exists = PG_ARGISNULL(2) ? false : PG_GETARG_BOOL(2);
ts_hypertable_permissions_check(hypertable_relid, GetUserId());
LockRelationOid(hypertable_relid, ShareUpdateExclusiveLock);
ht = ts_hypertable_cache_get_cache_and_entry(hypertable_relid, CACHE_FLAG_NONE, &hcache);
/*
* Remove entries from _timescaledb_catalog.chunk_column_stats table.
*
* There's a special entry in the catalog which contains the hypertable_id, the colname,
* an invalid id (for the chunk) and PG_INT64_MAX, PG_INT64_MIN as range values
* to indicate that ranges should be calculated for this column for chunks.
*
* Check if the entry already exists, first.
*/
if (ts_chunk_column_stats_lookup(ht->fd.id, INVALID_CHUNK_ID, NameStr(colname)) == NULL)
{
if (!if_not_exists)
{
ereport(ERROR,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("statistics not enabled for column \"%s\"", NameStr(colname))));
}
else
{
ereport(NOTICE,
(errcode(ERRCODE_DUPLICATE_OBJECT),
errmsg("statistics not enabled for column \"%s\", skipping",
NameStr(colname))));
goto do_return;
}
}
/* Delete all entries matching this hypertable_id and column_name. */
delete_count = ts_chunk_column_stats_delete_by_ht_colname(ht->fd.id, NameStr(colname));
/* refresh the ht entry to accommodate this deleted chunk_column_stats entry */
if (ht->range_space)
{
pfree(ht->range_space);
}
ht->range_space = ts_chunk_column_stats_range_space_scan(ht->fd.id,
ht->main_table_relid,
ts_cache_memory_ctx(hcache));
do_return:
retval = chunk_column_stats_disable_datum(fcinfo, ht->fd.id, &colname, delete_count > 0);
ts_cache_release(&hcache);
PG_RETURN_DATUM(retval);
}
/*
* Dimension range entries are similar to OPEN DIMENSION entries. So, most of
* the default fields are similar to them.
*/
Dimension *
ts_chunk_column_stats_fill_dummy_dimension(FormData_chunk_column_stats *r, Oid main_table_relid)
{
Dimension *d = palloc0(sizeof(Dimension));
d->fd.id = r->id;
d->fd.hypertable_id = r->hypertable_id;
d->fd.aligned = true;
namestrcpy(&d->fd.column_name, NameStr(r->column_name));
d->fd.interval_length = 1; /* a dummy interval length for the dummy dimension */
/* similar to open dimensions except that we don't participate in partitioning */
d->type = DIMENSION_TYPE_STATS;
d->column_attno = get_attnum(main_table_relid, NameStr(d->fd.column_name));
d->main_table_relid = main_table_relid;
/* rest of the fields are zeroed out */
return d;
}
/*
* Create a CHECK constraint for a min/max range chunk_column_stats entry
*/
static Constraint *
create_col_stats_check_constraint(const Form_chunk_column_stats info, Oid main_table_relid,
const char *name)
{
Constraint *constr = NULL;
Node *rangedef;
ColumnRef *colref;
List *compexprs = NIL;
Oid col_type;
if (info->range_start == PG_INT64_MIN && info->range_end == PG_INT64_MAX)
{
return NULL;
}
colref = makeNode(ColumnRef);
colref->fields = list_make1(makeString(pstrdup(NameStr(info->column_name))));
colref->location = -1;
/*
* Get the column type for later converting the internal format
* to string.
*/
const int ht_attno = get_attnum(main_table_relid, NameStr(info->column_name));
col_type = get_atttype(main_table_relid, ht_attno);
rangedef = (Node *) colref;
/* Elide range constraint for +INF or -INF */
if (info->range_start != PG_INT64_MIN)
{
A_Const *start_const = makeNode(A_Const);
memcpy(&start_const->val,
makeString(ts_internal_to_time_string(info->range_start, col_type)),
sizeof(start_const->val));
start_const->location = -1;
A_Expr *ge_expr = makeSimpleA_Expr(AEXPR_OP, ">=", rangedef, (Node *) start_const, -1);
compexprs = lappend(compexprs, ge_expr);
}
if (info->range_end != PG_INT64_MAX)
{
A_Const *end_const = makeNode(A_Const);
memcpy(&end_const->val,
makeString(ts_internal_to_time_string(info->range_end, col_type)),
sizeof(end_const->val));
end_const->location = -1;
A_Expr *lt_expr = makeSimpleA_Expr(AEXPR_OP, "<", rangedef, (Node *) end_const, -1);
compexprs = lappend(compexprs, lt_expr);
}
constr = makeNode(Constraint);
constr->contype = CONSTR_CHECK;
constr->conname = name ? pstrdup(name) : NULL;
constr->deferrable = false;
constr->skip_validation = true;
constr->initially_valid = true;
Assert(list_length(compexprs) >= 1);
if (list_length(compexprs) == 2)
{
constr->raw_expr = (Node *) makeBoolExpr(AND_EXPR, compexprs, -1);
}
else if (list_length(compexprs) == 1)
{
constr->raw_expr = linitial(compexprs);
}
return constr;
}
/*
* Fill in the form for chunk_column_stats.
*
* Note that it is necessary to deform the tuple since it is not possible to
* use GETSTRUCT when chunk_id can be NULL.
*/
static void
fill_form_from_slot(TupleTableSlot *slot, Form_chunk_column_stats form)
{
bool should_free;
HeapTuple tuple = ExecFetchSlotHeapTuple(slot, false, &should_free);
Datum values[_Anum_chunk_column_stats_max];
bool nulls[_Anum_chunk_column_stats_max];
heap_deform_tuple(tuple, slot->tts_tupleDescriptor, values, nulls);
form->id = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_id)]);
form->hypertable_id =
DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_hypertable_id)]);
if (nulls[AttrNumberGetAttrOffset(Anum_chunk_column_stats_chunk_id)])
{
form->chunk_id = INVALID_CHUNK_ID;
}
else
{
form->chunk_id =
DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_chunk_id)]);
}
namestrcpy(&form->column_name,
NameStr(*DatumGetName(
values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_column_name)])));
form->range_end =
DatumGetInt64(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_end)]);
form->range_start =
DatumGetInt64(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_range_start)]);
form->valid = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_chunk_column_stats_valid)]);
if (should_free)
{
heap_freetuple(tuple);
}
}
static ScanTupleResult
chunk_column_stats_tuple_found(TupleInfo *ti, void *data)
{
ChunkRangeSpace *rs = data;
Form_chunk_column_stats d = &rs->range_cols[rs->num_range_cols++];
fill_form_from_slot(ti->slot, d);
return SCAN_CONTINUE;
}
ChunkRangeSpace *
ts_chunk_column_stats_range_space_scan(int32 hypertable_id, Oid ht_reloid, MemoryContext mctx)
{
/* We won't have more entries than the number of columns in the HT */
int num_range_cols = ts_get_relnatts(ht_reloid);
ChunkRangeSpace *range_space =
MemoryContextAllocZero(mctx, CHUNKRANGESPACE_SIZE(num_range_cols));
ScanKeyData scankey[2];
range_space->hypertable_id = hypertable_id;
range_space->capacity = num_range_cols;
range_space->num_range_cols = 0;
/* Perform an index scan on hypertable_id, invalid chunk_id. */
ScanKeyInit(
&scankey[0],
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_hypertable_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(hypertable_id));
ScanKeyEntryInitialize(
&scankey[1],
SK_ISNULL | SK_SEARCHNULL,
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_chunk_id,
BTEqualStrategyNumber,
InvalidOid,
InvalidOid,
InvalidOid,
Int32GetDatum(INVALID_CHUNK_ID));
chunk_column_stats_scan_internal(scankey,
2,
chunk_column_stats_tuple_found,
range_space,
0,
CHUNK_COLUMN_STATS_HT_ID_CHUNK_ID_COLUMN_NAME_IDX,
AccessShareLock,
mctx);
if (range_space->num_range_cols == 0)
{
pfree(range_space);
return NULL;
}
return range_space;
}
static ScanTupleResult
form_range_tuple_found(TupleInfo *ti, void *data)
{
Form_chunk_column_stats rg = data;
fill_form_from_slot(ti->slot, rg);
return SCAN_DONE;
}
Form_chunk_column_stats
ts_chunk_column_stats_lookup(int32 hypertable_id, int32 chunk_id, const char *col_name)
{
ScanKeyData scankey[3];
Form_chunk_column_stats form_range = palloc0(sizeof(FormData_chunk_column_stats));
form_range->chunk_id = INVALID_CHUNK_ID; /* for clarity */
/* Perform an index scan on hypertable_id, chunk_id, col_name. */
ScanKeyInit(
&scankey[0],
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_hypertable_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(hypertable_id));
if (chunk_id == INVALID_CHUNK_ID)
{
ScanKeyEntryInitialize(
&scankey[1],
SK_ISNULL | SK_SEARCHNULL,
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_chunk_id,
BTEqualStrategyNumber,
InvalidOid,
InvalidOid,
InvalidOid,
Int32GetDatum(chunk_id));
}
else
{
ScanKeyInit(
&scankey[1],
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_chunk_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(chunk_id));
}
ScanKeyInit(
&scankey[2],
Anum_chunk_column_stats_ht_id_chunk_id_column_name_range_start_range_end_idx_column_name,
BTEqualStrategyNumber,
F_NAMEEQ,
CStringGetDatum(col_name));
chunk_column_stats_scan_internal(scankey,
3,
form_range_tuple_found,
form_range,
1,
CHUNK_COLUMN_STATS_HT_ID_CHUNK_ID_COLUMN_NAME_IDX,
AccessShareLock,
CurrentMemoryContext);
if (strlen(NameStr(form_range->column_name)) == 0)
{
pfree(form_range);
return NULL;
}
return form_range;
}
static bool
chunk_get_minmax(const Chunk *chunk, Oid col_type, const char *col_name, Datum *minmax)
{
StringInfoData command;
int res;
/* Lock down search_path */
int save_nestlevel = NewGUCNestLevel();
RestrictSearchPath();
const char *schema_name = ts_chunk_get_schema_name(chunk);
const char *table_name = ts_chunk_get_table_name(chunk);
initStringInfo(&command);
appendStringInfo(&command,
"SELECT pg_catalog.min(%s), pg_catalog.max(%s) FROM %s.%s",
quote_identifier(col_name),
quote_identifier(col_name),
quote_identifier(schema_name),
quote_identifier(table_name));
/*
* SPI_connect will switch MemoryContext so we need to keep track
* of caller context as we need to copy the values into caller
* context.
*/
MemoryContext caller = CurrentMemoryContext;
if (SPI_connect() != SPI_OK_CONNECT)
{
elog(ERROR, "could not connect to SPI");
}
res = SPI_execute(command.data, true /* read_only */, 0 /*count*/);
if (res < 0)
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
(errmsg("could not get the min/max values for column \"%s\" of chunk \"%s.%s\"",
col_name,
schema_name,
table_name))));
}
pfree(command.data);
Datum min, max;
bool isnull_min = false, isnull_max = false;
min = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull_min);
max = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull_max);
Assert(SPI_gettypeid(SPI_tuptable->tupdesc, 1) == col_type);
Assert(SPI_gettypeid(SPI_tuptable->tupdesc, 2) == col_type);
bool found = !isnull_min && !isnull_max;
if (found)
{
bool typbyval;
int16 typlen;
get_typlenbyval(col_type, &typlen, &typbyval);
/* Copy the values into caller context */
MemoryContext spi = MemoryContextSwitchTo(caller);
minmax[0] = datumCopy(min, typbyval, typlen);
minmax[1] = datumCopy(max, typbyval, typlen);
MemoryContextSwitchTo(spi);
}
/* Restore search_path */
AtEOXact_GUC(false, save_nestlevel);
res = SPI_finish();
if (res != SPI_OK_FINISH)
{
elog(ERROR, "SPI_finish failed: %s", SPI_result_code_string(res));
}
return found;
}
/*
* Update column dimension ranges in the catalog for the
* provided chunk (it's assumed that the chunk is locked
* appropriately).
*
* Calculate actual ranges for the given chunk for the columns
* insert these entries. This allows for the
* chunk to be picked up when queries use these columns in
* WHERE clauses with these ranges.
*
* Returns the number of column entries that have been added or
* updated.
*/
int
ts_chunk_column_stats_calculate(const Hypertable *ht, const Chunk *chunk)
{
Size i = 0;
ChunkRangeSpace *rs = ht->range_space;
MemoryContext work_mcxt, orig_mcxt;
/* Quick check. Bail out early if none */
if (rs == NULL)
{
return i;
}
work_mcxt =
AllocSetContextCreate(CurrentMemoryContext, "dimension-range-work", ALLOCSET_DEFAULT_SIZES);
orig_mcxt = MemoryContextSwitchTo(work_mcxt);
for (int range_index = 0; range_index < rs->num_range_cols; range_index++)
{
Datum minmax[2];
AttrNumber attno;
char *col_name = NameStr(rs->range_cols[range_index].column_name);
Oid col_type;
attno = get_attnum(ht->main_table_relid, col_name);
attno = ts_map_attno(ht->main_table_relid, chunk->fd.relid, attno);
col_type = get_atttype(chunk->fd.relid, attno);
/* calculate the min/max range for this column on this chunk */
if (chunk_get_minmax(chunk, col_type, col_name, minmax))
{
Form_chunk_column_stats range;
int64 min = ts_time_value_to_internal(minmax[0], col_type);
int64 max = ts_time_value_to_internal(minmax[1], col_type);
/* The end value is exclusive to the range, so incr by 1 */
if (max != DIMENSION_SLICE_MAXVALUE)
{
max++;
}
/*
* Check if an entry exists for this ht, chunk_id, colname combo. If it exists
* and it's not -inf/+inf then it's probably a case of re-computation of the
* ranges. In such a case, we compare the stored range_start and range_end entries
* and compare with the min/max calculated.
*
* if min < range_start, then new_range_start = min
* if max > range_end, then new_range_end = max
*
* We need to update the existing entry with changes in the range.
* Also, in case of updates, the entry might be marked "invalid" so it needs to be
* made "valid" again as well.
*/
range = ts_chunk_column_stats_lookup(ht->fd.id, chunk->fd.id, col_name);
/* Add a new entry if none exists */
if (range == NULL)
{
FormData_chunk_column_stats fd = { 0 };
fd.hypertable_id = ht->fd.id;
fd.chunk_id = chunk->fd.id;
namestrcpy(&fd.column_name, col_name);
fd.range_start = min;
fd.range_end = max;
fd.valid = true;
chunk_column_stats_insert(&fd);
i++;
}
/* update case */
else if (range->range_start != min || range->range_end != max || !range->valid)
{
range->range_start = min;
range->range_end = max;
range->valid = true;
ts_chunk_column_stats_update_by_id(range->id, range);
i++;
}
}
else
{
ereport(WARNING, errmsg("unable to calculate min/max values for column ranges"));
}
}
MemoryContextSwitchTo(orig_mcxt);
MemoryContextDelete(work_mcxt);