forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hypertable.c
2685 lines (2284 loc) · 78.1 KB
/
hypertable.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/heapam.h>
#include <access/htup_details.h>
#include <access/relscan.h>
#include <catalog/indexing.h>
#include <catalog/namespace.h>
#include <catalog/pg_collation.h>
#include <catalog/pg_constraint.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#include <commands/dbcommands.h>
#include <commands/schemacmds.h>
#include <commands/tablecmds.h>
#include <commands/tablespace.h>
#include <commands/trigger.h>
#include <funcapi.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <nodes/memnodes.h>
#include <nodes/value.h>
#include <parser/parse_func.h>
#include <storage/lmgr.h>
#include <utils/acl.h>
#include <utils/builtins.h>
#include <utils/lsyscache.h>
#include <utils/memutils.h>
#include <utils/snapmgr.h>
#include <utils/syscache.h>
#include "hypertable.h"
#include "hypertable_data_node.h"
#include "hypercube.h"
#include "dimension.h"
#include "chunk.h"
#include "chunk_adaptive.h"
#include "hypertable_compression.h"
#include "subspace_store.h"
#include "hypertable_cache.h"
#include "trigger.h"
#include "scanner.h"
#include "scan_iterator.h"
#include "catalog.h"
#include "dimension_slice.h"
#include "dimension_vector.h"
#include "hypercube.h"
#include "indexing.h"
#include "guc.h"
#include "errors.h"
#include "copy.h"
#include "utils.h"
#include "bgw_policy/policy.h"
#include "continuous_agg.h"
#include "license_guc.h"
#include "cross_module_fn.h"
#include "scan_iterator.h"
Oid
ts_rel_get_owner(Oid relid)
{
HeapTuple tuple;
Oid ownerid;
if (!OidIsValid(relid))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("unable to get owner for relation with OID %u: invalid OID", relid)));
tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (!HeapTupleIsValid(tuple))
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_TABLE),
errmsg("unable to get owner for relation with OID %u: does not exist", relid)));
ownerid = ((Form_pg_class) GETSTRUCT(tuple))->relowner;
ReleaseSysCache(tuple);
return ownerid;
}
bool
ts_hypertable_has_privs_of(Oid hypertable_oid, Oid userid)
{
return has_privs_of_role(userid, ts_rel_get_owner(hypertable_oid));
}
/*
* The error output for permission denied errors such as these changed in PG11,
* it modifies places where relation is specified to note the specific object
* type we note that permissions are denied for the hypertable for all PG
* versions so that tests need not change due to one word changes in error
* messages and because it is more clear this way.
*/
Oid
ts_hypertable_permissions_check(Oid hypertable_oid, Oid userid)
{
Oid ownerid = ts_rel_get_owner(hypertable_oid);
if (!has_privs_of_role(userid, ownerid))
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be owner of hypertable \"%s\"", get_rel_name(hypertable_oid))));
return ownerid;
}
void
ts_hypertable_permissions_check_by_id(int32 hypertable_id)
{
Oid table_relid = ts_hypertable_id_to_relid(hypertable_id);
ts_hypertable_permissions_check(table_relid, GetUserId());
}
static Oid
get_chunk_sizing_func_oid(FormData_hypertable *fd)
{
Oid argtype[] = { INT4OID, INT8OID, INT8OID };
return LookupFuncName(list_make2(makeString(NameStr(fd->chunk_sizing_func_schema)),
makeString(NameStr(fd->chunk_sizing_func_name))),
sizeof(argtype) / sizeof(argtype[0]),
argtype,
false);
}
static HeapTuple
hypertable_formdata_make_tuple(const FormData_hypertable *fd, TupleDesc desc)
{
Datum values[Natts_hypertable];
bool nulls[Natts_hypertable] = { false };
memset(values, 0, sizeof(Datum) * Natts_hypertable);
values[AttrNumberGetAttrOffset(Anum_hypertable_id)] = Int32GetDatum(fd->id);
values[AttrNumberGetAttrOffset(Anum_hypertable_schema_name)] = NameGetDatum(&fd->schema_name);
values[AttrNumberGetAttrOffset(Anum_hypertable_table_name)] = NameGetDatum(&fd->table_name);
values[AttrNumberGetAttrOffset(Anum_hypertable_associated_schema_name)] =
NameGetDatum(&fd->associated_schema_name);
Assert(&fd->associated_table_prefix != NULL);
values[AttrNumberGetAttrOffset(Anum_hypertable_associated_table_prefix)] =
NameGetDatum(&fd->associated_table_prefix);
values[AttrNumberGetAttrOffset(Anum_hypertable_num_dimensions)] =
Int16GetDatum(fd->num_dimensions);
values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_schema)] =
NameGetDatum(&fd->chunk_sizing_func_schema);
values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_name)] =
NameGetDatum(&fd->chunk_sizing_func_name);
values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_target_size)] =
Int64GetDatum(fd->chunk_target_size);
values[AttrNumberGetAttrOffset(Anum_hypertable_compressed)] = BoolGetDatum(fd->compressed);
if (fd->compressed_hypertable_id == INVALID_HYPERTABLE_ID)
nulls[AttrNumberGetAttrOffset(Anum_hypertable_compressed_hypertable_id)] = true;
else
values[AttrNumberGetAttrOffset(Anum_hypertable_compressed_hypertable_id)] =
Int32GetDatum(fd->compressed_hypertable_id);
if (fd->replication_factor == 0)
nulls[AttrNumberGetAttrOffset(Anum_hypertable_replication_factor)] = true;
else
values[AttrNumberGetAttrOffset(Anum_hypertable_replication_factor)] =
Int16GetDatum(fd->replication_factor);
return heap_form_tuple(desc, values, nulls);
}
static void
hypertable_formdata_fill(FormData_hypertable *fd, const TupleInfo *ti)
{
bool nulls[Natts_hypertable];
Datum values[Natts_hypertable];
bool should_free;
HeapTuple tuple;
tuple = ts_scanner_fetch_heap_tuple(ti, false, &should_free);
heap_deform_tuple(tuple, ts_scanner_get_tupledesc(ti), values, nulls);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_id)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_schema_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_table_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_associated_schema_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_associated_table_prefix)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_num_dimensions)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_schema)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_name)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_chunk_target_size)]);
Assert(!nulls[AttrNumberGetAttrOffset(Anum_hypertable_compressed)]);
fd->id = DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_hypertable_id)]);
memcpy(&fd->schema_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_schema_name)]),
NAMEDATALEN);
memcpy(&fd->table_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_table_name)]),
NAMEDATALEN);
memcpy(&fd->associated_schema_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_associated_schema_name)]),
NAMEDATALEN);
memcpy(&fd->associated_table_prefix,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_associated_table_prefix)]),
NAMEDATALEN);
fd->num_dimensions =
DatumGetInt16(values[AttrNumberGetAttrOffset(Anum_hypertable_num_dimensions)]);
memcpy(&fd->chunk_sizing_func_schema,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_schema)]),
NAMEDATALEN);
memcpy(&fd->chunk_sizing_func_name,
DatumGetName(values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_sizing_func_name)]),
NAMEDATALEN);
fd->chunk_target_size =
DatumGetInt64(values[AttrNumberGetAttrOffset(Anum_hypertable_chunk_target_size)]);
fd->compressed = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_hypertable_compressed)]);
if (nulls[AttrNumberGetAttrOffset(Anum_hypertable_compressed_hypertable_id)])
fd->compressed_hypertable_id = INVALID_HYPERTABLE_ID;
else
fd->compressed_hypertable_id = DatumGetInt32(
values[AttrNumberGetAttrOffset(Anum_hypertable_compressed_hypertable_id)]);
if (nulls[AttrNumberGetAttrOffset(Anum_hypertable_replication_factor)])
fd->replication_factor = INVALID_HYPERTABLE_ID;
else
fd->replication_factor =
DatumGetInt16(values[AttrNumberGetAttrOffset(Anum_hypertable_replication_factor)]);
if (should_free)
heap_freetuple(tuple);
}
Hypertable *
ts_hypertable_from_tupleinfo(const TupleInfo *ti)
{
Oid namespace_oid;
Hypertable *h = MemoryContextAllocZero(ti->mctx, sizeof(Hypertable));
hypertable_formdata_fill(&h->fd, ti);
namespace_oid = get_namespace_oid(NameStr(h->fd.schema_name), false);
h->main_table_relid = get_relname_relid(NameStr(h->fd.table_name), namespace_oid);
h->space = ts_dimension_scan(h->fd.id, h->main_table_relid, h->fd.num_dimensions, ti->mctx);
h->chunk_cache =
ts_subspace_store_init(h->space, ti->mctx, ts_guc_max_cached_chunks_per_hypertable);
h->chunk_sizing_func = get_chunk_sizing_func_oid(&h->fd);
h->max_ignore_invalidation_older_than = -1;
h->data_nodes = ts_hypertable_data_node_scan(h->fd.id, ti->mctx);
return h;
}
static ScanTupleResult
hypertable_tuple_get_relid(TupleInfo *ti, void *data)
{
Oid *relid = data;
FormData_hypertable fd;
Oid schema_oid;
hypertable_formdata_fill(&fd, ti);
schema_oid = get_namespace_oid(NameStr(fd.schema_name), true);
if (OidIsValid(schema_oid))
*relid = get_relname_relid(NameStr(fd.table_name), schema_oid);
return SCAN_DONE;
}
Oid
ts_hypertable_id_to_relid(int32 hypertable_id)
{
Catalog *catalog = ts_catalog_get();
Oid relid = InvalidOid;
ScanKeyData scankey[1];
ScannerCtx scanctx = {
.table = catalog_get_table_id(catalog, HYPERTABLE),
.index = catalog_get_index(catalog, HYPERTABLE, HYPERTABLE_ID_INDEX),
.nkeys = 1,
.scankey = scankey,
.tuple_found = hypertable_tuple_get_relid,
.data = &relid,
.lockmode = AccessShareLock,
.scandirection = ForwardScanDirection,
};
/* Perform an index scan on the hypertable pkey. */
ScanKeyInit(&scankey[0],
Anum_hypertable_pkey_idx_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(hypertable_id));
ts_scanner_scan(&scanctx);
return relid;
}
int32
ts_hypertable_relid_to_id(Oid relid)
{
Cache *hcache;
Hypertable *ht = ts_hypertable_cache_get_cache_and_entry(relid, CACHE_FLAG_MISSING_OK, &hcache);
int result = (ht == NULL) ? -1 : ht->fd.id;
ts_cache_release(hcache);
return result;
}
TS_FUNCTION_INFO_V1(ts_hypertable_get_time_type);
Datum
ts_hypertable_get_time_type(PG_FUNCTION_ARGS)
{
int32 hypertable_id = PG_GETARG_INT32(0);
Cache *hcache = ts_hypertable_cache_pin();
Hypertable *ht = ts_hypertable_cache_get_entry_by_id(hcache, hypertable_id);
Dimension *time_dimension;
Oid time_type;
if (ht == NULL)
PG_RETURN_NULL();
time_dimension = hyperspace_get_open_dimension(ht->space, 0);
if (time_dimension == NULL)
PG_RETURN_NULL();
/* This is deliberately column_type not partitioning_type, as that is how
* the SQL function is defined
*/
time_type = time_dimension->fd.column_type;
ts_cache_release(hcache);
PG_RETURN_OID(time_type);
}
typedef struct ChunkStoreEntry
{
MemoryContext mcxt;
Chunk *chunk;
} ChunkStoreEntry;
static void
chunk_store_entry_free(void *cse)
{
MemoryContextDelete(((ChunkStoreEntry *) cse)->mcxt);
}
static bool
hypertable_is_compressed_or_materialization(Hypertable *ht)
{
ContinuousAggHypertableStatus status = ts_continuous_agg_hypertable_status(ht->fd.id);
return (ht->fd.compressed || status == HypertableIsMaterialization);
}
static ScanFilterResult
hypertable_filter_exclude_compressed_and_materialization(TupleInfo *ti, void *data)
{
Hypertable *ht = ts_hypertable_from_tupleinfo(ti);
return hypertable_is_compressed_or_materialization(ht) ? SCAN_EXCLUDE : SCAN_INCLUDE;
}
static int
hypertable_scan_limit_internal(ScanKeyData *scankey, int num_scankeys, int indexid,
tuple_found_func on_tuple_found, void *scandata, int limit,
LOCKMODE lock, bool tuplock, MemoryContext mctx,
tuple_filter_func filter)
{
Catalog *catalog = ts_catalog_get();
ScannerCtx scanctx = {
.table = catalog_get_table_id(catalog, HYPERTABLE),
.index = catalog_get_index(catalog, HYPERTABLE, indexid),
.nkeys = num_scankeys,
.scankey = scankey,
.data = scandata,
.limit = limit,
.tuple_found = on_tuple_found,
.lockmode = lock,
.filter = filter,
.scandirection = ForwardScanDirection,
.result_mctx = mctx,
};
return ts_scanner_scan(&scanctx);
}
/* Is a user hypertable without compression or continuous aggs */
static bool
hypertable_is_user_table(Hypertable *ht)
{
ContinuousAggHypertableStatus status = ts_continuous_agg_hypertable_status(ht->fd.id);
return !ht->fd.compressed && status != HypertableIsMaterialization;
}
static ScanTupleResult
hypertable_tuple_add_stat(TupleInfo *ti, void *data)
{
HypertablesStat *stat = data;
Hypertable *ht = ts_hypertable_from_tupleinfo(ti);
bool isnull;
Datum datum;
datum = slot_getattr(ti->slot, Anum_hypertable_replication_factor, &isnull);
if (!isnull)
{
int16 replication_factor = DatumGetInt16(datum);
switch (replication_factor)
{
case HYPERTABLE_DISTRIBUTED_MEMBER:
stat->num_hypertables_distributed_members++;
break;
case HYPERTABLE_REGULAR:
/* This should not be possible */
Assert(0);
break;
default:
Assert(replication_factor >= 1);
Assert(!ht->fd.compressed);
stat->num_hypertables_distributed++;
if (replication_factor > 1)
stat->num_hypertables_distributed_and_replicated++;
break;
}
}
else
{
/* Number of user-created hypertables (doesn't count internal hypertables
* for compression or continuous aggs) */
if (hypertable_is_user_table(ht))
stat->num_hypertables_user++;
}
/* Number of hypertables with compression enabled */
if (TS_HYPERTABLE_HAS_COMPRESSION(ht))
stat->num_hypertables_compressed++;
return SCAN_CONTINUE;
}
void
ts_number_of_hypertables(HypertablesStat *stat)
{
stat->num_hypertables_total = hypertable_scan_limit_internal(NULL,
0,
HYPERTABLE_ID_INDEX,
hypertable_tuple_add_stat,
stat,
-1,
AccessShareLock,
false,
CurrentMemoryContext,
NULL);
}
static ScanTupleResult
hypertable_tuple_append(TupleInfo *ti, void *data)
{
List **hypertables = data;
*hypertables = lappend(*hypertables, ts_hypertable_from_tupleinfo(ti));
return SCAN_CONTINUE;
}
List *
ts_hypertable_get_all(void)
{
List *result = NIL;
hypertable_scan_limit_internal(NULL,
0,
InvalidOid,
hypertable_tuple_append,
&result,
-1,
RowExclusiveLock,
false,
CurrentMemoryContext,
hypertable_filter_exclude_compressed_and_materialization);
return result;
}
/* Lazy-load the maximum ignore_invalidation_older_than setting from all associated continuous aggs
*/
TSDLLEXPORT int64
ts_hypertable_get_max_ignore_invalidation_older_than(Hypertable *ht)
{
if (ht->max_ignore_invalidation_older_than < 0)
ht->max_ignore_invalidation_older_than =
ts_continuous_aggs_max_ignore_invalidation_older_than(ht->fd.id, NULL);
Assert(ht->max_ignore_invalidation_older_than >= 0);
return ht->max_ignore_invalidation_older_than;
}
static ScanTupleResult
hypertable_tuple_update(TupleInfo *ti, void *data)
{
Hypertable *ht = data;
HeapTuple new_tuple;
CatalogSecurityContext sec_ctx;
if (OidIsValid(ht->chunk_sizing_func))
{
Dimension *dim = ts_hyperspace_get_dimension(ht->space, DIMENSION_TYPE_OPEN, 0);
ChunkSizingInfo info = {
.table_relid = ht->main_table_relid,
.colname = dim == NULL ? NULL : NameStr(dim->fd.column_name),
.func = ht->chunk_sizing_func,
};
ts_chunk_adaptive_sizing_info_validate(&info);
namestrcpy(&ht->fd.chunk_sizing_func_schema, NameStr(info.func_schema));
namestrcpy(&ht->fd.chunk_sizing_func_name, NameStr(info.func_name));
}
else
{
elog(ERROR, "hypertable_tuple_update chunk_sizing_function cannot be NULL");
}
new_tuple = hypertable_formdata_make_tuple(&ht->fd, ts_scanner_get_tupledesc(ti));
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);
return SCAN_DONE;
}
int
ts_hypertable_update(Hypertable *ht)
{
ScanKeyData scankey[1];
ScanKeyInit(&scankey[0],
Anum_hypertable_pkey_idx_id,
BTEqualStrategyNumber,
F_INT4EQ,
Int32GetDatum(ht->fd.id));
return hypertable_scan_limit_internal(scankey,
1,
HYPERTABLE_ID_INDEX,
hypertable_tuple_update,
ht,
1,
RowExclusiveLock,
false,
CurrentMemoryContext,
NULL);
}
int
ts_hypertable_scan_with_memory_context(const char *schema, const char *table,
tuple_found_func tuple_found, void *data, LOCKMODE lockmode,
bool tuplock, MemoryContext mctx)
{
ScanKeyData scankey[2];
NameData schema_name, table_name;
namestrcpy(&schema_name, schema);
namestrcpy(&table_name, table);
/* Perform an index scan on schema and table. */
ScanKeyInit(&scankey[0],
Anum_hypertable_name_idx_table,
BTEqualStrategyNumber,
F_NAMEEQ,
NameGetDatum(&table_name));
ScanKeyInit(&scankey[1],
Anum_hypertable_name_idx_schema,
BTEqualStrategyNumber,
F_NAMEEQ,
NameGetDatum(&schema_name));
return hypertable_scan_limit_internal(scankey,
2,
HYPERTABLE_NAME_INDEX,
tuple_found,
data,
1,
lockmode,
tuplock,
mctx,
NULL);
}
TSDLLEXPORT ObjectAddress
ts_hypertable_create_trigger(Hypertable *ht, CreateTrigStmt *stmt, const char *query)
{
ObjectAddress root_trigger_addr;
List *chunks;
ListCell *lc;
int sec_ctx;
Oid saved_uid;
Oid owner;
Assert(ht != NULL);
if (stmt->transitionRels != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("hypertables do not support transition tables in triggers")));
/* create the trigger on the root table */
/* ACL permissions checks happen within this call */
root_trigger_addr = CreateTrigger(stmt,
query,
InvalidOid,
InvalidOid,
InvalidOid,
InvalidOid,
InvalidOid,
InvalidOid,
NULL,
false,
false);
/* and forward it to the chunks */
CommandCounterIncrement();
if (!stmt->row)
return root_trigger_addr;
/* switch to the hypertable owner's role -- note that this logic must be the same as
* `ts_trigger_create_all_on_chunk` */
owner = ts_rel_get_owner(ht->main_table_relid);
GetUserIdAndSecContext(&saved_uid, &sec_ctx);
if (saved_uid != owner)
SetUserIdAndSecContext(owner, sec_ctx | SECURITY_LOCAL_USERID_CHANGE);
chunks = find_inheritance_children(ht->main_table_relid, NoLock);
foreach (lc, chunks)
{
Oid chunk_oid = lfirst_oid(lc);
char *relschema = get_namespace_name(get_rel_namespace(chunk_oid));
char *relname = get_rel_name(chunk_oid);
char relkind = get_rel_relkind(chunk_oid);
Assert(relkind == RELKIND_RELATION || relkind == RELKIND_FOREIGN_TABLE);
/* Only create triggers on standard relations and not on, e.g., foreign
* table chunks */
if (relkind == RELKIND_RELATION)
ts_trigger_create_on_chunk(root_trigger_addr.objectId, relschema, relname);
}
if (saved_uid != owner)
SetUserIdAndSecContext(saved_uid, sec_ctx);
return root_trigger_addr;
}
/* based on RemoveObjects */
TSDLLEXPORT void
ts_hypertable_drop_trigger(Hypertable *ht, const char *trigger_name)
{
List *chunks = find_inheritance_children(ht->main_table_relid, NoLock);
ListCell *lc;
if (OidIsValid(ht->main_table_relid))
{
ObjectAddress objaddr = {
.classId = TriggerRelationId,
.objectId = get_trigger_oid(ht->main_table_relid, trigger_name, true),
};
if (OidIsValid(objaddr.objectId))
performDeletion(&objaddr, DROP_RESTRICT, 0);
}
foreach (lc, chunks)
{
Oid chunk_oid = lfirst_oid(lc);
ObjectAddress objaddr = {
.classId = TriggerRelationId,
.objectId = get_trigger_oid(chunk_oid, trigger_name, true),
};
if (OidIsValid(objaddr.objectId))
performDeletion(&objaddr, DROP_RESTRICT, 0);
}
}
static ScanTupleResult
hypertable_tuple_delete(TupleInfo *ti, void *data)
{
CatalogSecurityContext sec_ctx;
bool isnull;
bool compressed_hypertable_id_isnull;
int hypertable_id = DatumGetInt32(slot_getattr(ti->slot, Anum_hypertable_id, &isnull));
int compressed_hypertable_id =
DatumGetInt32(slot_getattr(ti->slot,
Anum_hypertable_compressed_hypertable_id,
&compressed_hypertable_id_isnull));
ts_tablespace_delete(hypertable_id, NULL);
ts_chunk_delete_by_hypertable_id(hypertable_id);
ts_dimension_delete_by_hypertable_id(hypertable_id, true);
ts_hypertable_data_node_delete_by_hypertable_id(hypertable_id);
/* Also remove any policy argument / job that uses this hypertable */
ts_bgw_policy_delete_by_hypertable_id(hypertable_id);
/* Remove any dependent continuous aggs */
ts_continuous_agg_drop_hypertable_callback(hypertable_id);
/* remove any associated compression definitions */
ts_hypertable_compression_delete_by_hypertable_id(hypertable_id);
if (!compressed_hypertable_id_isnull)
{
Hypertable *compressed_hypertable = ts_hypertable_get_by_id(compressed_hypertable_id);
/* The hypertable may have already been deleted by a cascade */
if (compressed_hypertable != NULL)
ts_hypertable_drop(compressed_hypertable, DROP_RESTRICT);
}
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_hypertable_delete_by_name(const char *schema_name, const char *table_name)
{
ScanKeyData scankey[2];
ScanKeyInit(&scankey[0],
Anum_hypertable_name_idx_table,
BTEqualStrategyNumber,
F_NAMEEQ,
DirectFunctionCall1(namein, CStringGetDatum(table_name)));
ScanKeyInit(&scankey[1],
Anum_hypertable_name_idx_schema,
BTEqualStrategyNumber,
F_NAMEEQ,
DirectFunctionCall1(namein, CStringGetDatum(schema_name)));
return hypertable_scan_limit_internal(scankey,
2,
HYPERTABLE_NAME_INDEX,
hypertable_tuple_delete,
NULL,
0,
RowExclusiveLock,
false,
CurrentMemoryContext,
NULL);
}
void
ts_hypertable_drop(Hypertable *hypertable, DropBehavior behavior)
{
ObjectAddress hypertable_addr = (ObjectAddress){
.classId = RelationRelationId,
.objectId = hypertable->main_table_relid,
};
/* Drop the postgres table */
performDeletion(&hypertable_addr, behavior, 0);
/* Clean up catalog */
ts_hypertable_delete_by_name(hypertable->fd.schema_name.data, hypertable->fd.table_name.data);
}
static ScanTupleResult
reset_associated_tuple_found(TupleInfo *ti, void *data)
{
HeapTuple new_tuple;
FormData_hypertable fd;
CatalogSecurityContext sec_ctx;
hypertable_formdata_fill(&fd, ti);
namestrcpy(&fd.associated_schema_name, INTERNAL_SCHEMA_NAME);
new_tuple = hypertable_formdata_make_tuple(&fd, ts_scanner_get_tupledesc(ti));
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);
return SCAN_CONTINUE;
}
/*
* Reset the matching associated schema to the internal schema.
*/
int
ts_hypertable_reset_associated_schema_name(const char *associated_schema)
{
ScanKeyData scankey[1];
ScanKeyInit(&scankey[0],
Anum_hypertable_associated_schema_name,
BTEqualStrategyNumber,
F_NAMEEQ,
DirectFunctionCall1(namein, CStringGetDatum(associated_schema)));
return hypertable_scan_limit_internal(scankey,
1,
INVALID_INDEXID,
reset_associated_tuple_found,
NULL,
0,
RowExclusiveLock,
false,
CurrentMemoryContext,
NULL);
}
static ScanTupleResult
tuple_found_lock(TupleInfo *ti, void *data)
{
TM_Result *result = data;
*result = ti->lockresult;
return SCAN_DONE;
}
TM_Result
ts_hypertable_lock_tuple(Oid table_relid)
{
TM_Result result;
int num_found;
num_found = hypertable_scan(get_namespace_name(get_rel_namespace(table_relid)),
get_rel_name(table_relid),
tuple_found_lock,
&result,
RowExclusiveLock,
true);
if (num_found != 1)
ereport(ERROR,
(errcode(ERRCODE_TS_HYPERTABLE_NOT_EXIST),
errmsg("table \"%s\" is not a hypertable", get_rel_name(table_relid))));
return result;
}
bool
ts_hypertable_lock_tuple_simple(Oid table_relid)
{
TM_Result result = ts_hypertable_lock_tuple(table_relid);
switch (result)
{
case TM_SelfModified:
/*
* Updated by the current transaction already. We equate this with
* a successful lock since the tuple should be locked if updated
* by us.
*/
return true;
case TM_Ok:
/* successfully locked */
return true;
#if PG12_GE
case TM_Deleted:
#endif
case TM_Updated:
ereport(ERROR,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("hypertable \"%s\" has already been updated by another transaction",
get_rel_name(table_relid)),
errhint("Retry the operation again.")));
pg_unreachable();
return false;
case TM_BeingModified:
ereport(ERROR,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("hypertable \"%s\" is being updated by another transaction",
get_rel_name(table_relid)),
errhint("Retry the operation again.")));
pg_unreachable();
return false;
case TM_WouldBlock:
/* Locking would block. Let caller decide what to do */
return false;
case TM_Invisible:
elog(ERROR, "attempted to lock invisible tuple");
pg_unreachable();
return false;
default:
elog(ERROR, "unexpected tuple lock status");
pg_unreachable();
return false;
}
}
int
ts_hypertable_set_name(Hypertable *ht, const char *newname)
{
namestrcpy(&ht->fd.table_name, newname);
return ts_hypertable_update(ht);
}
int
ts_hypertable_set_schema(Hypertable *ht, const char *newname)
{
namestrcpy(&ht->fd.schema_name, newname);
return ts_hypertable_update(ht);
}
int
ts_hypertable_set_num_dimensions(Hypertable *ht, int16 num_dimensions)
{
Assert(num_dimensions > 0);
ht->fd.num_dimensions = num_dimensions;
return ts_hypertable_update(ht);
}
#define DEFAULT_ASSOCIATED_TABLE_PREFIX_FORMAT "_hyper_%d"
#define DEFAULT_ASSOCIATED_DISTRIBUTED_TABLE_PREFIX_FORMAT "_dist_hyper_%d"
static const int MAXIMUM_PREFIX_LENGTH = NAMEDATALEN - 16;
static void
hypertable_insert_relation(Relation rel, FormData_hypertable *fd)
{
HeapTuple new_tuple;
CatalogSecurityContext sec_ctx;
new_tuple = hypertable_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);
}
static void
hypertable_insert(int32 hypertable_id, Name schema_name, Name table_name,
Name associated_schema_name, Name associated_table_prefix,
Name chunk_sizing_func_schema, Name chunk_sizing_func_name,
int64 chunk_target_size, int16 num_dimensions, bool compressed,
int16 replication_factor)
{
Catalog *catalog = ts_catalog_get();
Relation rel;
FormData_hypertable fd;
fd.id = hypertable_id;
if (fd.id == INVALID_HYPERTABLE_ID)
{
CatalogSecurityContext sec_ctx;
ts_catalog_database_info_become_owner(ts_catalog_database_info_get(), &sec_ctx);
fd.id = ts_catalog_table_next_seq_id(ts_catalog_get(), HYPERTABLE);
ts_catalog_restore_user(&sec_ctx);
}
namestrcpy(&fd.schema_name, NameStr(*schema_name));
namestrcpy(&fd.table_name, NameStr(*table_name));
namestrcpy(&fd.associated_schema_name, NameStr(*associated_schema_name));
if (NULL == associated_table_prefix)
{
NameData default_associated_table_prefix;
memset(NameStr(default_associated_table_prefix), '\0', NAMEDATALEN);
Assert(replication_factor >= 0);
if (replication_factor == 0)
snprintf(NameStr(default_associated_table_prefix),
NAMEDATALEN,
DEFAULT_ASSOCIATED_TABLE_PREFIX_FORMAT,
fd.id);
else
snprintf(NameStr(default_associated_table_prefix),
NAMEDATALEN,
DEFAULT_ASSOCIATED_DISTRIBUTED_TABLE_PREFIX_FORMAT,
fd.id);
namestrcpy(&fd.associated_table_prefix, NameStr(default_associated_table_prefix));
}
else
{
namestrcpy(&fd.associated_table_prefix, NameStr(*associated_table_prefix));
}
if (strnlen(NameStr(fd.associated_table_prefix), NAMEDATALEN) > MAXIMUM_PREFIX_LENGTH)
elog(ERROR, "associated_table_prefix too long");
fd.num_dimensions = num_dimensions;
namestrcpy(&fd.chunk_sizing_func_schema, NameStr(*chunk_sizing_func_schema));
namestrcpy(&fd.chunk_sizing_func_name, NameStr(*chunk_sizing_func_name));
fd.chunk_target_size = chunk_target_size;
if (fd.chunk_target_size < 0)
fd.chunk_target_size = 0;
fd.compressed = compressed;