forked from byucesoy/pg_color
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_color.c
2022 lines (1583 loc) · 47.1 KB
/
pg_color.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
/*
* pg_color: Color data type for PostgreSQL
*
* Author: Burak Yucesoy <[email protected]>
*/
#include "postgres.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/builtins.h"
#include "libpq/pqformat.h"
#include "nodes/makefuncs.h"
#ifndef PG_VERSION_NUM
#error "Unsupported too old PostgreSQL version"
#endif
#include "nodes/readfuncs.h"
#include "miscadmin.h"
#include "optimizer/planner.h"
#include "nodes/extensible.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
void _PG_init(void);
static PlannedStmt *
pg_color_planner(Query *parse, int cursorOptions, ParamListInfo boundParams);
PlannedStmt *
GetOriginalPlan(CustomScan *customScan);
typedef struct color
{
uint8 r;
uint8 g;
uint8 b;
} color;
#define DatumGetColor(X) ((color *) DatumGetPointer(X))
#define ColorGetDatum(X) PointerGetDatum(X)
#define PG_GETARG_COLOR(n) DatumGetColor(PG_GETARG_DATUM(n))
#define PG_RETURN_COLOR(x) return ColorGetDatum(x)
static void InitializeColorQueryStats(void);
static Node *
PgColorCreateScan(CustomScan *scan);
CustomScanMethods PgColorCustomScanMethods = {
"PGColor Scan",
PgColorCreateScan
};
typedef struct PgColorExtendedNode
{
ExtensibleNode extensible;
color *interceptedColor;
} PgColorExtendedNode;
typedef struct PgColorScanState
{
CustomScanState customScanState; /* underlying custom scan node */
PlannedStmt *plannedStatement; /* the execution plan */
PgColorExtendedNode *color; /* the color information passed to the execution */
uint64 queryId;
bool finishedScan; /* flag to check if remote scan is finished */
Tuplestorestate *tuplestorestate; /* tuple store to store distributed results */
} PgColorScanState;
static void
ColorQueryStatsExecutorsEntry(uint64 queryId, color *color);
static void
PgColorBeginScan(CustomScanState *node, EState *estate, int eflags);
TupleTableSlot *
PgColorExecScan(CustomScanState *node);
static void
PgColorEndScan(CustomScanState *node);
static void
PgColorReScan(CustomScanState *node);
static CustomExecMethods PgColorCustomExecMethods = {
.CustomName = "PgColorExecutorScan",
.BeginCustomScan = PgColorBeginScan,
.ExecCustomScan = PgColorExecScan,
.EndCustomScan = PgColorEndScan,
.ReScanCustomScan = PgColorReScan,
};
static void
PgColorBeginScan(CustomScanState *node, EState *estate, int eflags)
{
/* do nothing*/
#if PG_VERSION_NUM >= 120000
ExecInitResultSlot(&node->ss.ps, &TTSOpsMinimalTuple);
#endif
}
static EState *
ScanStateGetExecutorState(PgColorScanState *scanState)
{
return scanState->customScanState.ss.ps.state;
}
#include "executor/tstoreReceiver.h"
#include "utils/snapmgr.h"
TupleTableSlot *
ReturnTupleFromTuplestore(PgColorScanState *scanState);
TupleTableSlot *
PgColorExecScan(CustomScanState *node)
{
PgColorScanState *scanState = (PgColorScanState *) node;
TupleTableSlot *resultSlot = NULL;
if (!scanState->finishedScan)
{
/*TODO: standardExecutor_Run*/
DestReceiver *tupleStoreDestReceiever = CreateDestReceiver(DestTuplestore);
EState *executorState = ScanStateGetExecutorState(scanState);
ParamListInfo paramListInfo = executorState->es_param_list_info;
QueryEnvironment *queryEnv = create_queryEnv();
ScanDirection scanDirection = ForwardScanDirection;
bool randomAccess = true;
bool interTransactions = false;
scanState->tuplestorestate =
tuplestore_begin_heap(randomAccess, interTransactions, work_mem);
/*
* Use the tupleStore provided by the scanState because it is shared accross
* the other task executions and the adaptive executor.
*/
SetTuplestoreDestReceiverParams(tupleStoreDestReceiever,
scanState->tuplestorestate,
CurrentMemoryContext, false);
/* Create a QueryDesc for the query */
QueryDesc *queryDesc = CreateQueryDesc(scanState->plannedStatement
, "",
GetActiveSnapshot(), InvalidSnapshot,
tupleStoreDestReceiever, paramListInfo,
queryEnv, 0);
standard_ExecutorStart(queryDesc,0);
standard_ExecutorRun(queryDesc, scanDirection, 0L, true);
standard_ExecutorFinish(queryDesc);
standard_ExecutorEnd(queryDesc);
UnregisterSnapshot(GetActiveSnapshot());
scanState->finishedScan = true;
}
resultSlot = ReturnTupleFromTuplestore(scanState);
return resultSlot;
}
/*
* ReturnTupleFromTuplestore reads the next tuple from the tuple store of the
* given Citus scan node and returns it. It returns null if all tuples are read
* from the tuple store.
*/
TupleTableSlot *
ReturnTupleFromTuplestore(PgColorScanState *scanState)
{
Tuplestorestate *tupleStore = scanState->tuplestorestate;
TupleTableSlot *resultSlot = NULL;
EState *executorState = NULL;
ScanDirection scanDirection = NoMovementScanDirection;
bool forwardScanDirection = true;
if (tupleStore == NULL)
{
return NULL;
}
executorState = ScanStateGetExecutorState(scanState);
scanDirection = executorState->es_direction;
Assert(ScanDirectionIsValid(scanDirection));
if (ScanDirectionIsBackward(scanDirection))
{
forwardScanDirection = false;
}
resultSlot = scanState->customScanState.ss.ps.ps_ResultTupleSlot;
tuplestore_gettupleslot(tupleStore, forwardScanDirection, false, resultSlot);
return resultSlot;
}
PgColorExtendedNode *
GetPgColorExtendedNode(CustomScan *customScan);
static void
PgColorEndScan(CustomScanState *node)
{
PgColorScanState *scanState = (PgColorScanState *) node;
if (scanState->tuplestorestate)
{
tuplestore_end(scanState->tuplestorestate);
scanState->tuplestorestate = NULL;
}
ColorQueryStatsExecutorsEntry(scanState->queryId, scanState->color->interceptedColor);
}
static void
PgColorReScan(CustomScanState *node)
{
}
static Node *
PgColorCreateScan(CustomScan *scan)
{
PgColorScanState *scanState = palloc0(sizeof(PgColorScanState));
PgColorExtendedNode *colorData = GetPgColorExtendedNode(scan);
scanState->customScanState.ss.ps.type = T_CustomScanState;
scanState->color = colorData;
scanState->plannedStatement = GetOriginalPlan(scan);
scanState->queryId = scanState->plannedStatement->queryId;
scanState->customScanState.methods = &PgColorCustomExecMethods;
return (Node *) scanState;
}
PgColorExtendedNode *
GetPgColorExtendedNode(CustomScan *customScan)
{
Node *node = NULL;
PgColorExtendedNode *color = NULL;
Assert(list_length(customScan->custom_private) == 1);
node = (Node *) linitial(customScan->custom_private);
color = (PgColorExtendedNode *) node;
return color;
}
PlannedStmt *
GetOriginalPlan(CustomScan *customScan)
{
Node *node = NULL;
PlannedStmt *plan = NULL;
node = (Node *) linitial(customScan->custom_plans);
// Assert(CitusIsA(node, PgColorExtendedNode));
// CheckNodeCopyAndSerialization(node);
plan = (PlannedStmt *) node;
return plan;
}
static void
CopyPgColorExtendedNode(struct ExtensibleNode *target_node, const struct ExtensibleNode *source_node);
static bool
EqualPgColorExtendedNode(const struct ExtensibleNode *target_node, const struct ExtensibleNode *source_node);
void
OutPgColorExtendedNode( struct StringInfoData *str, const struct ExtensibleNode *raw_node);
void
ReadPgColorExtendedNode(struct ExtensibleNode *node);
void
CopyPgColorExtendedNode(struct ExtensibleNode *target_node, const struct ExtensibleNode *source_node)
{
PgColorExtendedNode *targetPlan = (PgColorExtendedNode *) target_node;
PgColorExtendedNode *sourcePlan = (PgColorExtendedNode *) source_node;
targetPlan->interceptedColor = palloc0(sizeof(color));
targetPlan->interceptedColor->r = sourcePlan->interceptedColor->r;
targetPlan->interceptedColor->g = sourcePlan->interceptedColor->g;
targetPlan->interceptedColor->b = sourcePlan->interceptedColor->b;
}
bool
EqualPgColorExtendedNode(const struct ExtensibleNode *target_node, const struct ExtensibleNode *source_node)
{
PgColorExtendedNode *targetPlan = (PgColorExtendedNode *) target_node;
PgColorExtendedNode *sourcePlan = (PgColorExtendedNode *) source_node;
return targetPlan->interceptedColor->r == sourcePlan->interceptedColor->r;
}
#define NodeName "PgColorExtendedNode"
/* Write a Node field */
#define WRITE_NODE_FIELD(fldname) \
(appendStringInfo(str, " :" CppAsString(fldname) " "), \
outNode(str, node->fldname))
#define WRITE_INT_FIELD(fldname) \
appendStringInfo(str, " :" CppAsString(fldname) " %d", node->fldname)
void
OutPgColorExtendedNode( struct StringInfoData *str, const struct ExtensibleNode *raw_node)
{
const PgColorExtendedNode *node = (const PgColorExtendedNode *) raw_node;
WRITE_INT_FIELD(interceptedColor->r);
WRITE_INT_FIELD(interceptedColor->g);
WRITE_INT_FIELD(interceptedColor->b);
}
#define READ_NODE_FIELD(fldname) \
token = pg_strtok(&length); /* skip :fldname */ \
(void) token; /* in case not used elsewhere */ \
local_node->fldname = nodeRead(NULL, 0)
#define READ_INT_FIELD(fldname) \
token = pg_strtok(&length); /* skip :fldname */ \
token = pg_strtok(&length); /* get field value */ \
local_node->fldname = atoi(token)
void
ReadPgColorExtendedNode(struct ExtensibleNode *node)
{
PgColorExtendedNode *local_node = (PgColorExtendedNode *) node;
const char *token;
int length;
READ_INT_FIELD(interceptedColor->r);
READ_INT_FIELD(interceptedColor->g);
READ_INT_FIELD(interceptedColor->b);
}
const ExtensibleNodeMethods nodeMethods =
{.extnodename = NodeName,
.node_size = sizeof(PgColorExtendedNode),
.nodeCopy = CopyPgColorExtendedNode,
.nodeEqual = EqualPgColorExtendedNode,
.nodeRead = ReadPgColorExtendedNode,
.nodeOut = OutPgColorExtendedNode
};
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
{
ereport(ERROR, (errmsg("Citus can only be loaded via shared_preload_libraries"),
errhint("Add citus to shared_preload_libraries configuration "
"variable in postgresql.conf in master and workers. Note "
"that citus should be at the beginning of "
"shared_preload_libraries.")));
}
RegisterExtensibleNodeMethods(&nodeMethods);
/* intercept planner */
planner_hook = pg_color_planner;
InitializeColorQueryStats();
}
static PlannedStmt *
FinalizePlan(PlannedStmt *localPlan, color *interceptedColor);
Const *
FetchColorInFilter(Query *query);
PlannedStmt *
pg_color_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
{
PlannedStmt *result = standard_planner(parse, cursorOptions, boundParams);
color *c = NULL;
Const *col = FetchColorInFilter(parse);
if (col != NULL)
{
c = DatumGetColor(col->constvalue);
return FinalizePlan(result, c);
}
return result;
}
bool
ExtractColorNodes(Node *node, List **colorList);
Const *
FetchColorInFilter(Query *query)
{
RangeTblEntry *rangeTableEntry = NULL;
FromExpr *joinTree = query->jointree;
Node *quals = NULL;
List *colorList = NIL;
if (query->commandType != CMD_SELECT)
{
return NULL;
}
/* make sure that the only range table in FROM clause */
if (list_length(query->rtable) != 1)
{
return NULL;
}
rangeTableEntry = (RangeTblEntry *) linitial(query->rtable);
if (rangeTableEntry->rtekind != RTE_RELATION)
{
return NULL;
}
/* WHERE clause should not be empty */
if (joinTree == NULL || joinTree->quals == NULL)
{
return NULL;
}
/* convert list of expressions into expression tree for further processing */
quals = joinTree->quals;
if (quals != NULL && IsA(quals, List))
{
quals = (Node *) make_ands_explicit((List *) quals);
}
ExtractColorNodes(quals, &colorList);
if (list_length(colorList) == 1)
return linitial(colorList);
return NULL;
}
#include "nodes/nodeFuncs.h"
bool
ExtractColorNodes(Node *node, List **colorList)
{
bool walkerResult = false;
if (node == NULL)
{
return false;
}
if (IsA(node, Const))
{
Const *val = (Const *) node;
if (val->consttype == 91750)
{
*colorList = lappend(*colorList, val);
}
}
else
{
walkerResult = expression_tree_walker(node, ExtractColorNodes,
colorList);
}
return walkerResult;
}
RangeTblEntry *
RemoteScanRangeTableEntry(List *columnNameList);
static PlannedStmt *
FinalizePlan(PlannedStmt *localPlan, color *interceptedColor)
{
PlannedStmt *finalPlan = NULL;
CustomScan *customScan = makeNode(CustomScan);
PgColorExtendedNode *interceptedColorData = NULL;
RangeTblEntry *remoteScanRangeTableEntry = NULL;
customScan->methods = &PgColorCustomScanMethods;
interceptedColorData = palloc(sizeof(PgColorExtendedNode));
interceptedColorData->extensible.extnodename = NodeName;
interceptedColorData->extensible.type = T_ExtensibleNode;
interceptedColorData->interceptedColor = interceptedColor;
customScan->custom_private = list_make1(interceptedColorData);
customScan->custom_plans = list_make1(localPlan);
customScan->flags = CUSTOMPATH_SUPPORT_BACKWARD_SCAN;
/* we will have custom scan range table entry as the first one in the list */
int customScanRangeTableIndex = 1;
ListCell *targetEntryCell = NULL;
List *targetList = NIL;
List *columnNameList = NIL;
/* build a targetlist to read from the custom scan output */
foreach(targetEntryCell, localPlan->planTree->targetlist)
{
TargetEntry *targetEntry = lfirst(targetEntryCell);
TargetEntry *newTargetEntry = NULL;
Var *newVar = NULL;
Value *columnName = NULL;
Assert(IsA(targetEntry, TargetEntry));
/*
* This is unlikely to be hit because we would not need resjunk stuff
* at the toplevel of a router query - all things needing it have been
* pushed down.
*/
if (targetEntry->resjunk)
{
continue;
}
/* build target entry pointing to remote scan range table entry */
newVar = makeVarFromTargetEntry(customScanRangeTableIndex, targetEntry);
newTargetEntry = flatCopyTargetEntry(targetEntry);
newTargetEntry->expr = (Expr *) newVar;
targetList = lappend(targetList, newTargetEntry);
columnName = makeString(targetEntry->resname);
columnNameList = lappend(columnNameList, columnName);
}
customScan->scan.plan.targetlist = targetList;
finalPlan = makeNode(PlannedStmt);
finalPlan->planTree = (Plan *) customScan;
finalPlan->canSetTag = true;
finalPlan->relationOids = NIL;
finalPlan->queryId = localPlan->queryId;
finalPlan->utilityStmt = localPlan->utilityStmt;
finalPlan->commandType = localPlan->commandType;
finalPlan->hasReturning = localPlan->hasReturning;
remoteScanRangeTableEntry = RemoteScanRangeTableEntry(columnNameList);
finalPlan->rtable = list_make1(remoteScanRangeTableEntry);
return finalPlan;
}
RangeTblEntry *
RemoteScanRangeTableEntry(List *columnNameList)
{
RangeTblEntry *remoteScanRangeTableEntry = makeNode(RangeTblEntry);
/* we use RTE_VALUES for custom scan because we can't look up relation */
remoteScanRangeTableEntry->rtekind = RTE_VALUES;
remoteScanRangeTableEntry->eref = makeAlias("remote_scan", columnNameList);
remoteScanRangeTableEntry->inh = false;
remoteScanRangeTableEntry->inFromCl = true;
return remoteScanRangeTableEntry;
}
static inline
color * color_from_str(char *str)
{
color *c = palloc0(sizeof(color));
char *endptr = NULL;
char *cur = str;
if (cur[0] != '(')
elog(ERROR, "expected '(' at position 0");
cur++;
c->r = strtol(cur, &endptr, 10);
if (cur == endptr)
elog(ERROR, "expected number at position 1");
if (endptr[0] != ',')
elog(ERROR, "expected ',' at position " INT64_FORMAT, endptr - str);
cur = endptr + 1;
c->g = strtoll(cur, &endptr, 10);
if (cur == endptr)
elog(ERROR, "expected number at position 2");
if (endptr[0] != ',')
elog(ERROR, "expected ',' at position " INT64_FORMAT, endptr - str);
cur = endptr + 1;
c->b = strtoll(cur, &endptr, 10);
if (endptr[0] != ')')
elog(ERROR, "expected ')' at position " INT64_FORMAT, endptr - str);
if (endptr[1] != '\0')
elog(ERROR, "unexpected character at position " INT64_FORMAT, 1 + (endptr - str));
return c;
}
static inline
char *color_to_str(color *c)
{
char *s = psprintf("(%d,%d,%d)", c->r, c->g, c->b);
return s;
}
Datum color_in(PG_FUNCTION_ARGS);
Datum color_out(PG_FUNCTION_ARGS);
Datum color_eq(PG_FUNCTION_ARGS);
Datum color_ne(PG_FUNCTION_ARGS);
Datum color_cmp(PG_FUNCTION_ARGS);
Datum color_lt(PG_FUNCTION_ARGS);
Datum color_le(PG_FUNCTION_ARGS);
Datum color_gt(PG_FUNCTION_ARGS);
Datum color_ge(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(color_in);
Datum
color_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
PG_RETURN_COLOR(color_from_str(str));
}
PG_FUNCTION_INFO_V1(color_out);
Datum
color_out(PG_FUNCTION_ARGS)
{
color *c = (color *) PG_GETARG_COLOR(0);
PG_RETURN_CSTRING(color_to_str(c));
}
PG_FUNCTION_INFO_V1(color_eq);
Datum
color_eq(PG_FUNCTION_ARGS)
{
color *c1 = PG_GETARG_COLOR(0);
color *c2 = PG_GETARG_COLOR(1);
// return 0;
return c1->r == c2->r && c1->g == c2->g && c1->b == c2->b;
}
PG_FUNCTION_INFO_V1(color_ne);
Datum
color_ne(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
return c1->r != c2->r || c1->g != c2->g || c1->b != c2->b;
}
PG_FUNCTION_INFO_V1(color_cmp);
Datum
color_cmp(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
if (c1 == NULL)
return 1;
if (c2 == NULL)
return -1;
if (c1->r > c2->r)
return 1;
else if (c1->r < c2->r)
return -1;
if (c1->g > c2->g)
return 1;
else if (c1->g < c2->g)
return -1;
if (c1->b > c2->b)
return 1;
else if (c1->b < c2->b)
return -1;
return 0;
}
PG_FUNCTION_INFO_V1(rgb_distance);
Datum
rgb_distance(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
double d1 = (double)c1->r - c2->r;
double d2 = (double)c1->g - c2->g;
double d3 = (double)c1->b - c2->b;
PG_RETURN_FLOAT8(sqrt(d1 * d1 + d2 * d2 + d3 * d3));
}
PG_FUNCTION_INFO_V1(color_lt);
Datum
color_lt(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
if (c1->r < c2->r)
return 1;
else if (c1->r > c2->r)
return 0;
if (c1->g < c2->g)
return 1;
else if (c1->g > c2->g)
return 0;
if (c1->b < c2->b)
return 1;
else if (c1->b > c2->b)
return 0;
return 0;
}
PG_FUNCTION_INFO_V1(color_le);
Datum
color_le(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
if (c1->r < c2->r)
return 1;
else if (c1->r > c2->r)
return 0;
if (c1->g < c2->g)
return 1;
else if (c1->g > c2->g)
return 0;
if (c1->b < c2->b)
return 1;
else if (c1->b > c2->b)
return 0;
return 1;
}
PG_FUNCTION_INFO_V1(color_gt);
Datum
color_gt(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
if (c1->r > c2->r)
return 1;
else if (c1->r < c2->r)
return 0;
if (c1->g > c2->g)
return 1;
else if (c1->g < c2->g)
return 0;
if (c1->b > c2->b)
return 1;
else if (c1->b < c2->b)
return 0;
return 0;
}
PG_FUNCTION_INFO_V1(color_ge);
Datum
color_ge(PG_FUNCTION_ARGS)
{
color *c1 = (color *) PG_GETARG_COLOR(0);
color *c2 = (color *) PG_GETARG_COLOR(1);
if (c1->r > c2->r)
return 1;
else if (c1->r < c2->r)
return 0;
if (c1->g > c2->g)
return 1;
else if (c1->g < c2->g)
return 0;
if (c1->b > c2->b)
return 1;
else if (c1->b < c2->b)
return 0;
return 1;
}
PG_FUNCTION_INFO_V1(color_send);
Datum
color_send(PG_FUNCTION_ARGS)
{
color *a = PG_GETARG_COLOR(0);
StringInfoData buf;
pq_begintypsend(&buf);
pq_sendint8(&buf, a->r);
pq_sendint8(&buf, a->g);
pq_sendint8(&buf, a->b);
PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}
PG_FUNCTION_INFO_V1(color_recv);
Datum
color_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
color *result = palloc0(sizeof(color));
result->r = pq_getmsgint64(buf);
result->g = pq_getmsgint64(buf);
result->b = pq_getmsgint64(buf);
PG_RETURN_COLOR(result);
}
/*-------------------------------------------------------------------------
*
* query_stats.c
* Statement-level statistics for distributed queries.
* Code is mostly taken from postgres/contrib/pg_stat_statements
* and adapted to citus.
*
* Copyright (c) 2012-2018, Citus Data, Inc.
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "access/hash.h"
#include "catalog/pg_authid.h"
#include "funcapi.h"
#include "storage/ipc.h"
#include "storage/fd.h"
#include "storage/spin.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include <unistd.h>
#define COLOR_STATS_DUMP_FILE "pg_stat/color_query_stats.stat"
#define COLOR_STAT_STATEMENTS_COLS 6
#define COLOR_STAT_STATAMENTS_QUERY_ID 0
#define COLOR_STAT_STATAMENTS_USER_ID 1
#define COLOR_STAT_STATAMENTS_DB_ID 2
#define COLOR_STAT_STATAMENTS_COLOR 3
#define COLOR_STAT_STATAMENTS_CALLS 4
#define USAGE_DECREASE_FACTOR (0.99) /* decreased every CitusQueryStatsEntryDealloc */
#define STICKY_DECREASE_FACTOR (0.50) /* factor for sticky entries */
#define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
#define USAGE_INIT (1.0) /* including initial planning */
#define STATS_SHARED_MEM_NAME "color_query_stats"
#define MAX_KEY_LENGTH NAMEDATALEN
/* Magic number identifying the stats file format */
static const uint32 COLOR_QUERY_STATS_FILE_HEADER = 0x0e756e0f;
/* TODO: maximum number of entries in queryStats hash, controlled by GUC citus.stat_statements_max */
int ColorStatsMax = 50000;
/*
* Hashtable key that defines the identity of a hashtable entry. We use the
* same hash as pg_stat_statements
*/
typedef struct QueryStatsHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
uint64 queryid; /* query identifier */
char color[MAX_KEY_LENGTH];
} QueryStatsHashKey;
/*
* Statistics per query and executor type
*/
typedef struct queryStatsEntry
{
QueryStatsHashKey key; /* hash key of entry - MUST BE FIRST */
int64 calls; /* # of times executed */
double usage; /* hashtable usage factor */
slock_t mutex; /* protects the counters only */
} QueryStatsEntry;
/*
* Global shared state
*/
typedef struct QueryStatsSharedState
{
LWLockId lock; /* protects hashtable search/modification */
double cur_median_usage; /* current median usage in hashtable */
} QueryStatsSharedState;
/* lookup table for existing pg_stat_statements entries */
typedef struct ExistingStatsHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
uint64 queryid; /* query identifier */
} ExistingStatsHashKey;
/* saved hook address in case of unload */
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
/* Links to shared memory state */
static QueryStatsSharedState *queryStats = NULL;
static HTAB *queryStatsHash = NULL;
/*--- Functions --- */
Datum color_query_stats(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(color_query_stats);
PG_FUNCTION_INFO_V1(color_stat_statements_reset);
static Size ColorQueryStatsSharedMemSize(void);
static void ColorQueryStatsShmemStartup(void);
static void ColorQueryStatsShmemShutdown(int code, Datum arg);
static QueryStatsEntry * ColorQueryStatsEntryAlloc(QueryStatsHashKey *key, bool sticky);
static void ColorQueryStatsEntryDealloc(void);
static void ColorQueryStatsEntryReset(void);
static uint32 ColorQuerysStatsHashFn(const void *key, Size keysize);
static int ColorQuerysStatsMatchFn(const void *key1, const void *key2, Size keysize);
static uint32 ExistingStatsHashFn(const void *key, Size keysize);
static int ExistingStatsMatchFn(const void *key1, const void *key2, Size keysize);
static HTAB * BuildExistingQueryIdHash(void);
static int GetPGColorStatsMax(void);
static void ColorQueryStatsRemoveExpiredEntries(HTAB *existingQueryIdHash);
static void ColorQueryStatsExecutorsEntry(uint64 queryId, color *color);
static Tuplestorestate *
SetupTuplestore(FunctionCallInfo fcinfo, TupleDesc *tupleDescriptor);
static void ColorQueryStatsSynchronizeEntries(void);
static ReturnSetInfo *
CheckTuplestoreReturn(FunctionCallInfo fcinfo, TupleDesc *tupdesc);