forked from timescale/timescaledb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk_api.c
1780 lines (1501 loc) · 52.8 KB
/
chunk_api.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 Timescale License.
* Please see the included NOTICE for copyright information and
* LICENSE-TIMESCALE for a copy of the license.
*/
#include <postgres.h>
#include <access/htup_details.h>
#include <access/htup.h>
#include <access/multixact.h>
#include <access/visibilitymap.h>
#include <access/xact.h>
#include <catalog/indexing.h>
#include <catalog/pg_class.h>
#include <catalog/pg_inherits.h>
#include <catalog/pg_namespace.h>
#include <catalog/pg_operator.h>
#include <catalog/pg_type.h>
#include <commands/vacuum.h>
#include <fmgr.h>
#include <funcapi.h>
#include <miscadmin.h>
#include <utils/array.h>
#include <utils/builtins.h>
#include <utils/jsonb.h>
#include <utils/lsyscache.h>
#include <utils/syscache.h>
#include "compat/compat.h"
#include "chunk.h"
#include "chunk_api.h"
#include "data_node.h"
#include "errors.h"
#include "error_utils.h"
#include "hypercube.h"
#include "hypertable_cache.h"
#include "utils.h"
#include "remote/async.h"
#include "remote/dist_txn.h"
#include "remote/stmt_params.h"
#include "remote/dist_commands.h"
#include "remote/tuplefactory.h"
#include "ts_catalog/catalog.h"
#include "ts_catalog/chunk_data_node.h"
/*
* These values come from the pg_type table.
*/
#define FLOAT4_TYPELEN sizeof(float4)
#define FLOAT4_TYPEBYVAL true
#define FLOAT4_TYPEALIGN 'i'
#define CSTRING_TYPELEN (-2)
#define CSTRING_TYPEBYVAL false
#define CSTRING_TYPEALIGN 'c'
#define INT4_TYPELEN sizeof(int32)
#define INT4_TYPEBYVAL true
#define INT4_TYPEALIGN 'i'
#define OID_TYPELEN sizeof(Oid)
#define OID_TYPEBYVAL true
#define OID_TYPEALIGN 'i'
#define CSTRING_ARY_TYPELEN (-1)
/*
* Convert a hypercube to a JSONB value.
*
* For instance, a two-dimensional hypercube, with dimensions "time" and
* "device", might look as follows:
*
* {"time": [1514419200000000, 1515024000000000],
* "device": [-9223372036854775808, 1073741823]}
*/
static JsonbValue *
hypercube_to_jsonb_value(Hypercube *hc, Hyperspace *hs, JsonbParseState **ps)
{
int i;
Assert(hs->num_dimensions == hc->num_slices);
pushJsonbValue(ps, WJB_BEGIN_OBJECT, NULL);
for (i = 0; i < hc->num_slices; i++)
{
JsonbValue k, v;
char *dim_name = NameStr(hs->dimensions[i].fd.column_name);
Datum range_start =
DirectFunctionCall1(int8_numeric, Int64GetDatum(hc->slices[i]->fd.range_start));
Datum range_end =
DirectFunctionCall1(int8_numeric, Int64GetDatum(hc->slices[i]->fd.range_end));
Assert(hs->dimensions[i].fd.id == hc->slices[i]->fd.dimension_id);
k.type = jbvString;
k.val.string.len = strlen(dim_name);
k.val.string.val = dim_name;
pushJsonbValue(ps, WJB_KEY, &k);
pushJsonbValue(ps, WJB_BEGIN_ARRAY, NULL);
v.type = jbvNumeric;
v.val.numeric = DatumGetNumeric(range_start);
pushJsonbValue(ps, WJB_ELEM, &v);
v.val.numeric = DatumGetNumeric(range_end);
pushJsonbValue(ps, WJB_ELEM, &v);
pushJsonbValue(ps, WJB_END_ARRAY, NULL);
}
return pushJsonbValue(ps, WJB_END_OBJECT, NULL);
}
/*
* Create a hypercube from a JSONB object.
*
* Takes a JSONB object with a hypercube's dimensional constraints and outputs
* a Hypercube. The JSONB is the same format as output by
* hypercube_to_jsonb_value() above, i.e.:
*
* {"time": [1514419200000000, 1515024000000000],
* "device": [-9223372036854775808, 1073741823]}
*/
static Hypercube *
hypercube_from_jsonb(Jsonb *json, const Hyperspace *hs, const char **parse_error)
{
JsonbIterator *it;
JsonbIteratorToken type;
JsonbValue v;
Hypercube *hc = NULL;
const char *err = NULL;
it = JsonbIteratorInit(&json->root);
type = JsonbIteratorNext(&it, &v, false);
if (type != WJB_BEGIN_OBJECT)
{
err = "invalid JSON format";
goto out_err;
}
if (v.val.object.nPairs != hs->num_dimensions)
{
err = "invalid number of hypercube dimensions";
goto out_err;
}
hc = ts_hypercube_alloc(hs->num_dimensions);
while ((type = JsonbIteratorNext(&it, &v, false)))
{
int i;
const Dimension *dim;
int64 range[2];
const char *name;
if (type == WJB_END_OBJECT)
break;
if (type != WJB_KEY)
{
err = "invalid JSON format";
goto out_err;
}
name = pnstrdup(v.val.string.val, v.val.string.len);
dim = ts_hyperspace_get_dimension_by_name(hs, DIMENSION_TYPE_ANY, name);
if (NULL == dim)
{
err = psprintf("dimension \"%s\" does not exist in hypertable", name);
goto out_err;
}
type = JsonbIteratorNext(&it, &v, false);
if (type != WJB_BEGIN_ARRAY)
{
err = "invalid JSON format";
goto out_err;
}
if (v.val.array.nElems != 2)
{
err = psprintf("unexpected number of dimensional bounds for dimension \"%s\"", name);
goto out_err;
}
for (i = 0; i < 2; i++)
{
type = JsonbIteratorNext(&it, &v, false);
if (type != WJB_ELEM)
{
err = "invalid JSON format";
goto out_err;
}
if (v.type != jbvNumeric)
{
err = psprintf("constraint for dimension \"%s\" is not numeric", name);
goto out_err;
}
range[i] =
DatumGetInt64(DirectFunctionCall1(numeric_int8, NumericGetDatum(v.val.numeric)));
}
type = JsonbIteratorNext(&it, &v, false);
if (type != WJB_END_ARRAY)
{
err = "invalid JSON format";
goto out_err;
}
ts_hypercube_add_slice_from_range(hc, dim->fd.id, range[0], range[1]);
}
out_err:
if (NULL != parse_error)
*parse_error = err;
if (NULL != err)
return NULL;
return hc;
}
enum Anum_create_chunk
{
Anum_create_chunk_id = 1,
Anum_create_chunk_hypertable_id,
Anum_create_chunk_schema_name,
Anum_create_chunk_table_name,
Anum_create_chunk_relkind,
Anum_create_chunk_slices,
Anum_create_chunk_created,
_Anum_create_chunk_max,
};
#define Natts_create_chunk (_Anum_create_chunk_max - 1)
static HeapTuple
chunk_form_tuple(Chunk *chunk, Hypertable *ht, TupleDesc tupdesc, bool created)
{
Datum values[Natts_create_chunk];
bool nulls[Natts_create_chunk] = { false };
JsonbParseState *ps = NULL;
JsonbValue *jv = hypercube_to_jsonb_value(chunk->cube, ht->space, &ps);
if (NULL == jv)
return NULL;
values[AttrNumberGetAttrOffset(Anum_create_chunk_id)] = Int32GetDatum(chunk->fd.id);
values[AttrNumberGetAttrOffset(Anum_create_chunk_hypertable_id)] =
Int32GetDatum(chunk->fd.hypertable_id);
values[AttrNumberGetAttrOffset(Anum_create_chunk_schema_name)] =
NameGetDatum(&chunk->fd.schema_name);
values[AttrNumberGetAttrOffset(Anum_create_chunk_table_name)] =
NameGetDatum(&chunk->fd.table_name);
values[AttrNumberGetAttrOffset(Anum_create_chunk_relkind)] = CharGetDatum(chunk->relkind);
values[AttrNumberGetAttrOffset(Anum_create_chunk_slices)] =
JsonbPGetDatum(JsonbValueToJsonb(jv));
values[AttrNumberGetAttrOffset(Anum_create_chunk_created)] = BoolGetDatum(created);
return heap_form_tuple(tupdesc, values, nulls);
}
Datum
chunk_show(PG_FUNCTION_ARGS)
{
Oid chunk_relid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
Chunk *chunk = ts_chunk_get_by_relid(chunk_relid, true);
Cache *hcache = ts_hypertable_cache_pin();
Hypertable *ht =
ts_hypertable_cache_get_entry(hcache, chunk->hypertable_relid, CACHE_FLAG_NONE);
TupleDesc tupdesc;
HeapTuple tuple;
Assert(NULL != chunk);
Assert(NULL != ht);
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
/*
* We use the create_chunk tuple for show_chunk, because they only differ
* in the created column at the end. That column will not be included here
* since it is not part of the tuple descriptor.
*/
tuple = chunk_form_tuple(chunk, ht, tupdesc, false);
ts_cache_release(hcache);
if (NULL == tuple)
ereport(ERROR,
(errcode(ERRCODE_TS_INTERNAL_ERROR), errmsg("could not create tuple from chunk")));
PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
static void
check_privileges_for_creating_chunk(Oid hyper_relid)
{
AclResult acl_result;
acl_result = pg_class_aclcheck(hyper_relid, GetUserId(), ACL_INSERT);
if (acl_result != ACLCHECK_OK)
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("permission denied for table \"%s\"", get_rel_name(hyper_relid)),
errdetail("Insert privileges required on \"%s\" to create chunks.",
get_rel_name(hyper_relid))));
}
static Hypercube *
get_hypercube_from_slices(Jsonb *slices, const Hypertable *ht)
{
Hypercube *hc;
const char *parse_err;
hc = hypercube_from_jsonb(slices, ht->space, &parse_err);
if (hc == NULL)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid hypercube for hypertable \"%s\"",
get_rel_name(ht->main_table_relid)),
errdetail("%s", parse_err)));
return hc;
}
/*
* Create a chunk and its metadata.
*
* This function will create a chunk, either from an existing table or by
* creating a new table. If chunk_table_relid is InvalidOid, the chunk table
* will be created, otherwise the table referenced by the relid will be
* used. The chunk will be associated with the hypertable given by
* hypertable_relid.
*/
Datum
chunk_create(PG_FUNCTION_ARGS)
{
Oid hypertable_relid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
Jsonb *slices = PG_ARGISNULL(1) ? NULL : PG_GETARG_JSONB_P(1);
const char *schema_name = PG_ARGISNULL(2) ? NULL : PG_GETARG_CSTRING(2);
const char *table_name = PG_ARGISNULL(3) ? NULL : PG_GETARG_CSTRING(3);
Oid chunk_table_relid = PG_ARGISNULL(4) ? InvalidOid : PG_GETARG_OID(4);
Cache *hcache = ts_hypertable_cache_pin();
Hypertable *ht = ts_hypertable_cache_get_entry(hcache, hypertable_relid, CACHE_FLAG_NONE);
Hypercube *hc;
Chunk *chunk;
TupleDesc tupdesc;
HeapTuple tuple;
bool created;
Assert(NULL != ht);
Assert(OidIsValid(ht->main_table_relid));
check_privileges_for_creating_chunk(hypertable_relid);
if (NULL == slices)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid slices")));
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
hc = get_hypercube_from_slices(slices, ht);
Assert(NULL != hc);
chunk = ts_chunk_find_or_create_without_cuts(ht,
hc,
schema_name,
table_name,
chunk_table_relid,
&created);
Assert(NULL != chunk);
tuple = chunk_form_tuple(chunk, ht, tupdesc, created);
ts_cache_release(hcache);
if (NULL == tuple)
ereport(ERROR,
(errcode(ERRCODE_TS_INTERNAL_ERROR), errmsg("could not create tuple from chunk")));
PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
}
#define CREATE_CHUNK_FUNCTION_NAME "create_chunk"
#define CREATE_CHUNK_NUM_ARGS 5
#define CHUNK_CREATE_STMT \
"SELECT * FROM " INTERNAL_SCHEMA_NAME "." CREATE_CHUNK_FUNCTION_NAME "($1, $2, $3, $4, $5)"
#define ESTIMATE_JSON_STR_SIZE(num_dims) (60 * (num_dims))
static Oid create_chunk_argtypes[CREATE_CHUNK_NUM_ARGS] = {
REGCLASSOID, JSONBOID, NAMEOID, NAMEOID, REGCLASSOID
};
/*
* Fill in / get the TupleDesc for the result type of the create_chunk()
* function.
*/
static void
get_create_chunk_result_type(TupleDesc *tupdesc)
{
Oid funcoid = ts_get_function_oid(CREATE_CHUNK_FUNCTION_NAME,
INTERNAL_SCHEMA_NAME,
CREATE_CHUNK_NUM_ARGS,
create_chunk_argtypes);
if (get_func_result_type(funcoid, NULL, tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
}
static void
get_result_datums(Datum *values, bool *nulls, unsigned int numvals, AttInMetadata *attinmeta,
PGresult *res)
{
unsigned int i;
memset(nulls, 0, sizeof(bool) * numvals);
for (i = 0; i < numvals; i++)
{
if (PQgetisnull(res, 0, i))
nulls[i] = true;
else
values[i] = InputFunctionCall(&attinmeta->attinfuncs[i],
PQgetvalue(res, 0, i),
attinmeta->attioparams[i],
attinmeta->atttypmods[i]);
}
}
static const char *
chunk_api_dimension_slices_json(const Chunk *chunk, const Hypertable *ht)
{
JsonbParseState *ps = NULL;
JsonbValue *jv = hypercube_to_jsonb_value(chunk->cube, ht->space, &ps);
Jsonb *hcjson = JsonbValueToJsonb(jv);
return JsonbToCString(NULL, &hcjson->root, ESTIMATE_JSON_STR_SIZE(ht->space->num_dimensions));
}
/*
* Create a replica of a chunk on all its assigned or specified list of data nodes.
*
* If "data_nodes" list is explicitly specified use that instead of the list of
* data nodes from the chunk.
*/
void
chunk_api_create_on_data_nodes(const Chunk *chunk, const Hypertable *ht,
const char *remote_chunk_name, List *data_nodes)
{
AsyncRequestSet *reqset = async_request_set_create();
const char *params[CREATE_CHUNK_NUM_ARGS] = {
quote_qualified_identifier(NameStr(ht->fd.schema_name), NameStr(ht->fd.table_name)),
chunk_api_dimension_slices_json(chunk, ht),
NameStr(chunk->fd.schema_name),
NameStr(chunk->fd.table_name),
remote_chunk_name ? remote_chunk_name : NULL,
};
AsyncResponseResult *res;
ListCell *lc;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
/*
* In case of "unavailable" datanodes, the chunk->data_nodes list is already pruned
* and doesn't contain "unavailable" datanodes. So this chunk creation will never
* happen on such "unavailable" datanodes. By the same logic, metadata update on the
* AN for the chunk->datanode mappings will only happen for the listed "live" DNs
* and not for the "unavailable" ones
*/
List *target_data_nodes = data_nodes ? data_nodes : chunk->data_nodes;
get_create_chunk_result_type(&tupdesc);
attinmeta = TupleDescGetAttInMetadata(tupdesc);
foreach (lc, target_data_nodes)
{
ChunkDataNode *cdn = lfirst(lc);
TSConnectionId id = remote_connection_id(cdn->foreign_server_oid, GetUserId());
TSConnection *conn = remote_dist_txn_get_connection(id, REMOTE_TXN_NO_PREP_STMT);
AsyncRequest *req;
req = async_request_send_with_params(conn,
CHUNK_CREATE_STMT,
stmt_params_create_from_values(params,
CREATE_CHUNK_NUM_ARGS),
FORMAT_TEXT);
async_request_attach_user_data(req, cdn);
async_request_set_add(reqset, req);
}
while ((res = async_request_set_wait_ok_result(reqset)) != NULL)
{
PGresult *pgres = async_response_result_get_pg_result(res);
ChunkDataNode *cdn = async_response_result_get_user_data(res);
Datum values[Natts_create_chunk];
bool nulls[Natts_create_chunk];
const char *schema_name, *table_name;
bool created;
Assert(Natts_create_chunk == tupdesc->natts);
get_result_datums(values, nulls, tupdesc->natts, attinmeta, pgres);
created = DatumGetBool(values[AttrNumberGetAttrOffset(Anum_create_chunk_created)]);
/*
* Sanity check the result. Use error rather than an assert since this
* is the result of a remote call to a data node that could potentially
* run a different version of the remote function than we'd expect.
*/
if (!created)
elog(ERROR, "chunk creation failed on data node \"%s\"", NameStr(cdn->fd.node_name));
if (nulls[AttrNumberGetAttrOffset(Anum_create_chunk_id)] ||
nulls[AttrNumberGetAttrOffset(Anum_create_chunk_schema_name)] ||
nulls[AttrNumberGetAttrOffset(Anum_create_chunk_table_name)])
elog(ERROR, "unexpected chunk creation result on data node");
schema_name =
DatumGetCString(values[AttrNumberGetAttrOffset(Anum_create_chunk_schema_name)]);
table_name = DatumGetCString(values[AttrNumberGetAttrOffset(Anum_create_chunk_table_name)]);
if (namestrcmp((Name) &chunk->fd.schema_name, schema_name) != 0 ||
namestrcmp((Name) &chunk->fd.table_name, table_name) != 0)
elog(ERROR, "remote chunk has mismatching schema or table name");
cdn->fd.node_chunk_id =
DatumGetInt32(values[AttrNumberGetAttrOffset(Anum_create_chunk_id)]);
}
}
enum Anum_chunk_relstats
{
Anum_chunk_relstats_chunk_id = 1,
Anum_chunk_relstats_hypertable_id,
Anum_chunk_relstats_num_pages,
Anum_chunk_relstats_num_tuples,
Anum_chunk_relstats_num_allvisible,
_Anum_chunk_relstats_max,
};
/*
* Construct a tuple for the get_chunk_relstats SQL function.
*/
static HeapTuple
chunk_get_single_stats_tuple(Chunk *chunk, TupleDesc tupdesc)
{
HeapTuple ctup;
Form_pg_class pgcform;
Datum values[_Anum_chunk_relstats_max];
bool nulls[_Anum_chunk_relstats_max] = { false };
Datum reltuples;
ctup = SearchSysCache1(RELOID, ObjectIdGetDatum(chunk->table_id));
if (!HeapTupleIsValid(ctup))
elog(ERROR,
"pg_class entry for chunk \"%s.%s\" not found",
NameStr(chunk->fd.schema_name),
NameStr(chunk->fd.table_name));
pgcform = (Form_pg_class) GETSTRUCT(ctup);
values[AttrNumberGetAttrOffset(Anum_chunk_relstats_chunk_id)] = Int32GetDatum(chunk->fd.id);
values[AttrNumberGetAttrOffset(Anum_chunk_relstats_hypertable_id)] =
Int32GetDatum(chunk->fd.hypertable_id);
values[AttrNumberGetAttrOffset(Anum_chunk_relstats_num_pages)] =
Int32GetDatum(pgcform->relpages);
reltuples = Float4GetDatum(pgcform->reltuples > 0 ? pgcform->reltuples : 0);
values[AttrNumberGetAttrOffset(Anum_chunk_relstats_num_tuples)] = reltuples;
values[AttrNumberGetAttrOffset(Anum_chunk_relstats_num_allvisible)] =
Int32GetDatum(pgcform->relallvisible);
ReleaseSysCache(ctup);
return heap_form_tuple(tupdesc, values, nulls);
}
enum Anum_chunk_colstats
{
Anum_chunk_colstats_chunk_id = 1,
Anum_chunk_colstats_hypertable_id,
Anum_chunk_colstats_column_id,
Anum_chunk_colstats_nullfrac,
Anum_chunk_colstats_width,
Anum_chunk_colstats_distinct,
Anum_chunk_colstats_slot_kinds,
Anum_chunk_colstats_slot_op_strings,
Anum_chunk_colstats_slot_collations,
Anum_chunk_colstats_slot1_numbers,
Anum_chunk_colstats_slot2_numbers,
Anum_chunk_colstats_slot3_numbers,
Anum_chunk_colstats_slot4_numbers,
Anum_chunk_colstats_slot5_numbers,
Anum_chunk_colstats_slot_valtype_strings,
Anum_chunk_colstats_slot1_values,
Anum_chunk_colstats_slot2_values,
Anum_chunk_colstats_slot3_values,
Anum_chunk_colstats_slot4_values,
Anum_chunk_colstats_slot5_values,
_Anum_chunk_colstats_max,
};
/*
* It's not safe to send OIDs for operations or types between postgres instances for user defined
* types. Instead convert the operation OID to strings and then look up the local OID for the
* corresponding names on the other node. A single op OID will need 6 strings {op_name,
* op_namespace, larg_name, larg_namespace, rarg_name, rarg_namespace}
*/
#define STRINGS_PER_TYPE_OID 2
#define STRINGS_PER_OP_OID 6
enum StringArrayTypeIdx
{
ENCODED_TYPE_NAME = 0,
ENCODED_TYPE_NAMESPACE
};
enum OpArrayTypeIdx
{
ENCODED_OP_NAME = 0,
ENCODED_OP_NAMESPACE,
ENCODED_OP_LARG_NAME,
ENCODED_OP_LARG_NAMESPACE,
ENCODED_OP_RARG_NAME,
ENCODED_OP_RARG_NAMESPACE,
};
#define LargSubarrayForOpArray(op_string_array) (&(op_string_array)[ENCODED_OP_LARG_NAME])
#define RargSubarrayForOpArray(op_string_array) (&(op_string_array)[ENCODED_OP_RARG_NAME])
static void
convert_type_oid_to_strings(Oid type_id, Datum *result_strings)
{
Form_pg_type type;
Form_pg_namespace namespace;
HeapTuple namespace_tuple;
HeapTuple type_tuple;
type_tuple = SearchSysCache1(TYPEOID, type_id);
Assert(HeapTupleIsValid(type_tuple));
type = (Form_pg_type) GETSTRUCT(type_tuple);
result_strings[ENCODED_TYPE_NAME] = PointerGetDatum(pstrdup(type->typname.data));
namespace_tuple = SearchSysCache1(NAMESPACEOID, type->typnamespace);
Assert(HeapTupleIsValid(namespace_tuple));
namespace = (Form_pg_namespace) GETSTRUCT(namespace_tuple);
result_strings[ENCODED_TYPE_NAMESPACE] = PointerGetDatum(pstrdup(namespace->nspname.data));
ReleaseSysCache(namespace_tuple);
ReleaseSysCache(type_tuple);
}
static void
convert_op_oid_to_strings(Oid op_id, Datum *result_strings)
{
Form_pg_operator operator;
Form_pg_namespace namespace;
HeapTuple operator_tuple;
HeapTuple namespace_tuple;
operator_tuple = SearchSysCache1(OPEROID, op_id);
Assert(HeapTupleIsValid(operator_tuple));
operator=(Form_pg_operator) GETSTRUCT(operator_tuple);
result_strings[ENCODED_OP_NAME] = PointerGetDatum(pstrdup(operator->oprname.data));
namespace_tuple = SearchSysCache1(NAMESPACEOID, operator->oprnamespace);
Assert(HeapTupleIsValid(namespace_tuple));
namespace = (Form_pg_namespace) GETSTRUCT(namespace_tuple);
result_strings[ENCODED_OP_NAMESPACE] = PointerGetDatum(pstrdup(namespace->nspname.data));
ReleaseSysCache(namespace_tuple);
convert_type_oid_to_strings(operator->oprleft, LargSubarrayForOpArray(result_strings));
convert_type_oid_to_strings(operator->oprright, RargSubarrayForOpArray(result_strings));
ReleaseSysCache(operator_tuple);
}
static Oid
convert_strings_to_type_id(Datum *input_strings)
{
Oid arg_namespace = GetSysCacheOid1(NAMESPACENAME,
Anum_pg_namespace_oid,
input_strings[ENCODED_TYPE_NAMESPACE]);
Oid result;
Assert(OidIsValid(arg_namespace));
result = GetSysCacheOid2(TYPENAMENSP,
Anum_pg_type_oid,
input_strings[ENCODED_TYPE_NAME],
ObjectIdGetDatum(arg_namespace));
Assert(OidIsValid(result));
return result;
}
static Oid
convert_strings_to_op_id(Datum *input_strings)
{
Oid proc_namespace =
GetSysCacheOid1(NAMESPACENAME, Anum_pg_namespace_oid, input_strings[ENCODED_OP_NAMESPACE]);
Oid larg = convert_strings_to_type_id(LargSubarrayForOpArray(input_strings));
Oid rarg = convert_strings_to_type_id(RargSubarrayForOpArray(input_strings));
Oid result;
Assert(OidIsValid(proc_namespace));
result = GetSysCacheOid4(OPERNAMENSP,
Anum_pg_operator_oid,
input_strings[ENCODED_OP_NAME],
ObjectIdGetDatum(larg),
ObjectIdGetDatum(rarg),
ObjectIdGetDatum(proc_namespace));
Assert(OidIsValid(result));
return result;
}
static void
collect_colstat_slots(const HeapTuple tuple, const Form_pg_statistic formdata, Datum *values,
bool *nulls)
{
/* Fetching the values and/or numbers fields for a slot requires knowledge of which fields are
* present for each kind of stats. Note that this doesn't support custom statistics.
*/
static const int statistic_kind_slot_fields[STATISTIC_KIND_BOUNDS_HISTOGRAM + 1] = {
0,
ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS, /* MCV */
ATTSTATSSLOT_VALUES, /* HISTOGRAM */
ATTSTATSSLOT_NUMBERS, /* CORRELATION */
ATTSTATSSLOT_VALUES | ATTSTATSSLOT_NUMBERS, /* MCELEM */
ATTSTATSSLOT_NUMBERS, /* DECHIST */
/* ATTSTATSSLOT_VALUES is not always present for all HISTOGRAM operators.. */
ATTSTATSSLOT_NUMBERS, /* RANGE_LENGTH_HISTOGRAM */
ATTSTATSSLOT_VALUES /* BOUNDS_HISTOGRAM */
};
int i;
Datum slotkind[STATISTIC_NUM_SLOTS];
Datum op_strings[STRINGS_PER_OP_OID * STATISTIC_NUM_SLOTS];
Datum slot_collation[STATISTIC_NUM_SLOTS];
Datum value_type_strings[STRINGS_PER_TYPE_OID * STATISTIC_NUM_SLOTS];
ArrayType *array;
int nopstrings = 0;
int nvalstrings = 0;
for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
{
int16 kind = ((int16 *) (&formdata->stakind1))[i];
Datum slot_op = ObjectIdGetDatum(((Oid *) &formdata->staop1)[i]);
AttStatsSlot stat_slot;
int slot_fields;
const int numbers_idx = AttrNumberGetAttrOffset(Anum_chunk_colstats_slot1_numbers) + i;
const int values_idx = AttrNumberGetAttrOffset(Anum_chunk_colstats_slot1_values) + i;
slot_collation[i] = ObjectIdGetDatum(((Oid *) &formdata->stacoll1)[i]);
slotkind[i] = ObjectIdGetDatum(kind);
/*
* As per comments in pg_statistic_d.h, "kind" codes from 0 - 99 are reserved
* for assignment by the core PostgreSQL project. Beyond that are for PostGIS
* and other projects
*/
#define PG_STATS_KINDS_MAX 99
if (!OidIsValid(kind) || kind > PG_STATS_KINDS_MAX)
{
nulls[numbers_idx] = true;
nulls[values_idx] = true;
continue;
}
/* slot_op can be invalid for some "kinds" like STATISTIC_KIND_BOUNDS_HISTOGRAM */
if (OidIsValid(slot_op))
{
convert_op_oid_to_strings(slot_op, op_strings + nopstrings);
nopstrings += STRINGS_PER_OP_OID;
}
if (kind > STATISTIC_KIND_BOUNDS_HISTOGRAM)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("unable to fetch user defined statistics from data nodes")));
slot_fields = statistic_kind_slot_fields[kind];
get_attstatsslot(&stat_slot, tuple, kind, InvalidOid, slot_fields);
if (slot_fields & ATTSTATSSLOT_NUMBERS)
{
Datum *stanumbers = palloc(sizeof(Datum) * stat_slot.nnumbers);
int j;
for (j = 0; j < stat_slot.nnumbers; j++)
stanumbers[j] = Float4GetDatum(stat_slot.numbers[j]);
array = construct_array(stanumbers,
stat_slot.nnumbers,
FLOAT4OID,
FLOAT4_TYPELEN,
FLOAT4_TYPEBYVAL,
FLOAT4_TYPEALIGN);
values[numbers_idx] = PointerGetDatum(array);
}
else
nulls[numbers_idx] = true;
if (slot_fields & ATTSTATSSLOT_VALUES)
{
Datum *encoded_value_ary = palloc0(sizeof(Datum) * stat_slot.nvalues);
HeapTuple type_tuple = SearchSysCache1(TYPEOID, stat_slot.valuetype);
Form_pg_type type;
int k;
Assert(HeapTupleIsValid(type_tuple));
type = (Form_pg_type) GETSTRUCT(type_tuple);
convert_type_oid_to_strings(stat_slot.valuetype, value_type_strings + nvalstrings);
nvalstrings += STRINGS_PER_TYPE_OID;
for (k = 0; k < stat_slot.nvalues; ++k)
encoded_value_ary[k] = OidFunctionCall1(type->typoutput, stat_slot.values[k]);
array = construct_array(encoded_value_ary,
stat_slot.nvalues,
CSTRINGOID,
CSTRING_TYPELEN,
CSTRING_TYPEBYVAL,
CSTRING_TYPEALIGN);
values[values_idx] = PointerGetDatum(array);
ReleaseSysCache(type_tuple);
}
else
nulls[values_idx] = true;
free_attstatsslot(&stat_slot);
}
array = construct_array(slotkind,
STATISTIC_NUM_SLOTS,
INT4OID,
INT4_TYPELEN,
INT4_TYPEBYVAL,
INT4_TYPEALIGN);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_slot_kinds)] = PointerGetDatum(array);
array = construct_array(op_strings,
nopstrings,
CSTRINGOID,
CSTRING_TYPELEN,
CSTRING_TYPEBYVAL,
CSTRING_TYPEALIGN);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_slot_op_strings)] = PointerGetDatum(array);
array = construct_array(slot_collation,
STATISTIC_NUM_SLOTS,
OIDOID,
OID_TYPELEN,
OID_TYPEBYVAL,
OID_TYPEALIGN);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_slot_collations)] = PointerGetDatum(array);
array = construct_array(value_type_strings,
nvalstrings,
CSTRINGOID,
CSTRING_TYPELEN,
CSTRING_TYPEBYVAL,
CSTRING_TYPEALIGN);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_slot_valtype_strings)] =
PointerGetDatum(array);
}
/*
* Construct a tuple for the get_chunk_relstats SQL function.
*/
static HeapTuple
chunk_get_single_colstats_tuple(Chunk *chunk, int column, TupleDesc tupdesc)
{
HeapTuple ctup;
Form_pg_statistic pgsform;
Datum values[_Anum_chunk_colstats_max];
bool nulls[_Anum_chunk_colstats_max] = { false };
bool dropped;
if (DatumGetBool(DirectFunctionCall1(row_security_active, ObjectIdGetDatum(chunk->table_id))))
return NULL;
ctup = SearchSysCache2(ATTNUM, ObjectIdGetDatum(chunk->table_id), column);
if (!HeapTupleIsValid(ctup))
return NULL;
dropped = ((Form_pg_attribute) GETSTRUCT(ctup))->attisdropped;
ReleaseSysCache(ctup);
if (dropped)
return NULL;
if (!DatumGetBool(DirectFunctionCall3(has_column_privilege_id_attnum,
ObjectIdGetDatum(chunk->table_id),
Int16GetDatum(column),
PointerGetDatum(cstring_to_text("SELECT")))))
return NULL;
ctup = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(chunk->table_id), column, false);
/* pg_statistics will not have an entry for an unanalyzed table */
if (!HeapTupleIsValid(ctup))
return NULL;
pgsform = (Form_pg_statistic) GETSTRUCT(ctup);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_chunk_id)] = Int32GetDatum(chunk->fd.id);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_hypertable_id)] =
Int32GetDatum(chunk->fd.hypertable_id);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_column_id)] = Int32GetDatum(column);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_nullfrac)] =
Float4GetDatum(pgsform->stanullfrac);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_width)] = Int32GetDatum(pgsform->stawidth);
values[AttrNumberGetAttrOffset(Anum_chunk_colstats_distinct)] =
Float4GetDatum(pgsform->stadistinct);
collect_colstat_slots(ctup, pgsform, values, nulls);
ReleaseSysCache(ctup);
return heap_form_tuple(tupdesc, values, nulls);
}
static void
chunk_update_colstats(Chunk *chunk, int16 attnum, float nullfract, int32 width, float distinct,
ArrayType *kind_array, ArrayType *collations, Oid *slot_ops,
ArrayType **slot_numbers, Oid *value_kinds, ArrayType **slot_values)
{
Relation rel;
Relation sd;
Datum values[Natts_pg_statistic];
bool nulls[Natts_pg_statistic];
bool replaces[Natts_pg_statistic];
HeapTuple stup;
HeapTuple oldtup;
int i, k;
int *slot_kinds;
rel = try_relation_open(chunk->table_id, ShareUpdateExclusiveLock);
/* If a vacuum is running we might not be able to grab the lock, so just
* raise an error and let the user try again. */
if (NULL == rel)
ereport(ERROR,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("unable to acquire table lock to update column statistics on \"%s\"",
NameStr(chunk->fd.table_name))));
sd = relation_open(StatisticRelationId, RowExclusiveLock);
memset(nulls, false, Natts_pg_statistic);
memset(replaces, true, Natts_pg_statistic);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_starelid)] = ObjectIdGetDatum(rel->rd_id);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_staattnum)] = Int16GetDatum(attnum);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_stainherit)] = BoolGetDatum(false);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_stanullfrac)] = Float4GetDatum(nullfract);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_stawidth)] = Int32GetDatum(width);
values[AttrNumberGetAttrOffset(Anum_pg_statistic_stadistinct)] = Float4GetDatum(distinct);
i = AttrNumberGetAttrOffset(Anum_pg_statistic_stakind1);
slot_kinds = (int *) ARR_DATA_PTR(kind_array);
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
values[i++] = Int16GetDatum(slot_kinds[k]); /* stakindN */
i = AttrNumberGetAttrOffset(Anum_pg_statistic_stacoll1);
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
values[i++] = ObjectIdGetDatum(((Oid *) ARR_DATA_PTR(collations))[k]); /* stacollN */
i = AttrNumberGetAttrOffset(Anum_pg_statistic_staop1);
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
values[i++] = ObjectIdGetDatum(slot_ops[k]); /* staopN */
i = AttrNumberGetAttrOffset(Anum_pg_statistic_stanumbers1);
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
if (slot_numbers[k] == NULL)
nulls[i++] = true;
else
values[i++] = PointerGetDatum(slot_numbers[k]); /* stanumbersN */
i = AttrNumberGetAttrOffset(Anum_pg_statistic_stavalues1);
for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
{
Oid value_oid = value_kinds[k];
HeapTuple type_tuple;