forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk.c
4846 lines (4163 loc) · 138 KB
/
chunk.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 <access/htup.h>
#include <access/htup_details.h>
#include <access/reloptions.h>
#include <access/tupdesc.h>
#include <access/xact.h>
#include <catalog/indexing.h>
#include <catalog/namespace.h>
#include <catalog/pg_class.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_trigger.h>
#include <catalog/pg_type.h>
#include <catalog/toasting.h>
#include <commands/defrem.h>
#include <commands/tablecmds.h>
#include <commands/trigger.h>
#include <executor/executor.h>
#include <fmgr.h>
#include <funcapi.h>
#include <miscadmin.h>
#include <nodes/execnodes.h>
#include <nodes/makefuncs.h>
#include <storage/lmgr.h>
#include <tcop/tcopprot.h>
#include <utils/acl.h>
#include <utils/builtins.h>
#include <utils/datum.h>
#include <utils/hsearch.h>
#include <utils/lsyscache.h>
#include <utils/syscache.h>
#include <utils/timestamp.h>
#include "chunk.h"
#include "bgw_policy/chunk_stats.h"
#include "cache.h"
#include "chunk_index.h"
#include "chunk_scan.h"
#include "compat/compat.h"
#include "cross_module_fn.h"
#include "debug_point.h"
#include "dimension.h"
#include "dimension_slice.h"
#include "dimension_vector.h"
#include "errors.h"
#include "export.h"
#include "extension.h"
#include "hypercube.h"
#include "hypertable.h"
#include "hypertable_cache.h"
#include "partitioning.h"
#include "process_utility.h"
#include "scan_iterator.h"
#include "scanner.h"
#include "time_utils.h"
#include "trigger.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/chunk_data_node.h"
#include "ts_catalog/compression_chunk_size.h"
#include "ts_catalog/continuous_agg.h"
#include "ts_catalog/hypertable_data_node.h"
#include "utils.h"
TS_FUNCTION_INFO_V1(ts_chunk_show_chunks);
TS_FUNCTION_INFO_V1(ts_chunk_drop_chunks);
TS_FUNCTION_INFO_V1(ts_chunk_drop_single_chunk);
TS_FUNCTION_INFO_V1(ts_chunk_attach_osm_table_chunk);
TS_FUNCTION_INFO_V1(ts_chunks_in);
TS_FUNCTION_INFO_V1(ts_chunk_id_from_relid);
TS_FUNCTION_INFO_V1(ts_chunk_show);
TS_FUNCTION_INFO_V1(ts_chunk_create);
TS_FUNCTION_INFO_V1(ts_chunk_status);
static bool ts_chunk_add_status(Chunk *chunk, int32 status);
#if PG14_GE
static bool ts_chunk_clear_status(Chunk *chunk, int32 status);
#endif
static const char *
DatumGetNameString(Datum datum)
{
Name name = DatumGetName(datum);
return pstrdup(NameStr(*name));
}
/* Used when processing scanned chunks */
typedef enum ChunkResult
{
CHUNK_DONE,
CHUNK_IGNORED,
CHUNK_PROCESSED
} ChunkResult;
/*
* Context for scanning and building a chunk from a stub.
*
* If found, the chunk will be created and the chunk pointer member is set in
* the result. Optionally, a caller can pre-allocate the chunk member's memory,
* which is useful if one, e.g., wants to fill in an memory-aligned array of
* chunks.
*
* If the chunk is a tombstone (dropped flag set), then the Chunk will not be
* created and instead is_dropped will be TRUE.
*/
typedef struct ChunkStubScanCtx
{
ChunkStub *stub;
Chunk *chunk;
bool is_dropped;
} ChunkStubScanCtx;
static bool
chunk_stub_is_valid(const ChunkStub *stub, int16 expected_slices)
{
return stub && stub->id > 0 && stub->constraints && expected_slices == stub->cube->num_slices &&
stub->cube->num_slices == stub->constraints->num_dimension_constraints;
}
typedef ChunkResult (*on_chunk_stub_func)(ChunkScanCtx *ctx, ChunkStub *stub);
static void chunk_scan_ctx_init(ChunkScanCtx *ctx, const Hyperspace *hs, const Point *point);
static void chunk_scan_ctx_destroy(ChunkScanCtx *ctx);
static void chunk_collision_scan(ChunkScanCtx *scanctx, const Hypercube *cube);
static int chunk_scan_ctx_foreach_chunk_stub(ChunkScanCtx *ctx, on_chunk_stub_func on_chunk,
uint16 limit);
static Datum chunks_return_srf(FunctionCallInfo fcinfo);
static int chunk_cmp(const void *ch1, const void *ch2);
static int chunk_point_find_chunk_id(const Hypertable *ht, const Point *p);
static void init_scan_by_qualified_table_name(ScanIterator *iterator, const char *schema_name,
const char *table_name);
static Hypertable *find_hypertable_from_table_or_cagg(Cache *hcache, Oid relid, bool allow_matht);
static Chunk *get_chunks_in_time_range(Hypertable *ht, int64 older_than, int64 newer_than,
const char *caller_name, MemoryContext mctx,
uint64 *num_chunks_returned, ScanTupLock *tuplock);
static Chunk *chunk_resurrect(const Hypertable *ht, int chunk_id);
/*
* The chunk status field values are persisted in the database and must never be changed.
* Those values are used as flags and must always be powers of 2 to allow bitwise operations.
*/
#define CHUNK_STATUS_DEFAULT 0
/*
* Setting a Data-Node chunk as CHUNK_STATUS_COMPRESSED means that the corresponding
* compressed_chunk_id field points to a chunk that holds the compressed data. Otherwise,
* the corresponding compressed_chunk_id is NULL.
*
* However, for Access-Nodes compressed_chunk_id is always NULL. CHUNK_STATUS_COMPRESSED being set
* means that a remote compress_chunk() operation has taken place for this distributed
* meta-chunk. On the other hand, if CHUNK_STATUS_COMPRESSED is cleared, then it is probable
* that a remote compress_chunk() has not taken place, but not certain.
*
* For the above reason, this flag should not be assumed to be consistent (when it is cleared)
* for Access-Nodes. When used in distributed hypertables one should take advantage of the
* idempotent properties of remote compress_chunk() and distributed compression policy to
* make progress.
*/
#define CHUNK_STATUS_COMPRESSED 1
/*
* When inserting into a compressed chunk the configured compress_orderby is not retained.
* Any such chunks need an explicit Sort step to produce ordered output until the chunk
* ordering has been restored by recompress_chunk. This flag can only exist on compressed
* chunks.
*/
#define CHUNK_STATUS_COMPRESSED_UNORDERED 2
/*
* A chunk is in frozen state (i.e no inserts/updates/deletes into this chunk are
* permitted. Other chunk level operations like dropping chunk etc. are also blocked.
*
*/
#define CHUNK_STATUS_FROZEN 4
/*
* A chunk is in this state when it is compressed but also has uncompressed tuples
* in the uncompressed chunk.
*/
#define CHUNK_STATUS_COMPRESSED_PARTIAL 8
static HeapTuple
chunk_formdata_make_tuple(const FormData_chunk *fd, TupleDesc desc)
{
Datum values[Natts_chunk];
bool nulls[Natts_chunk] = { false };
memset(values, 0, sizeof(Datum) * Natts_chunk);
values[AttrNumberGetAttrOffset(Anum_chunk_id)] = Int32GetDatum(fd->id);
values[AttrNumberGetAttrOffset(Anum_chunk_hypertable_id)] = Int32GetDatum(fd->hypertable_id);
values[AttrNumberGetAttrOffset(Anum_chunk_schema_name)] = NameGetDatum(&fd->schema_name);
values[AttrNumberGetAttrOffset(Anum_chunk_table_name)] = NameGetDatum(&fd->table_name);
/*when we insert a chunk the compressed chunk id is always NULL */
if (fd->compressed_chunk_id == INVALID_CHUNK_ID)
nulls[AttrNumberGetAttrOffset(Anum_chunk_compressed_chunk_id)] = true;
else
{
values[AttrNumberGetAttrOffset(Anum_chunk_compressed_chunk_id)] =
Int32GetDatum(fd->compressed_chunk_id);
}
values[AttrNumberGetAttrOffset(Anum_chunk_dropped)] = BoolGetDatum(fd->dropped);
values[AttrNumberGetAttrOffset(Anum_chunk_status)] = Int32GetDatum(fd->status);
values[AttrNumberGetAttrOffset(Anum_chunk_osm_chunk)] = BoolGetDatum(fd->osm_chunk);
return heap_form_tuple(desc, values, nulls);
}
void
ts_chunk_formdata_fill(FormData_chunk *fd, const TupleInfo *ti)
{
bool should_free;
HeapTuple tuple = ts_scanner_fetch_heap_tuple(ti, false, &should_free);
bool nulls[Natts_chunk];
Datum values[Natts_chunk];
memset(fd, 0, sizeof(FormData_chunk));
heap_deform_tuple(tuple, ts_scanner_get_tupledesc(ti), values, nulls);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_id)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_hypertable_id)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_schema_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_table_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_dropped)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_status)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_chunk_osm_chunk)]);
fd->id = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_id)]);
fd->hypertable_id = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_hypertable_id)]);
memcpy(&fd->schema_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_chunk_schema_name)]),
NAMEDATALEN);
memcpy(&fd->table_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_chunk_table_name)]),
NAMEDATALEN);
if (nulls[AttrNumberGetAttrOffset(Anum_chunk_compressed_chunk_id)])
fd->compressed_chunk_id = INVALID_CHUNK_ID;
else
fd->compressed_chunk_id =
DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_compressed_chunk_id)]);
fd->dropped = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_chunk_dropped)]);
fd->status = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_chunk_status)]);
fd->osm_chunk = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_chunk_osm_chunk)]);
if (should_free)
heap_freetuple(tuple);
}
int64
ts_chunk_primary_dimension_start(const Chunk *chunk)
{
return chunk->cube->slices[0]->fd.range_start;
}
int64
ts_chunk_primary_dimension_end(const Chunk *chunk)
{
return chunk->cube->slices[0]->fd.range_end;
}
static void
chunk_insert_relation(Relation rel, const Chunk *chunk)
{
HeapTuple new_tuple;
CatalogSecurityContext sec_ctx;
new_tuple = chunk_formdata_make_tuple(&chunk->fd, RelationGetDescr(rel));
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
ts_catalog_insert(rel, new_tuple);
ts_catalog_restore_user(&sec_ctx);
heap_freetuple(new_tuple);
}
void
ts_chunk_insert_lock(const Chunk *chunk, LOCKMODE lock)
{
Catalog *catalog = ts_catalog_get();
Relation rel;
rel = table_open(catalog_get_table_id(catalog, CHUNK), lock);
chunk_insert_relation(rel, chunk);
table_close(rel, lock);
}
typedef struct CollisionInfo
{
Hypercube *cube;
ChunkStub *colliding_chunk;
} CollisionInfo;
/*-
* Align a chunk's hypercube in 'aligned' dimensions.
*
* Alignment ensures that chunks line up in a particular dimension, i.e., their
* ranges should either be identical or not overlap at all.
*
* Non-aligned:
*
* ' [---------] <- existing slice
* ' [---------] <- calculated (new) slice
*
* To align the slices above there are two cases depending on where the
* insertion point happens:
*
* Case 1 (reuse slice):
*
* ' [---------]
* ' [--x------]
*
* The insertion point x falls within the range of the existing slice. We should
* reuse the existing slice rather than creating a new one.
*
* Case 2 (cut to align):
*
* ' [---------]
* ' [-------x-]
*
* The insertion point falls outside the range of the existing slice and we need
* to cut the new slice to line up.
*
* ' [---------]
* ' cut [---]
* '
*
* Note that slice reuse (case 1) happens already when calculating the tentative
* hypercube for the chunk, and is thus already performed once reaching this
* function. Thus, we deal only with case 2 here. Also note that a new slice
* might overlap in complicated ways, requiring multiple cuts. For instance,
* consider the following situation:
*
* ' [------] [-] [---]
* ' [---x-------] <- calculated slice
*
* This should but cut-to-align as follows:
*
* ' [------] [-] [---]
* ' [x]
*
* After a chunk collision scan, this function is called for each chunk in the
* chunk scan context. Chunks in the scan context may have only a partial set of
* slices if they only overlap in some, but not all, dimensions (see
* illustrations below). Still, partial chunks may still be of interest for
* alignment in a particular dimension. Thus, if a chunk has an overlapping
* slice in an aligned dimension, we cut to not overlap with that slice.
*/
static ChunkResult
do_dimension_alignment(ChunkScanCtx *scanctx, ChunkStub *stub)
{
CollisionInfo *info = scanctx->data;
Hypercube *cube = info->cube;
const Hyperspace *space = scanctx->space;
ChunkResult res = CHUNK_IGNORED;
int i;
for (i = 0; i < space->num_dimensions; i++)
{
const Dimension *dim = &space->dimensions[i];
const DimensionSlice *chunk_slice;
DimensionSlice *cube_slice;
int64 coord = scanctx->point->coordinates[i];
if (!dim->fd.aligned)
continue;
/*
* The stub might not have a slice for each dimension, so we cannot
* use array indexing. Fetch slice by dimension ID instead.
*/
chunk_slice = ts_hypercube_get_slice_by_dimension_id(stub->cube, dim->fd.id);
if (NULL == chunk_slice)
continue;
cube_slice = cube->slices[i];
/*
* Only cut-to-align if the slices collide and are not identical
* (i.e., if we are reusing an existing slice we should not cut it)
*/
if (!ts_dimension_slices_equal(cube_slice, chunk_slice) &&
ts_dimension_slices_collide(cube_slice, chunk_slice))
{
ts_dimension_slice_cut(cube_slice, chunk_slice, coord);
res = CHUNK_PROCESSED;
}
}
return res;
}
/*
* Calculate, and potentially set, a new chunk interval for an open dimension.
*/
static bool
calculate_and_set_new_chunk_interval(const Hypertable *ht, const Point *p)
{
Hyperspace *hs = ht->space;
Dimension *dim = NULL;
Datum datum;
int64 chunk_interval, coord;
int i;
if (!OidIsValid(ht->chunk_sizing_func) || ht->fd.chunk_target_size <= 0)
return false;
/* Find first open dimension */
for (i = 0; i < hs->num_dimensions; i++)
{
dim = &hs->dimensions[i];
if (IS_OPEN_DIMENSION(dim))
break;
dim = NULL;
}
/* Nothing to do if no open dimension */
if (NULL == dim)
{
elog(WARNING,
"adaptive chunking enabled on hypertable \"%s\" without an open (time) dimension",
get_rel_name(ht->main_table_relid));
return false;
}
coord = p->coordinates[i];
datum = OidFunctionCall3(ht->chunk_sizing_func,
Int32GetDatum(dim->fd.id),
Int64GetDatum(coord),
Int64GetDatum(ht->fd.chunk_target_size));
chunk_interval = DatumGetInt64(datum);
/* Check if the function didn't set and interval or nothing changed */
if (chunk_interval <= 0 || chunk_interval == dim->fd.interval_length)
return false;
/* Update the dimension */
ts_dimension_set_chunk_interval(dim, chunk_interval);
return true;
}
/*
* Resolve chunk collisions.
*
* After a chunk collision scan, this function is called for each chunk in the
* chunk scan context. We only care about chunks that have a full set of
* slices/constraints that overlap with our tentative hypercube, i.e., they
* fully collide. We resolve those collisions by cutting the hypercube.
*/
static ChunkResult
do_collision_resolution(ChunkScanCtx *scanctx, ChunkStub *stub)
{
CollisionInfo *info = scanctx->data;
Hypercube *cube = info->cube;
const Hyperspace *space = scanctx->space;
ChunkResult res = CHUNK_IGNORED;
int i;
if (stub->cube->num_slices != space->num_dimensions || !ts_hypercubes_collide(cube, stub->cube))
return CHUNK_IGNORED;
for (i = 0; i < space->num_dimensions; i++)
{
DimensionSlice *cube_slice = cube->slices[i];
DimensionSlice *chunk_slice = stub->cube->slices[i];
int64 coord = scanctx->point->coordinates[i];
/*
* Only cut if we aren't reusing an existing slice and there is a
* collision
*/
if (!ts_dimension_slices_equal(cube_slice, chunk_slice) &&
ts_dimension_slices_collide(cube_slice, chunk_slice))
{
ts_dimension_slice_cut(cube_slice, chunk_slice, coord);
res = CHUNK_PROCESSED;
/*
* Redo the collision check after each cut since cutting in one
* dimension might have resolved the collision in another
*/
if (!ts_hypercubes_collide(cube, stub->cube))
return res;
}
}
Assert(!ts_hypercubes_collide(cube, stub->cube));
return res;
}
static ChunkResult
check_for_collisions(ChunkScanCtx *scanctx, ChunkStub *stub)
{
CollisionInfo *info = scanctx->data;
Hypercube *cube = info->cube;
const Hyperspace *space = scanctx->space;
/* Check if this chunk collides with our hypercube */
if (stub->cube->num_slices == space->num_dimensions && ts_hypercubes_collide(cube, stub->cube))
{
info->colliding_chunk = stub;
return CHUNK_DONE;
}
return CHUNK_IGNORED;
}
/*
* Check if a (tentative) chunk collides with existing chunks.
*
* Return the colliding chunk. Note that the chunk is a stub and not a full
* chunk.
*/
static ChunkStub *
chunk_collides(const Hypertable *ht, const Hypercube *hc)
{
ChunkScanCtx scanctx;
CollisionInfo info = {
.cube = (Hypercube *) hc,
.colliding_chunk = NULL,
};
chunk_scan_ctx_init(&scanctx, ht->space, NULL);
/* Scan for all chunks that collide with the hypercube of the new chunk */
chunk_collision_scan(&scanctx, hc);
scanctx.data = &info;
/* Find chunks that collide */
chunk_scan_ctx_foreach_chunk_stub(&scanctx, check_for_collisions, 0);
chunk_scan_ctx_destroy(&scanctx);
return info.colliding_chunk;
}
/*-
* Resolve collisions and perform alignmment.
*
* Chunks collide only if their hypercubes overlap in all dimensions. For
* instance, the 2D chunks below collide because they overlap in both the X and
* Y dimensions:
*
* ' _____
* ' | |
* ' | ___|__
* ' |_|__| |
* ' | |
* ' |_____|
*
* While the following chunks do not collide, although they still overlap in the
* X dimension:
*
* ' _____
* ' | |
* ' | |
* ' |____|
* ' ______
* ' | |
* ' | *|
* ' |_____|
*
* For the collision case above we obviously want to cut our hypercube to no
* longer collide with existing chunks. However, the second case might still be
* of interest for alignment in case X is an 'aligned' dimension. If '*' is the
* insertion point, then we still want to cut the hypercube to ensure that the
* dimension remains aligned, like so:
*
* ' _____
* ' | |
* ' | |
* ' |____|
* ' ___
* ' | |
* ' |*|
* ' |_|
*
*
* We perform alignment first as that might actually resolve chunk
* collisions. After alignment we check for any remaining collisions.
*/
static void
chunk_collision_resolve(const Hypertable *ht, Hypercube *cube, const Point *p)
{
ChunkScanCtx scanctx;
CollisionInfo info = {
.cube = cube,
.colliding_chunk = NULL,
};
chunk_scan_ctx_init(&scanctx, ht->space, p);
/* Scan for all chunks that collide with the hypercube of the new chunk */
chunk_collision_scan(&scanctx, cube);
scanctx.data = &info;
/* Cut the hypercube in any aligned dimensions */
chunk_scan_ctx_foreach_chunk_stub(&scanctx, do_dimension_alignment, 0);
/*
* If there are any remaining collisions with chunks, then cut-to-fit to
* resolve those collisions
*/
chunk_scan_ctx_foreach_chunk_stub(&scanctx, do_collision_resolution, 0);
chunk_scan_ctx_destroy(&scanctx);
}
static int
chunk_add_constraints(const Chunk *chunk)
{
int num_added;
num_added = ts_chunk_constraints_add_dimension_constraints(chunk->constraints,
chunk->fd.id,
chunk->cube);
num_added += ts_chunk_constraints_add_inheritable_constraints(chunk->constraints,
chunk->fd.id,
chunk->relkind,
chunk->hypertable_relid);
return num_added;
}
/* applies the attributes and statistics target for columns on the hypertable
to columns on the chunk */
static void
set_attoptions(Relation ht_rel, Oid chunk_oid)
{
TupleDesc tupleDesc = RelationGetDescr(ht_rel);
int natts = tupleDesc->natts;
int attno;
List *alter_cmds = NIL;
for (attno = 1; attno <= natts; attno++)
{
Form_pg_attribute attribute = TupleDescAttr(tupleDesc, attno - 1);
char *attributeName = NameStr(attribute->attname);
HeapTuple tuple;
Datum options;
bool isnull;
/* Ignore dropped */
if (attribute->attisdropped)
continue;
tuple = SearchSysCacheAttName(RelationGetRelid(ht_rel), attributeName);
Assert(tuple != NULL);
/*
* Pass down the attribute options (ALTER TABLE ALTER COLUMN SET
* attribute_option)
*/
options = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions, &isnull);
if (!isnull)
{
AlterTableCmd *cmd = makeNode(AlterTableCmd);
cmd->subtype = AT_SetOptions;
cmd->name = attributeName;
cmd->def = (Node *) untransformRelOptions(options);
alter_cmds = lappend(alter_cmds, cmd);
}
/*
* Pass down the attribute options (ALTER TABLE ALTER COLUMN SET
* STATISTICS)
*/
options = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attstattarget, &isnull);
if (!isnull)
{
int32 target = DatumGetInt32(options);
/* Don't do anything if it's set to the default */
if (target != -1)
{
AlterTableCmd *cmd = makeNode(AlterTableCmd);
cmd->subtype = AT_SetStatistics;
cmd->name = attributeName;
cmd->def = (Node *) makeInteger(target);
alter_cmds = lappend(alter_cmds, cmd);
}
}
ReleaseSysCache(tuple);
}
if (alter_cmds != NIL)
{
ts_alter_table_with_event_trigger(chunk_oid, NULL, alter_cmds, false);
list_free_deep(alter_cmds);
}
}
static void
create_toast_table(CreateStmt *stmt, Oid chunk_oid)
{
/* similar to tcop/utility.c */
static char *validnsps[] = HEAP_RELOPT_NAMESPACES;
Datum toast_options =
transformRelOptions((Datum) 0, stmt->options, "toast", validnsps, true, false);
(void) heap_reloptions(RELKIND_TOASTVALUE, toast_options, true);
NewRelationCreateToastTable(chunk_oid, toast_options);
}
/*
* Get the access method name for a relation.
*/
static char *
get_am_name_for_rel(Oid relid)
{
HeapTuple tuple;
Form_pg_class cform;
Oid amoid;
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
elog(ERROR, "cache lookup failed for relation %u", relid);
cform = (Form_pg_class) GETSTRUCT(tuple);
amoid = cform->relam;
ReleaseSysCache(tuple);
return get_am_name(amoid);
}
static void
copy_hypertable_acl_to_relid(const Hypertable *ht, const Oid owner_id, const Oid relid)
{
ts_copy_relation_acl(ht->main_table_relid, relid, owner_id);
}
/*
* Create a chunk's table.
*
* A chunk inherits from the main hypertable and will have the same owner. Since
* chunks can be created either in the TimescaleDB internal schema or in a
* user-specified schema, some care has to be taken to use the right
* permissions, depending on the case:
*
* 1. if the chunk is created in the internal schema, we create it as the
* catalog/schema owner (i.e., anyone can create chunks there via inserting into
* a hypertable, but can not do it via CREATE TABLE).
*
* 2. if the chunk is created in a user-specified "associated schema", then we
* shouldn't use the catalog owner to create the table since that typically
* implies super-user permissions. If we would allow that, anyone can specify
* someone else's schema in create_hypertable() and create chunks in it without
* having the proper permissions to do so. With this logic, the hypertable owner
* must have permissions to create tables in the associated schema, or else
* table creation will fail. If the schema doesn't yet exist, the table owner
* instead needs the proper permissions on the database to create the schema.
*/
Oid
ts_chunk_create_table(const Chunk *chunk, const Hypertable *ht, const char *tablespacename)
{
Relation rel;
ObjectAddress objaddr;
int sec_ctx;
/*
* The CreateForeignTableStmt embeds a regular CreateStmt, so we can use
* it to create both regular and foreign tables
*/
CreateForeignTableStmt stmt = {
.base.type = T_CreateStmt,
.base.relation = makeRangeVar((char *) NameStr(chunk->fd.schema_name),
(char *) NameStr(chunk->fd.table_name),
0),
.base.inhRelations = list_make1(makeRangeVar((char *) NameStr(ht->fd.schema_name),
(char *) NameStr(ht->fd.table_name),
0)),
.base.tablespacename = tablespacename ? (char *) tablespacename : NULL,
/* Propagate storage options of the main table to a regular chunk
* table, but avoid using it for a foreign chunk table. */
.base.options =
(chunk->relkind == RELKIND_RELATION) ? ts_get_reloptions(ht->main_table_relid) : NIL,
.base.accessMethod = (chunk->relkind == RELKIND_RELATION) ?
get_am_name_for_rel(chunk->hypertable_relid) :
NULL,
};
Oid uid, saved_uid;
Assert(chunk->hypertable_relid == ht->main_table_relid);
rel = table_open(ht->main_table_relid, AccessShareLock);
/*
* If the chunk is created in the internal schema, become the catalog
* owner, otherwise become the hypertable owner
*/
if (namestrcmp((Name) &chunk->fd.schema_name, INTERNAL_SCHEMA_NAME) == 0)
uid = ts_catalog_database_info_get()->owner_uid;
else
uid = rel->rd_rel->relowner;
GetUserIdAndSecContext(&saved_uid, &sec_ctx);
if (uid != saved_uid)
SetUserIdAndSecContext(uid, sec_ctx | SECURITY_LOCAL_USERID_CHANGE);
objaddr = DefineRelation(&stmt.base, chunk->relkind, rel->rd_rel->relowner, NULL, NULL);
/* Make the newly defined relation visible so that we can update the
* ACL. */
CommandCounterIncrement();
/* Copy acl from hypertable to chunk relation record */
copy_hypertable_acl_to_relid(ht, rel->rd_rel->relowner, objaddr.objectId);
if (chunk->relkind == RELKIND_RELATION)
{
/*
* need to create a toast table explicitly for some of the option
* setting to work
*/
create_toast_table(&stmt.base, objaddr.objectId);
/*
* Some options require being table owner to set for example statistics
* so we have to set them before restoring security context
*/
set_attoptions(rel, objaddr.objectId);
if (uid != saved_uid)
SetUserIdAndSecContext(saved_uid, sec_ctx);
}
else if (chunk->relkind == RELKIND_FOREIGN_TABLE)
{
ChunkDataNode *cdn;
if (list_length(chunk->data_nodes) == 0)
ereport(ERROR,
(errcode(ERRCODE_TS_INSUFFICIENT_NUM_DATA_NODES),
(errmsg("no data nodes associated with chunk \"%s\"",
get_rel_name(chunk->table_id)))));
/*
* Use the first chunk data node as the "primary" to put in the foreign
* table
*/
cdn = linitial(chunk->data_nodes);
stmt.base.type = T_CreateForeignServerStmt;
stmt.servername = NameStr(cdn->fd.node_name);
/* Create the foreign table catalog information */
CreateForeignTable(&stmt, objaddr.objectId);
/*
* Some options require being table owner to set for example statistics
* so we have to set them before restoring security context
*/
set_attoptions(rel, objaddr.objectId);
/*
* Need to restore security context to execute remote commands as the
* original user
*/
if (uid != saved_uid)
SetUserIdAndSecContext(saved_uid, sec_ctx);
/* Create the corresponding chunk replicas on the remote data nodes */
ts_cm_functions->create_chunk_on_data_nodes(chunk, ht, NULL, NIL);
/* Record the remote data node chunk ID mappings */
ts_chunk_data_node_insert_multi(chunk->data_nodes);
}
else
elog(ERROR, "invalid relkind \"%c\" when creating chunk", chunk->relkind);
table_close(rel, AccessShareLock);
return objaddr.objectId;
}
static List *
chunk_assign_data_nodes(const Chunk *chunk, const Hypertable *ht)
{
List *htnodes;
List *chunk_data_nodes = NIL;
ListCell *lc;
if (chunk->relkind != RELKIND_FOREIGN_TABLE)
return NIL;
if (ht->data_nodes == NIL)
ereport(ERROR,
(errcode(ERRCODE_TS_INSUFFICIENT_NUM_DATA_NODES),
(errmsg("no data nodes associated with hypertable \"%s\"",
get_rel_name(ht->main_table_relid)))));
Assert(chunk->cube != NULL);
htnodes = ts_hypertable_assign_chunk_data_nodes(ht, chunk->cube);
Assert(htnodes != NIL);
foreach (lc, htnodes)
{
const char *dn = lfirst(lc);
ForeignServer *foreign_server = GetForeignServerByName(dn, false);
ChunkDataNode *chunk_data_node = palloc0(sizeof(ChunkDataNode));
/*
* Create a stub data node (partially filled in entry). This will be
* fully filled in and persisted to metadata tables once we create the
* remote tables during insert
*/
chunk_data_node->fd.chunk_id = chunk->fd.id;
chunk_data_node->fd.node_chunk_id = -1;
namestrcpy(&chunk_data_node->fd.node_name, foreign_server->servername);
chunk_data_node->foreign_server_oid = foreign_server->serverid;
chunk_data_nodes = lappend(chunk_data_nodes, chunk_data_node);
}
return chunk_data_nodes;
}
List *
ts_chunk_get_data_node_name_list(const Chunk *chunk)
{
List *datanodes = NULL;
ListCell *lc;
foreach (lc, chunk->data_nodes)
{
ChunkDataNode *cdn = lfirst(lc);
datanodes = lappend(datanodes, NameStr(cdn->fd.node_name));
}
return datanodes;
}
bool
ts_chunk_has_data_node(const Chunk *chunk, const char *node_name)
{
ListCell *lc;
ChunkDataNode *cdn;
bool found = false;
if (chunk == NULL || node_name == NULL)
return false;
/* check that the chunk is indeed present on the specified data node */
foreach (lc, chunk->data_nodes)
{
cdn = lfirst(lc);
if (namestrcmp(&cdn->fd.node_name, node_name) == 0)
{
found = true;
break;
}
}
return found;
}
static int32
get_next_chunk_id()
{
int32 chunk_id;
CatalogSecurityContext sec_ctx;
const Catalog *catalog = ts_catalog_get();
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
chunk_id = ts_catalog_table_next_seq_id(catalog, CHUNK);
ts_catalog_restore_user(&sec_ctx);
return chunk_id;
}
/*
* Create a chunk object from the dimensional constraints in the given hypercube.
*
* The chunk object is then used to create the actual chunk table and update the
* metadata separately.
*
* The table name for the chunk can be given explicitly, or generated if
* table_name is NULL. If the table name is generated, it will use the given
* prefix or, if NULL, use the hypertable's associated table prefix. Similarly,
* if schema_name is NULL it will use the hypertable's associated schema for
* the chunk.
*/
static Chunk *
chunk_create_object(const Hypertable *ht, Hypercube *cube, const char *schema_name,
const char *table_name, const char *prefix, int32 chunk_id)
{