-
Notifications
You must be signed in to change notification settings - Fork 848
/
dimension.c
1764 lines (1474 loc) · 52.4 KB
/
dimension.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 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 <catalog/pg_type.h>
#include <catalog/namespace.h>
#include <access/relscan.h>
#include <commands/tablecmds.h>
#include <utils/lsyscache.h>
#include <utils/syscache.h>
#include <utils/builtins.h>
#include <utils/timestamp.h>
#include <funcapi.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <storage/lmgr.h>
#include "ts_catalog/catalog.h"
#include "compat/compat.h"
#include "cross_module_fn.h"
#include "dimension.h"
#include "dimension_slice.h"
#include "dimension_vector.h"
#include "hypertable.h"
#include "indexing.h"
#include "hypertable_cache.h"
#include "partitioning.h"
#include "scanner.h"
#include "time_utils.h"
#include "utils.h"
#include "errors.h"
#include "debug_point.h"
/* add_dimension record attribute numbers */
enum Anum_add_dimension
{
Anum_add_dimension_id = 1,
Anum_add_dimension_schema_name,
Anum_add_dimension_table_name,
Anum_add_dimension_column_name,
Anum_add_dimension_created,
_Anum_add_dimension_max,
};
#define Natts_add_dimension (_Anum_add_dimension_max - 1)
static int
cmp_dimension_id(const void *left, const void *right)
{
const Dimension *diml = (Dimension *) left;
const Dimension *dimr = (Dimension *) right;
if (diml->fd.id < dimr->fd.id)
return -1;
if (diml->fd.id > dimr->fd.id)
return 1;
return 0;
}
const Dimension *
ts_hyperspace_get_dimension_by_id(const Hyperspace *hs, int32 id)
{
Dimension dim = {
.fd.id = id,
};
return bsearch(&dim, hs->dimensions, hs->num_dimensions, sizeof(Dimension), cmp_dimension_id);
}
Dimension *
ts_hyperspace_get_mutable_dimension_by_name(Hyperspace *hs, DimensionType type, const char *name)
{
int i;
for (i = 0; i < hs->num_dimensions; i++)
{
Dimension *dim = &hs->dimensions[i];
if ((type == DIMENSION_TYPE_ANY || dim->type == type) &&
namestrcmp(&dim->fd.column_name, name) == 0)
return dim;
}
return NULL;
}
const Dimension *
ts_hyperspace_get_dimension_by_name(const Hyperspace *hs, DimensionType type, const char *name)
{
return ts_hyperspace_get_mutable_dimension_by_name((Hyperspace *) hs, type, name);
}
Dimension *
ts_hyperspace_get_mutable_dimension(Hyperspace *hs, DimensionType type, Index n)
{
int i;
for (i = 0; i < hs->num_dimensions; i++)
{
if (type == DIMENSION_TYPE_ANY || hs->dimensions[i].type == type)
{
if (n == 0)
return &hs->dimensions[i];
n--;
}
}
return NULL;
}
const Dimension *
ts_hyperspace_get_dimension(const Hyperspace *hs, DimensionType type, Index n)
{
return ts_hyperspace_get_mutable_dimension((Hyperspace *) hs, type, n);
}
static int
hyperspace_get_num_dimensions_by_type(Hyperspace *hs, DimensionType type)
{
int i;
int n = 0;
for (i = 0; i < hs->num_dimensions; i++)
{
if (type == DIMENSION_TYPE_ANY || hs->dimensions[i].type == type)
n++;
}
return n;
}
static inline DimensionType
dimension_type(TupleInfo *ti)
{
if (slot_attisnull(ti->slot, Anum_dimension_interval_length) &&
!slot_attisnull(ti->slot, Anum_dimension_num_slices))
return DIMENSION_TYPE_CLOSED;
if (!slot_attisnull(ti->slot, Anum_dimension_interval_length) &&
slot_attisnull(ti->slot, Anum_dimension_num_slices))
return DIMENSION_TYPE_OPEN;
elog(ERROR, "invalid partitioning dimension");
/* suppress compiler warning on MSVC */
return DIMENSION_TYPE_ANY;
}
static void
dimension_fill_in_from_tuple(Dimension *d, TupleInfo *ti, Oid main_table_relid)
{
Datum values[Natts_dimension];
bool isnull[Natts_dimension];
bool should_free;
HeapTuple tuple = ts_scanner_fetch_heap_tuple(ti, false, &should_free);
/*
* With need to use heap_deform_tuple() rather than GETSTRUCT(), since
* optional values may be omitted from the tuple.
*/
heap_deform_tuple(tuple, ts_scanner_get_tupledesc(ti), values, isnull);
d->type = dimension_type(ti);
d->fd.id = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_dimension_id)]);
d->fd.hypertable_id =
DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_dimension_hypertable_id)]);
d->fd.aligned = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_dimension_aligned)]);
d->fd.column_type =
DatumGetObjectId(values[AttrNumberGetAttrOffset(Anum_dimension_column_type)]);
memcpy(&d->fd.column_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_dimension_column_name)]),
NAMEDATALEN);
if (!isnull[Anum_dimension_partitioning_func_schema - 1] &&
!isnull[Anum_dimension_partitioning_func - 1])
{
MemoryContext old;
d->fd.num_slices =
DatumGetInt16(values[AttrNumberGetAttrOffset(Anum_dimension_num_slices)]);
memcpy(&d->fd.partitioning_func_schema,
DatumGetName(
values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func_schema)]),
NAMEDATALEN);
memcpy(&d->fd.partitioning_func,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func)]),
NAMEDATALEN);
old = MemoryContextSwitchTo(ti->mctx);
d->partitioning = ts_partitioning_info_create(NameStr(d->fd.partitioning_func_schema),
NameStr(d->fd.partitioning_func),
NameStr(d->fd.column_name),
d->type,
main_table_relid);
/* Closed "space" partitions might be explicitly partitioned if it is
* the "first" space dimension. If it is not the first, the dimension
* partitions state will be NULL */
if (IS_CLOSED_DIMENSION(d))
d->dimension_partitions = ts_dimension_partition_info_get(d->fd.id);
else
d->dimension_partitions = NULL;
MemoryContextSwitchTo(old);
}
if (!isnull[Anum_dimension_integer_now_func_schema - 1] &&
!isnull[Anum_dimension_integer_now_func - 1])
{
namestrcpy(&d->fd.integer_now_func_schema,
DatumGetCString(
values[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func_schema)]));
namestrcpy(&d->fd.integer_now_func,
DatumGetCString(
values[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func)]));
}
if (IS_CLOSED_DIMENSION(d))
d->fd.num_slices = DatumGetInt16(values[Anum_dimension_num_slices - 1]);
else
d->fd.interval_length =
DatumGetInt64(values[AttrNumberGetAttrOffset(Anum_dimension_interval_length)]);
d->column_attno = get_attnum(main_table_relid, NameStr(d->fd.column_name));
d->main_table_relid = main_table_relid;
if (should_free)
heap_freetuple(tuple);
}
static Datum
create_range_datum(FunctionCallInfo fcinfo, DimensionSlice *slice)
{
TupleDesc tupdesc;
Datum values[2];
bool nulls[2] = { false };
HeapTuple tuple;
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
elog(ERROR, "function returning record called in context that cannot accept type record");
tupdesc = BlessTupleDesc(tupdesc);
values[0] = Int64GetDatum(slice->fd.range_start);
values[1] = Int64GetDatum(slice->fd.range_end);
tuple = heap_form_tuple(tupdesc, values, nulls);
return HeapTupleGetDatum(tuple);
}
static DimensionSlice *
calculate_open_range_default(const Dimension *dim, int64 value)
{
int64 range_start, range_end;
Oid dimtype = ts_dimension_get_partition_type(dim);
if (value < 0)
{
const int64 dim_min = ts_time_get_min(dimtype);
range_end = ((value + 1) / dim->fd.interval_length) * dim->fd.interval_length;
/* prevent integer underflow */
if (dim_min - range_end > -dim->fd.interval_length)
range_start = DIMENSION_SLICE_MINVALUE;
else
range_start = range_end - dim->fd.interval_length;
}
else
{
const int64 dim_end = ts_time_get_max(dimtype);
range_start = (value / dim->fd.interval_length) * dim->fd.interval_length;
/* prevent integer overflow */
if (dim_end - range_start < dim->fd.interval_length)
range_end = DIMENSION_SLICE_MAXVALUE;
else
range_end = range_start + dim->fd.interval_length;
}
return ts_dimension_slice_create(dim->fd.id, range_start, range_end);
}
TS_FUNCTION_INFO_V1(ts_dimension_calculate_open_range_default);
/*
* Expose open dimension range calculation for testing purposes.
*/
Datum
ts_dimension_calculate_open_range_default(PG_FUNCTION_ARGS)
{
int64 value = PG_GETARG_INT64(0);
Dimension dim = {
.type = DIMENSION_TYPE_OPEN,
.fd.id = 0,
.fd.interval_length = PG_GETARG_INT64(1),
.fd.column_type = TypenameGetTypid(PG_GETARG_CSTRING(2)),
};
DimensionSlice *slice = calculate_open_range_default(&dim, value);
PG_RETURN_DATUM(create_range_datum(fcinfo, slice));
}
static int64
calculate_closed_range_interval(const Dimension *dim)
{
Assert(NULL != dim && IS_CLOSED_DIMENSION(dim));
return DIMENSION_SLICE_CLOSED_MAX / ((int64) dim->fd.num_slices);
}
static DimensionSlice *
calculate_closed_range_default(const Dimension *dim, int64 value)
{
int64 range_start, range_end;
/* The interval that divides the dimension into N equal sized slices */
int64 interval = calculate_closed_range_interval(dim);
int64 last_start = interval * (dim->fd.num_slices - 1);
if (value < 0)
elog(ERROR, "invalid value " INT64_FORMAT " for closed dimension", value);
if (value >= last_start)
{
/* put overflow from integer-division errors in last range */
range_start = last_start;
range_end = DIMENSION_SLICE_MAXVALUE;
}
else
{
range_start = (value / interval) * interval;
range_end = range_start + interval;
}
if (0 == range_start)
{
range_start = DIMENSION_SLICE_MINVALUE;
}
return ts_dimension_slice_create(dim->fd.id, range_start, range_end);
}
TS_FUNCTION_INFO_V1(ts_dimension_calculate_closed_range_default);
/*
* Exposed closed dimension range calculation for testing purposes.
*/
Datum
ts_dimension_calculate_closed_range_default(PG_FUNCTION_ARGS)
{
int64 value = PG_GETARG_INT64(0);
Dimension dim = {
.type = DIMENSION_TYPE_CLOSED,
.fd.id = 0,
.fd.num_slices = PG_GETARG_INT16(1),
};
DimensionSlice *slice = calculate_closed_range_default(&dim, value);
PG_RETURN_DATUM(create_range_datum(fcinfo, slice));
}
DimensionSlice *
ts_dimension_calculate_default_slice(const Dimension *dim, int64 value)
{
if (IS_OPEN_DIMENSION(dim))
return calculate_open_range_default(dim, value);
return calculate_closed_range_default(dim, value);
}
/*
* Get the ordinal value of a slice in an open dimension.
*
* Note that, for an open dimension, we can only deal with already created
* slices and cannot account for, e.g., gaps in the dimension where future
* slices might be created and thus changing the ordinal value for a slice.
*
* For instance, the ordinal value of slice D below is 2 (zero indexed):
*
* ' | A | B | <gap> | D | E |
*
* but when slice C is later created the ordinal value of D will be 3:
*
* ' | A | B | C | D | E |
*/
static int
ts_dimension_get_open_slice_ordinal(const Dimension *dim, const DimensionSlice *slice)
{
DimensionVec *vec;
int i;
Assert(NULL != dim && IS_OPEN_DIMENSION(dim));
Assert(NULL != slice);
vec = ts_dimension_get_slices(dim);
Assert(NULL != vec);
/* Find the index (ordinal) of the chunk's slice in the open dimension */
i = ts_dimension_vec_find_slice_index(vec, slice->fd.id);
if (i >= 0)
return i;
else
{
/*
* Returns the number of slices if the slice not found, i.e., i = -1.
* Dimension slice might not exist if a chunk table is created without
* modifying metadata. It happens only during copy/move chunk for distributed
* hypertable, thus this code, which is used when no space dimension exists,
* is unlikely to be used.
*/
return vec->num_slices;
}
}
/*
* Get the ordinal value of a slice in a closed dimension.
*
* For closed dimensions, we calculate the ordinal value of a slice based on
* the assumption that the dimension is fully partitioned in equal size slices
* as given by the current partitioning configuration. In reality, though,
* slices are created lazily so a closed dimension might have less slices in
* time interval than the configuration suggests. Further, during time
* intervals where repartitioning happens, there might be an unexpected number
* of slices due to a mix of slices from both the old and the new partitioning
* configuration. As a result, the ordinal value of a given slice might not
* actually match the partitioning settings at a given point in time. In this case, we will return
* the ordinal of current slice most overlapping the given slice (or first fully overlapped slice).
*/
static int
ts_dimension_get_closed_slice_ordinal(const Dimension *dim, const DimensionSlice *target_slice)
{
int64 current_slice_size;
int64 target_slice_size;
int candidate_slice_ordinal;
int64 target_overlap_with_candidate_slice;
Assert(NULL != dim && IS_CLOSED_DIMENSION(dim));
Assert(NULL != target_slice);
Assert(dim->fd.num_slices > 0);
/* Slicing assumes partitioning functions use the range [0, INT32_MAX], though the first slice
* uses INT64_MIN as its lower bound, and the last slice uses INT64_MAX as its upper bound. */
if (target_slice->fd.range_start == DIMENSION_SLICE_MINVALUE)
return 0;
if (target_slice->fd.range_end == DIMENSION_SLICE_MAXVALUE)
return dim->fd.num_slices - 1;
Assert(target_slice->fd.range_start > 0);
Assert(target_slice->fd.range_end < DIMENSION_SLICE_CLOSED_MAX);
/* Given a target slice starting from some point p, determine a candidate slice in the current
* partitioning configuration that contains p. If that slice contains over half of our target
* slice, return it's ordinal. Otherwise return the ordinal for the next slice. */
current_slice_size = calculate_closed_range_interval(dim);
target_slice_size = target_slice->fd.range_end - target_slice->fd.range_start;
candidate_slice_ordinal = target_slice->fd.range_start / current_slice_size;
target_overlap_with_candidate_slice =
current_slice_size - (target_slice->fd.range_start % current_slice_size);
/* Note that if the candidate slice wholly contains the target slice,
* target_overlap_with_candidate_slice will actually be greater than target_slice_size. This
* doesn't affect the correctness of the following check. */
if (target_overlap_with_candidate_slice >= target_slice_size / 2)
return candidate_slice_ordinal;
else
return candidate_slice_ordinal + 1;
}
/*
* Get the ordinal value of a slice in a dimension.
*
* This function returns the ordinal value of a slice (starting at 0) in the
* dimension it belongs to. In other words, the "earliest" slice along the
* dimensional axis gets the lowest ordinal value and the "latest" the largest.
*/
int
ts_dimension_get_slice_ordinal(const Dimension *dim, const DimensionSlice *slice)
{
Assert(NULL != dim);
Assert(NULL != slice);
Assert(dim->fd.id == slice->fd.dimension_id);
switch (dim->type)
{
case DIMENSION_TYPE_OPEN:
return ts_dimension_get_open_slice_ordinal(dim, slice);
case DIMENSION_TYPE_CLOSED:
return ts_dimension_get_closed_slice_ordinal(dim, slice);
default:
Assert(false);
break;
}
pg_unreachable();
return -1;
}
static Hyperspace *
hyperspace_create(int32 hypertable_id, Oid main_table_relid, uint16 num_dimensions,
MemoryContext mctx)
{
Hyperspace *hs = MemoryContextAllocZero(mctx, HYPERSPACE_SIZE(num_dimensions));
hs->hypertable_id = hypertable_id;
hs->main_table_relid = main_table_relid;
hs->capacity = num_dimensions;
hs->num_dimensions = 0;
return hs;
}
static ScanTupleResult
dimension_tuple_found(TupleInfo *ti, void *data)
{
Hyperspace *hs = data;
Dimension *d = &hs->dimensions[hs->num_dimensions++];
dimension_fill_in_from_tuple(d, ti, hs->main_table_relid);
return SCAN_CONTINUE;
}
static int
dimension_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, DIMENSION),
.index = catalog_get_index(catalog, DIMENSION, 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);
}
Hyperspace *
ts_dimension_scan(int32 hypertable_id, Oid main_table_relid, int16 num_dimensions,
MemoryContext mctx)
{
Hyperspace *space = hyperspace_create(hypertable_id, main_table_relid, num_dimensions, mctx);
ScanKeyData scankey[1];
/* Perform an index scan on hypertable_id. */
ScanKeyInit(&scankey[0],
Anum_dimension_hypertable_id_column_name_idx_hypertable_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(hypertable_id));
dimension_scan_internal(scankey,
1,
dimension_tuple_found,
space,
num_dimensions,
DIMENSION_HYPERTABLE_ID_COLUMN_NAME_IDX,
AccessShareLock,
mctx);
/* Sort dimensions in ascending order to allow binary search lookups */
qsort(space->dimensions, space->num_dimensions, sizeof(Dimension), cmp_dimension_id);
return space;
}
static ScanTupleResult
dimension_find_hypertable_id_tuple_found(TupleInfo *ti, void *data)
{
int32 *hypertable_id = data;
bool isnull = false;
Datum datum = slot_getattr(ti->slot, Anum_dimension_hypertable_id, &isnull);
Assert(!isnull);
*hypertable_id = DatumGetInt32(datum);
return SCAN_DONE;
}
int32
ts_dimension_get_hypertable_id(int32 dimension_id)
{
int32 hypertable_id;
ScanKeyData scankey[1];
int ret;
/* Perform an index scan dimension_id. */
ScanKeyInit(&scankey[0],
Anum_dimension_id_idx_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(dimension_id));
ret = dimension_scan_internal(scankey,
1,
dimension_find_hypertable_id_tuple_found,
&hypertable_id,
1,
DIMENSION_ID_IDX,
AccessShareLock,
CurrentMemoryContext);
if (ret == 1)
return hypertable_id;
return -1;
}
DimensionVec *
ts_dimension_get_slices(const Dimension *dim)
{
return ts_dimension_slice_scan_by_dimension(dim->fd.id, 0);
}
static int
dimension_scan_update(int32 dimension_id, tuple_found_func tuple_found, void *data,
LOCKMODE lockmode)
{
Catalog *catalog = ts_catalog_get();
ScanKeyData scankey[1];
ScannerCtx scanctx = {
.table = catalog_get_table_id(catalog, DIMENSION),
.index = catalog_get_index(catalog, DIMENSION, DIMENSION_ID_IDX),
.nkeys = 1,
.limit = 1,
.scankey = scankey,
.data = data,
.tuple_found = tuple_found,
.lockmode = lockmode,
.scandirection = ForwardScanDirection,
};
ScanKeyInit(&scankey[0],
Anum_dimension_id_idx_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(dimension_id));
return ts_scanner_scan(&scanctx);
}
static ScanTupleResult
dimension_tuple_delete(TupleInfo *ti, void *data)
{
CatalogSecurityContext sec_ctx;
bool isnull;
Datum dimension_id = slot_getattr(ti->slot, Anum_dimension_id, &isnull);
bool *delete_slices = data;
Assert(!isnull);
/* delete dimension slices */
if (NULL != delete_slices && *delete_slices)
ts_dimension_slice_delete_by_dimension_id(DatumGetInt32(dimension_id), false);
/* delete all dimension partitions */
ts_dimension_partition_info_delete(DatumGetInt32(dimension_id));
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
ts_catalog_delete_tid(ti->scanrel, ts_scanner_get_tuple_tid(ti));
ts_catalog_restore_user(&sec_ctx);
return SCAN_CONTINUE;
}
int
ts_dimension_delete_by_hypertable_id(int32 hypertable_id, bool delete_slices)
{
ScanKeyData scankey[1];
/* Perform an index scan to delete based on hypertable_id */
ScanKeyInit(&scankey[0],
Anum_dimension_hypertable_id_column_name_idx_hypertable_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(hypertable_id));
return dimension_scan_internal(scankey,
1,
dimension_tuple_delete,
&delete_slices,
0,
DIMENSION_HYPERTABLE_ID_COLUMN_NAME_IDX,
RowExclusiveLock,
CurrentMemoryContext);
}
static ScanTupleResult
dimension_tuple_update(TupleInfo *ti, void *data)
{
Dimension *dim = data;
Datum values[Natts_dimension];
bool nulls[Natts_dimension];
CatalogSecurityContext sec_ctx;
bool should_free;
HeapTuple tuple = ts_scanner_fetch_heap_tuple(ti, false, &should_free);
HeapTuple new_tuple;
heap_deform_tuple(tuple, ts_scanner_get_tupledesc(ti), values, nulls);
Assert((dim->fd.num_slices <= 0 && dim->fd.interval_length > 0) ||
(dim->fd.num_slices > 0 && dim->fd.interval_length <= 0));
values[AttrNumberGetAttrOffset(Anum_dimension_column_name)] =
NameGetDatum(&dim->fd.column_name);
values[AttrNumberGetAttrOffset(Anum_dimension_column_type)] =
ObjectIdGetDatum(dim->fd.column_type);
values[AttrNumberGetAttrOffset(Anum_dimension_num_slices)] = Int16GetDatum(dim->fd.num_slices);
if (!nulls[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func)] &&
!nulls[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func_schema)])
{
values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func)] =
NameGetDatum(&dim->fd.partitioning_func);
values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func_schema)] =
NameGetDatum(&dim->fd.partitioning_func_schema);
}
if (*NameStr(dim->fd.integer_now_func) != '\0' &&
*NameStr(dim->fd.integer_now_func_schema) != '\0')
{
values[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func)] =
NameGetDatum(&dim->fd.integer_now_func);
values[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func_schema)] =
NameGetDatum(&dim->fd.integer_now_func_schema);
nulls[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func)] = false;
nulls[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func_schema)] = false;
}
if (!nulls[AttrNumberGetAttrOffset(Anum_dimension_interval_length)])
values[AttrNumberGetAttrOffset(Anum_dimension_interval_length)] =
Int64GetDatum(dim->fd.interval_length);
new_tuple = heap_form_tuple(ts_scanner_get_tupledesc(ti), values, nulls);
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
ts_catalog_update_tid(ti->scanrel, ts_scanner_get_tuple_tid(ti), new_tuple);
ts_catalog_restore_user(&sec_ctx);
heap_freetuple(new_tuple);
if (should_free)
heap_freetuple(tuple);
return SCAN_DONE;
}
static int32
dimension_insert_relation(Relation rel, int32 hypertable_id, Name colname, Oid coltype,
int16 num_slices, regproc partitioning_func, int64 interval_length)
{
TupleDesc desc = RelationGetDescr(rel);
Datum values[Natts_dimension];
bool nulls[Natts_dimension] = { false };
CatalogSecurityContext sec_ctx;
int32 dimension_id;
values[AttrNumberGetAttrOffset(Anum_dimension_hypertable_id)] = Int32GetDatum(hypertable_id);
values[AttrNumberGetAttrOffset(Anum_dimension_column_name)] = NameGetDatum(colname);
values[AttrNumberGetAttrOffset(Anum_dimension_column_type)] = ObjectIdGetDatum(coltype);
if (OidIsValid(partitioning_func))
{
Oid pronamespace = get_func_namespace(partitioning_func);
values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func)] =
DirectFunctionCall1(namein, CStringGetDatum(get_func_name(partitioning_func)));
values[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func_schema)] =
DirectFunctionCall1(namein, CStringGetDatum(get_namespace_name(pronamespace)));
}
else
{
nulls[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func)] = true;
nulls[AttrNumberGetAttrOffset(Anum_dimension_partitioning_func_schema)] = true;
}
if (num_slices > 0)
{
/* Closed (hash) dimension */
Assert(num_slices > 0 && interval_length <= 0);
values[AttrNumberGetAttrOffset(Anum_dimension_num_slices)] = Int16GetDatum(num_slices);
values[AttrNumberGetAttrOffset(Anum_dimension_aligned)] = BoolGetDatum(false);
nulls[AttrNumberGetAttrOffset(Anum_dimension_interval_length)] = true;
}
else
{
/* Open (time) dimension */
Assert(num_slices <= 0 && interval_length > 0);
values[AttrNumberGetAttrOffset(Anum_dimension_interval_length)] =
Int64GetDatum(interval_length);
values[AttrNumberGetAttrOffset(Anum_dimension_aligned)] = BoolGetDatum(true);
nulls[AttrNumberGetAttrOffset(Anum_dimension_num_slices)] = true;
}
/* no integer_now function by default */
nulls[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func_schema)] = true;
nulls[AttrNumberGetAttrOffset(Anum_dimension_integer_now_func)] = true;
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
dimension_id = Int32GetDatum(ts_catalog_table_next_seq_id(ts_catalog_get(), DIMENSION));
values[AttrNumberGetAttrOffset(Anum_dimension_id)] = dimension_id;
ts_catalog_insert_values(rel, desc, values, nulls);
ts_catalog_restore_user(&sec_ctx);
return dimension_id;
}
static int32
dimension_insert(int32 hypertable_id, Name colname, Oid coltype, int16 num_slices,
regproc partitioning_func, int64 interval_length)
{
Catalog *catalog = ts_catalog_get();
Relation rel;
int32 dimension_id;
rel = table_open(catalog_get_table_id(catalog, DIMENSION), RowExclusiveLock);
dimension_id = dimension_insert_relation(rel,
hypertable_id,
colname,
coltype,
num_slices,
partitioning_func,
interval_length);
table_close(rel, RowExclusiveLock);
return dimension_id;
}
int
ts_dimension_set_type(Dimension *dim, Oid newtype)
{
if (!IS_VALID_OPEN_DIM_TYPE(newtype))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
errmsg("cannot change data type of hypertable column \"%s\" from %s to %s",
NameStr(dim->fd.column_name),
format_type_be(dim->fd.column_type),
format_type_be(newtype)),
errhint("Use an integer, timestamp, or date type.")));
dim->fd.column_type = newtype;
return dimension_scan_update(dim->fd.id, dimension_tuple_update, dim, RowExclusiveLock);
}
TSDLLEXPORT Oid
ts_dimension_get_partition_type(const Dimension *dim)
{
Assert(dim != NULL);
return dim->partitioning != NULL ? dim->partitioning->partfunc.rettype : dim->fd.column_type;
}
int
ts_dimension_set_name(Dimension *dim, const char *newname)
{
namestrcpy(&dim->fd.column_name, newname);
return dimension_scan_update(dim->fd.id, dimension_tuple_update, dim, RowExclusiveLock);
}
int
ts_dimension_set_chunk_interval(Dimension *dim, int64 chunk_interval)
{
Assert(IS_OPEN_DIMENSION(dim));
dim->fd.interval_length = chunk_interval;
return dimension_scan_update(dim->fd.id, dimension_tuple_update, dim, RowExclusiveLock);
}
int
ts_dimension_set_number_of_slices(Dimension *dim, int16 num_slices)
{
Assert(IS_CLOSED_DIMENSION(dim));
dim->fd.num_slices = num_slices;
return dimension_scan_update(dim->fd.id, dimension_tuple_update, dim, RowExclusiveLock);
}
/*
* Apply any dimension-specific transformations on a value, i.e., apply
* partitioning function. Optionally get the type of the resulting value via
* the restype parameter.
*/
Datum
ts_dimension_transform_value(const Dimension *dim, Oid collation, Datum value, Oid const_datum_type,
Oid *restype)
{
if (NULL != dim->partitioning)
value = ts_partitioning_func_apply(dim->partitioning, collation, value);
if (NULL != restype)
{
if (NULL != dim->partitioning)
*restype = dim->partitioning->partfunc.rettype;
else if (const_datum_type != InvalidOid)
*restype = const_datum_type;
else
*restype = dim->fd.column_type;
}
return value;
}
Point *
ts_point_create(int16 num_dimensions)
{
Point *p = palloc0(POINT_SIZE(num_dimensions));
p->cardinality = num_dimensions;
p->num_coords = 0;
return p;
}
TSDLLEXPORT Point *
ts_hyperspace_calculate_point(const Hyperspace *hs, TupleTableSlot *slot)
{
Point *p = ts_point_create(hs->num_dimensions);
int i;
for (i = 0; i < hs->num_dimensions; i++)
{
const Dimension *d = &hs->dimensions[i];
Datum datum;
bool isnull;
Oid dimtype;
if (NULL != d->partitioning)
datum = ts_partitioning_func_apply_slot(d->partitioning, slot, &isnull);
else
datum = slot_getattr(slot, d->column_attno, &isnull);
switch (d->type)
{
case DIMENSION_TYPE_OPEN:
dimtype = ts_dimension_get_partition_type(d);
if (isnull)
ereport(ERROR,
(errcode(ERRCODE_NOT_NULL_VIOLATION),
errmsg("NULL value in column \"%s\" violates not-null constraint",
NameStr(d->fd.column_name)),
errhint("Columns used for time partitioning cannot be NULL.")));
p->coordinates[p->num_coords++] = ts_time_value_to_internal(datum, dimtype);
break;
case DIMENSION_TYPE_CLOSED:
p->coordinates[p->num_coords++] = (int64) DatumGetInt32(datum);
break;
case DIMENSION_TYPE_ANY:
elog(ERROR, "invalid dimension type when inserting tuple");
break;
}
}
return p;
}
static inline int64
interval_to_usec(Interval *interval)
{
return (interval->month * DAYS_PER_MONTH * USECS_PER_DAY) + (interval->day * USECS_PER_DAY) +
interval->time;
}
#define INT_TYPE_MAX(type) \
(int64)(((type) == INT2OID) ? PG_INT16_MAX : \
(((type) == INT4OID) ? PG_INT32_MAX : PG_INT64_MAX))
#define IS_VALID_NUM_SLICES(num_slices) ((num_slices) >= 1 && (num_slices) <= PG_INT16_MAX)
static int64
get_validated_integer_interval(Oid dimtype, int64 value)
{
if (value < 1 || value > INT_TYPE_MAX(dimtype))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid interval: must be between 1 and " INT64_FORMAT,
INT_TYPE_MAX(dimtype))));
if (IS_TIMESTAMP_TYPE(dimtype) && value < USECS_PER_SEC)
ereport(WARNING,
(errcode(ERRCODE_AMBIGUOUS_PARAMETER),
errmsg("unexpected interval: smaller than one second"),
errhint("The interval is specified in microseconds.")));
return value;