-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathchunk.c
More file actions
5341 lines (4617 loc) · 145 KB
/
Copy pathchunk.c
File metadata and controls
5341 lines (4617 loc) · 145 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/genam.h>
#include <access/htup.h>
#include <access/htup_details.h>
#include <access/reloptions.h>
#include <access/table.h>
#include <access/tableam.h>
#include <access/tupdesc.h>
#include <access/xact.h>
#include <catalog/indexing.h>
#include <catalog/namespace.h>
#include <catalog/pg_attribute.h>
#include <catalog/pg_class.h>
#include <catalog/pg_constraint.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_opfamily.h>
#include <catalog/pg_publication.h>
#include <catalog/pg_publication_rel_d.h>
#include <catalog/pg_trigger.h>
#include <catalog/pg_type.h>
#include <catalog/pg_type_d.h>
#include <catalog/toasting.h>
#include <commands/defrem.h>
#include <commands/publicationcmds.h>
#include <commands/tablecmds.h>
#include <commands/trigger.h>
#include <executor/executor.h>
#include <fmgr.h>
#include <foreign/fdwapi.h>
#include <funcapi.h>
#include <miscadmin.h>
#include <nodes/execnodes.h>
#include <nodes/lockoptions.h>
#include <nodes/makefuncs.h>
#include <nodes/value.h>
#include <parser/parse_node.h>
#include <storage/lmgr.h>
#include <storage/lockdefs.h>
#include <tcop/tcopprot.h>
#include <ts_stats/ts_stats_record.h>
#include <utils/acl.h>
#include <utils/array.h>
#include <utils/builtins.h>
#include <utils/datum.h>
#include <utils/elog.h>
#include <utils/fmgroids.h>
#include <utils/hsearch.h>
#include <utils/inval.h>
#include <utils/lsyscache.h>
#include <utils/palloc.h>
#include <utils/syscache.h>
#include <utils/timestamp.h>
#include <utils/typcache.h>
#include "chunk.h"
#include "compat/compat.h"
#include "bgw_policy/chunk_stats.h"
#include "cache.h"
#include "chunk_index.h"
#include "cross_module_fn.h"
#include "debug_assert.h"
#include "debug_point.h"
#include "dimension.h"
#include "dimension_slice.h"
#include "dimension_vector.h"
#include "errors.h"
#include "foreign_key.h"
#include "guc.h"
#include "hypercube.h"
#include "hypertable.h"
#include "hypertable_cache.h"
#include "osm_callbacks.h"
#include "partition_chunk.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_column_stats.h"
#include "ts_catalog/chunk_rewrite.h"
#include "ts_catalog/compression_chunk_size.h"
#include "ts_catalog/compression_settings.h"
#include "ts_catalog/continuous_agg.h"
#include "ts_catalog/continuous_aggs_watermark.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_chunk_drop_osm_chunk);
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);
static const char *
DatumGetRegClassString(Datum datum)
{
return DatumGetCString(DirectFunctionCall1(regclassout, datum));
}
/* 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.
*
*/
typedef struct ChunkStubScanCtx
{
ChunkStub *stub;
Chunk *chunk;
LOCKMODE chunk_lockmode;
const ScanTupLock *slice_lock;
} ChunkStubScanCtx;
typedef ChunkResult (*on_chunk_stub_func)(ChunkScanCtx *ctx, ChunkStub *stub);
static void chunk_scan_ctx_init(ChunkScanCtx *ctx, const Hypertable *ht, 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,
uint64 limit);
static Datum show_chunks_return_srf(FunctionCallInfo fcinfo);
static int chunk_cmp(const void *ch1, const void *ch2);
static void init_scan_by_relid(ScanIterator *iterator, Oid relid);
static Chunk *get_chunks_in_time_range(Hypertable *ht, int64 older_than, int64 newer_than,
MemoryContext mctx, uint64 *num_chunks_returned,
ScanTupLock *tuplock);
static Chunk *get_chunks_in_creation_time_range(Hypertable *ht, int64 older_than, int64 newer_than,
MemoryContext mctx, uint64 *num_chunks_returned,
ScanTupLock *tupLock);
static HeapTuple
chunk_formdata_make_tuple(const FormData_chunk *fd, TupleDesc desc)
{
Datum values[Natts_chunk];
bool nulls[Natts_chunk] = { false };
Assert(OidIsValid(fd->relid));
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_status)] = Int32GetDatum(fd->status);
values[AttrNumberGetAttrOffset(Anum_chunk_osm_chunk)] = BoolGetDatum(fd->osm_chunk);
values[AttrNumberGetAttrOffset(Anum_chunk_creation_time)] = Int64GetDatum(fd->creation_time);
values[AttrNumberGetAttrOffset(Anum_chunk_relid)] = ObjectIdGetDatum(fd->relid);
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);
/*
* Every chunk column is fixed-length and NOT NULL, and the catalog table is
* rebuilt rather than altered on upgrade, so a stored tuple always holds all
* of its attributes. We can therefore copy the form directly.
*/
Assert(HeapTupleHeaderGetNatts(tuple->t_data) == Natts_chunk);
*fd = *(Form_chunk) GETSTRUCT(tuple);
if (should_free)
{
heap_freetuple(tuple);
}
}
/*
* A chunk's schema and table name are not stored in the catalog; they are
* looked up from the chunk relation on demand.
*/
char *
ts_chunk_get_schema_name(const Chunk *chunk)
{
return get_namespace_name(get_rel_namespace(chunk->fd.relid));
}
char *
ts_chunk_get_table_name(const Chunk *chunk)
{
return get_rel_name(chunk->fd.relid);
}
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;
FormData_chunk fd = chunk->fd;
new_tuple = chunk_formdata_make_tuple(&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->ht->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;
}
/*
* 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->ht->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->ht->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, 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 alignment.
*
* 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, 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);
}
/* 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)
{
AlterTableInternal(chunk_oid, alter_cmds, false);
list_free_deep(alter_cmds);
}
}
static void
create_toast_table(CreateStmt *stmt, Oid chunk_oid)
{
/* similar to tcop/utility.c */
#if PG18_LT
char *validnsps[] = HEAP_RELOPT_NAMESPACES;
#else
const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
#endif
Datum toast_options =
transformRelOptions(UnassignedDatum, stmt->options, "toast", validnsps, true, false);
(void) heap_reloptions(RELKIND_TOASTVALUE, toast_options, true);
NewRelationCreateToastTable(chunk_oid, toast_options);
}
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 *schema_name,
const char *table_name, const char *tablespacename)
{
Relation rel;
ObjectAddress address;
int sec_ctx;
char *amname = NULL;
amname = get_am_name(ts_get_rel_am(chunk->hypertable_relid));
/*
* CreateStmt node to create the chunk table
*/
CreateStmt stmt = {
.type = T_CreateStmt,
.relation = makeRangeVar((char *) schema_name, (char *) table_name, 0),
.tablespacename = tablespacename ? (char *) tablespacename : NULL,
.options =
(chunk->relkind == RELKIND_RELATION) ? ts_get_reloptions(ht->main_table_relid) : NIL,
.accessMethod = amname,
};
/*
* If partitioned hypertables are enabled, create the chunk as a standalone
* table with the same columns as the hypertable to attach it as a partition
* later. Otherwise, create it as an inherited table.
*/
if (is_partitioning_allowed(ht->main_table_relid))
{
List *attlist = NIL;
List *constraints = NIL;
ts_partition_chunk_prepare_attributes(ht->main_table_relid, &attlist, &constraints);
stmt.tableElts = attlist;
stmt.constraints = constraints;
}
else
{
stmt.inhRelations = list_make1(makeRangeVar((char *) NameStr(ht->fd.schema_name),
(char *) NameStr(ht->fd.table_name),
0));
}
Oid uid, saved_uid;
Assert(chunk->hypertable_relid == ht->main_table_relid);
rel = table_open(ht->main_table_relid, AccessShareLock);
/* Inherit the persistence (LOGGED or UNLOGGED) from the parent hypertable */
stmt.relation->relpersistence = rel->rd_rel->relpersistence;
/*
* If the chunk is created in the internal schema, become the catalog
* owner, otherwise become the hypertable owner
*/
if (strcmp(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);
}
/* Prepare event trigger state and invoke ddl_command_start triggers */
if (ts_guc_enable_event_triggers)
{
EventTriggerBeginCompleteQuery();
EventTriggerDDLCommandStart((Node *) &stmt);
}
address = DefineRelation(&stmt, chunk->relkind, rel->rd_rel->relowner, NULL, NULL);
/* Invoke ddl_command_end triggers and clean up the event trigger state */
if (ts_guc_enable_event_triggers)
{
EventTriggerCollectSimpleCommand(address, InvalidObjectAddress, (Node *) &stmt);
EventTriggerDDLCommandEnd((Node *) &stmt);
EventTriggerEndCompleteQuery();
}
/* 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, address.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, address.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, address.objectId);
if (uid != saved_uid)
{
SetUserIdAndSecContext(saved_uid, sec_ctx);
}
}
else
{
elog(ERROR, "invalid relkind \"%c\" when creating chunk", chunk->relkind);
}
/* Insert the table into the cache to attach it as partition later */
if (is_partitioning_allowed(ht->main_table_relid))
{
ts_partition_cache_insert_chunk(ht, address.objectId);
}
table_close(rel, AccessShareLock);
return address.objectId;
}
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;
}
/*
* Stamp the chunk_id on every cube slice
*/
static void
prepare_cube_slices_for_chunk(Hypercube *cube, int32 chunk_id)
{
Assert(chunk_id > 0);
for (int i = 0; i < cube->num_slices; i++)
{
cube->slices[i]->fd.id = 0;
cube->slices[i]->fd.chunk_id = chunk_id;
}
}
/*
* Pick a table name for a new chunk. The table name can be given explicitly, or
* generated from the hypertable's associated table prefix and the chunk id if
* table_name is NULL.
*/
static char *
chunk_choose_table_name(const Hypertable *ht, int32 chunk_id, const char *table_name)
{
if (NULL == table_name || table_name[0] == '\0')
{
const char *prefix = NameStr(ht->fd.associated_table_prefix);
char *name = psprintf("%s_%d_chunk", prefix, chunk_id);
if (strlen(name) >= NAMEDATALEN)
{
ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("chunk table name too long")));
}
return name;
}
return pstrdup(table_name);
}
/*
* 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.
*/
static Chunk *
chunk_create_object(const Hypertable *ht, Hypercube *cube, int32 chunk_id)
{
const Hyperspace *hs = ht->space;
/* Create a new chunk based on the hypercube */
Chunk *chunk = ts_chunk_create_base(chunk_id);
chunk->fd.hypertable_id = hs->hypertable_id;
chunk->cube = cube;
chunk->hypertable_relid = ht->main_table_relid;
return chunk;
}
/*
* Ensure the replica identity setting of a chunk matches that of the root
* table.
*/
static void
chunk_set_replica_identity(const Chunk *chunk)
{
Relation ht_rel = relation_open(chunk->hypertable_relid, AccessShareLock);
Relation ch_rel = relation_open(chunk->fd.relid, AccessShareLock);
/* Do nothing if REPLICA IDENTITY of hypertable and chunk are equal */
if (ht_rel->rd_rel->relreplident == ch_rel->rd_rel->relreplident)
{
table_close(ch_rel, NoLock);
table_close(ht_rel, NoLock);
return;
}
ReplicaIdentityStmt stmt = {
.type = T_ReplicaIdentityStmt,
.identity_type = ht_rel->rd_rel->relreplident,
};
AlterTableCmd cmd = {
.type = T_AlterTableCmd,
.def = (Node *) &stmt,
.subtype = AT_ReplicaIdentity,
};
CatalogSecurityContext sec_ctx;
if (stmt.identity_type == REPLICA_IDENTITY_INDEX)
{
/* Use RelationGetReplicaIndex() instead of rd_replidindex
* directly to ensure the index list is loaded after any
* relcache invalidation. */
Oid ht_indexoid = RelationGetReplicaIndex(ht_rel);
Oid chunk_index_relid = InvalidOid;
if (OidIsValid(ht_indexoid))
{
chunk_index_relid = ts_chunk_index_get_by_hypertable_indexrelid(ch_rel, ht_indexoid);
}
if (OidIsValid(chunk_index_relid))
{
stmt.name = get_rel_name(chunk_index_relid);
}
else
{
stmt.identity_type = REPLICA_IDENTITY_NOTHING;
}
}
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
ts_alter_table_with_event_trigger(chunk->fd.relid, NULL, list_make1(&cmd), false);
ts_catalog_restore_user(&sec_ctx);
table_close(ch_rel, NoLock);
table_close(ht_rel, NoLock);
}
static void
chunk_create_table_constraints(const Hypertable *ht, const Chunk *chunk)
{
/* Do not create any of these for partitioned hypertables */
if (is_partitioning_allowed(ht->main_table_relid))
{
return;
}
/* Create the chunk's constraints, triggers, and indexes */
ts_chunk_constraints_create(ht, chunk);
if (chunk->relkind == RELKIND_RELATION && !IS_OSM_CHUNK(chunk))
{
ts_trigger_create_all_on_chunk(chunk);
ts_chunk_index_create_all(chunk->fd.hypertable_id,
chunk->hypertable_relid,
chunk->fd.id,
chunk->fd.relid,
InvalidOid);
chunk_set_replica_identity(chunk);
}
/* Copy FK constraints after indexes are created, since FK validation
* requires the supporting unique index to exist on the chunk. */
ts_chunk_copy_referencing_fk(ht, chunk);
ts_chunk_inherit_outbound_fk(ht, chunk);
}
static Oid
chunk_create_table(Chunk *chunk, const Hypertable *ht, const char *schema_name,
const char *table_name)
{
/* Create the actual table relation for the chunk */
const char *tablespace = ts_hypertable_select_tablespace_name(ht, chunk);
chunk->fd.relid = ts_chunk_create_table(chunk, ht, schema_name, table_name, tablespace);
Assert(OidIsValid(chunk->fd.relid));
return chunk->fd.relid;
}
/*
* Creates only a table for a chunk.
* Either table name or chunk id needs to be provided.
*/
static Chunk *
chunk_create_only_table_after_lock(const Hypertable *ht, Hypercube *cube, const char *schema_name,
const char *table_name, int32 chunk_id)
{
Assert(table_name != NULL || chunk_id != INVALID_CHUNK_ID);
if (!schema_name || schema_name[0] == '\0')
{
schema_name = NameStr(ht->fd.associated_schema_name);
}
Chunk *chunk = chunk_create_object(ht, cube, chunk_id);
char *chunk_table_name = chunk_choose_table_name(ht, chunk_id, table_name);
chunk_create_table(chunk, ht, schema_name, chunk_table_name);
return chunk;
}
static void
get_hypertable_publication_filters(Oid puboid, const Chunk *chunk, List **columns,
Node **whereClause)
{
HeapTuple pubtuple;
Datum datum;
bool isnull;
*columns = NIL;
*whereClause = NULL;
/* Get filters for hypertable, chunk should inherit them */
pubtuple = SearchSysCache2(PUBLICATIONRELMAP,
ObjectIdGetDatum(chunk->hypertable_relid),
ObjectIdGetDatum(puboid));
if (!HeapTupleIsValid(pubtuple))
{
return;
}