-
Notifications
You must be signed in to change notification settings - Fork 5
/
pg_stat_query_plans_parser.c
1136 lines (992 loc) · 35.1 KB
/
pg_stat_query_plans_parser.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
#include "postgres.h"
#if PG_VERSION_NUM >= 130000
#include "common/hashfn.h"
#elif PG_VERSION_NUM >= 120000
#include "utils/hashutils.h"
#else
#include "access/hash.h"
#endif
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/scanner.h"
#include "parser/scansup.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 160000
#include "gram_pg16.h"
#else
#include "parser/gram.h"
#endif
#include "pg_stat_query_plans_parser.h"
#include "pg_stat_query_plans_assert.h"
#if PG_VERSION_NUM < 140000
static bool need_replace(int token);
/*
* pgqpAppendJumble: Append a value that is substantive in a given query to
* the current jumble.
*/
void pgqpAppendJumble(pgqpJumbleState *jstate, const unsigned char *item,
Size size) {
unsigned char *jumble = jstate->jumble;
Size jumble_len = jstate->jumble_len;
/*
* Whenever the jumble buffer is full, we hash the current contents and
* reset the buffer to contain just that hash value, thus relying on the
* hash to summarize everything so far.
*/
while (size > 0) {
Size part_size;
if (jumble_len >= JUMBLE_SIZE) {
uint64 start_hash;
start_hash = DatumGetUInt64(hash_any_extended(jumble, JUMBLE_SIZE, 0));
memcpy(jumble, &start_hash, sizeof(start_hash));
jumble_len = sizeof(start_hash);
}
part_size = Min(size, JUMBLE_SIZE - jumble_len);
memcpy(jumble + jumble_len, item, part_size);
jumble_len += part_size;
item += part_size;
size -= part_size;
}
jstate->jumble_len = jumble_len;
}
/*
* Wrappers around pgqpAppendJumble to encapsulate details of serialization
* of individual local variable elements.
*/
#define PGQP_APP_JUMB(item) \
pgqpAppendJumble(jstate, (const unsigned char *)&(item), sizeof(item))
#define PGQP_APP_JUMB_STRING(str) \
pgqpAppendJumble(jstate, (const unsigned char *)(str), strlen(str) + 1)
/*
* pgqpJumbleQuery: Selectively serialize the query tree, appending significant
* data to the "query jumble" while ignoring nonsignificant data.
*
* Rule of thumb for what to include is that we should ignore anything not
* semantically significant (such as alias names) as well as anything that can
* be deduced from child nodes (else we'd just be double-hashing that piece
* of information).
*/
void pgqpJumbleQuery(pgqpJumbleState *jstate, Query *query) {
pgqpAssert(IsA(query, Query));
pgqpAssert(query->utilityStmt == NULL);
PGQP_APP_JUMB(query->commandType);
/* resultRelation is usually predictable from commandType */
pgqpJumbleExpr(jstate, (Node *)query->cteList);
pgqpJumbleRangeTable(jstate, query->rtable);
pgqpJumbleExpr(jstate, (Node *)query->jointree);
pgqpJumbleExpr(jstate, (Node *)query->targetList);
pgqpJumbleExpr(jstate, (Node *)query->onConflict);
pgqpJumbleExpr(jstate, (Node *)query->returningList);
pgqpJumbleExpr(jstate, (Node *)query->groupClause);
pgqpJumbleExpr(jstate, (Node *)query->groupingSets);
pgqpJumbleExpr(jstate, query->havingQual);
pgqpJumbleExpr(jstate, (Node *)query->windowClause);
pgqpJumbleExpr(jstate, (Node *)query->distinctClause);
pgqpJumbleExpr(jstate, (Node *)query->sortClause);
pgqpJumbleExpr(jstate, query->limitOffset);
pgqpJumbleExpr(jstate, query->limitCount);
pgqpJumbleRowMarks(jstate, query->rowMarks);
pgqpJumbleExpr(jstate, query->setOperations);
}
/*
* Jumble a range table
*/
void pgqpJumbleRangeTable(pgqpJumbleState *jstate, List *rtable) {
ListCell *lc;
foreach (lc, rtable) {
RangeTblEntry *rte = lfirst_node(RangeTblEntry, lc);
PGQP_APP_JUMB(rte->rtekind);
switch (rte->rtekind) {
case RTE_RELATION:
PGQP_APP_JUMB(rte->relid);
pgqpJumbleExpr(jstate, (Node *)rte->tablesample);
break;
case RTE_SUBQUERY:
pgqpJumbleQuery(jstate, rte->subquery);
break;
case RTE_JOIN:
PGQP_APP_JUMB(rte->jointype);
break;
case RTE_FUNCTION:
pgqpJumbleExpr(jstate, (Node *)rte->functions);
break;
case RTE_TABLEFUNC:
pgqpJumbleExpr(jstate, (Node *)rte->tablefunc);
break;
case RTE_VALUES:
pgqpJumbleExpr(jstate, (Node *)rte->values_lists);
break;
case RTE_CTE:
/*
* Depending on the CTE name here isn't ideal, but it's the
* only info we have to identify the referenced WITH item.
*/
PGQP_APP_JUMB_STRING(rte->ctename);
PGQP_APP_JUMB(rte->ctelevelsup);
break;
case RTE_NAMEDTUPLESTORE:
PGQP_APP_JUMB_STRING(rte->enrname);
break;
#if PG_VERSION_NUM >= 120000
case RTE_RESULT:
break;
#endif
default:
elog(ERROR, "unrecognized RTE kind: %d", (int)rte->rtekind);
break;
}
}
}
/*
* Jumble a rowMarks list
*/
void pgqpJumbleRowMarks(pgqpJumbleState *jstate, List *rowMarks) {
ListCell *lc;
foreach (lc, rowMarks) {
RowMarkClause *rowmark = lfirst_node(RowMarkClause, lc);
if (!rowmark->pushedDown) {
PGQP_APP_JUMB(rowmark->rti);
PGQP_APP_JUMB(rowmark->strength);
PGQP_APP_JUMB(rowmark->waitPolicy);
}
}
}
/*
* Jumble an expression tree
*
* In general this function should handle all the same node types that
* expression_tree_walker() does, and therefore it's coded to be as parallel
* to that function as possible. However, since we are only invoked on
* queries immediately post-parse-analysis, we need not handle node types
* that only appear in planning.
*
* Note: the reason we don't simply use expression_tree_walker() is that the
* point of that function is to support tree walkers that don't care about
* most tree node types, but here we care about all types. We should complain
* about any unrecognized node type.
*/
void pgqpJumbleExpr(pgqpJumbleState *jstate, Node *node) {
ListCell *temp;
if (node == NULL)
return;
/* Guard against stack overflow due to overly complex expressions */
check_stack_depth();
/*
* We always emit the node's NodeTag, then any additional fields that are
* considered significant, and then we recurse to any child nodes.
*/
PGQP_APP_JUMB(node->type);
switch (nodeTag(node)) {
case T_Var: {
Var *var = (Var *)node;
PGQP_APP_JUMB(var->varno);
PGQP_APP_JUMB(var->varattno);
PGQP_APP_JUMB(var->varlevelsup);
} break;
case T_Const: {
Const *c = (Const *)node;
/* We jumble only the constant's type, not its value */
PGQP_APP_JUMB(c->consttype);
/* Also, record its parse location for query normalization */
pgqpRecordConstLocation(jstate, c->location);
} break;
case T_Param: {
Param *p = (Param *)node;
PGQP_APP_JUMB(p->paramkind);
PGQP_APP_JUMB(p->paramid);
PGQP_APP_JUMB(p->paramtype);
/* Also, track the highest external Param id */
if (p->paramkind == PARAM_EXTERN &&
p->paramid > jstate->highest_extern_param_id)
jstate->highest_extern_param_id = p->paramid;
} break;
case T_Aggref: {
Aggref *expr = (Aggref *)node;
PGQP_APP_JUMB(expr->aggfnoid);
pgqpJumbleExpr(jstate, (Node *)expr->aggdirectargs);
pgqpJumbleExpr(jstate, (Node *)expr->args);
pgqpJumbleExpr(jstate, (Node *)expr->aggorder);
pgqpJumbleExpr(jstate, (Node *)expr->aggdistinct);
pgqpJumbleExpr(jstate, (Node *)expr->aggfilter);
} break;
case T_GroupingFunc: {
GroupingFunc *grpnode = (GroupingFunc *)node;
pgqpJumbleExpr(jstate, (Node *)grpnode->refs);
} break;
case T_WindowFunc: {
WindowFunc *expr = (WindowFunc *)node;
PGQP_APP_JUMB(expr->winfnoid);
PGQP_APP_JUMB(expr->winref);
pgqpJumbleExpr(jstate, (Node *)expr->args);
pgqpJumbleExpr(jstate, (Node *)expr->aggfilter);
} break;
#if PG_VERSION_NUM >= 120000
case T_SubscriptingRef: {
SubscriptingRef *sbsref = (SubscriptingRef *)node;
pgqpJumbleExpr(jstate, (Node *)sbsref->refupperindexpr);
pgqpJumbleExpr(jstate, (Node *)sbsref->reflowerindexpr);
pgqpJumbleExpr(jstate, (Node *)sbsref->refexpr);
pgqpJumbleExpr(jstate, (Node *)sbsref->refassgnexpr);
} break;
#else
case T_ArrayRef: {
ArrayRef *aref = (ArrayRef *)node;
pgqpJumbleExpr(jstate, (Node *)aref->refupperindexpr);
pgqpJumbleExpr(jstate, (Node *)aref->reflowerindexpr);
pgqpJumbleExpr(jstate, (Node *)aref->refexpr);
pgqpJumbleExpr(jstate, (Node *)aref->refassgnexpr);
} break;
#endif
case T_FuncExpr: {
FuncExpr *expr = (FuncExpr *)node;
PGQP_APP_JUMB(expr->funcid);
pgqpJumbleExpr(jstate, (Node *)expr->args);
} break;
case T_NamedArgExpr: {
NamedArgExpr *nae = (NamedArgExpr *)node;
PGQP_APP_JUMB(nae->argnumber);
pgqpJumbleExpr(jstate, (Node *)nae->arg);
} break;
case T_OpExpr:
case T_DistinctExpr: /* struct-equivalent to OpExpr */
case T_NullIfExpr: /* struct-equivalent to OpExpr */
{
OpExpr *expr = (OpExpr *)node;
PGQP_APP_JUMB(expr->opno);
pgqpJumbleExpr(jstate, (Node *)expr->args);
} break;
case T_ScalarArrayOpExpr: {
ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *)node;
PGQP_APP_JUMB(expr->opno);
PGQP_APP_JUMB(expr->useOr);
pgqpJumbleExpr(jstate, (Node *)expr->args);
} break;
case T_BoolExpr: {
BoolExpr *expr = (BoolExpr *)node;
PGQP_APP_JUMB(expr->boolop);
pgqpJumbleExpr(jstate, (Node *)expr->args);
} break;
case T_SubLink: {
SubLink *sublink = (SubLink *)node;
PGQP_APP_JUMB(sublink->subLinkType);
PGQP_APP_JUMB(sublink->subLinkId);
pgqpJumbleExpr(jstate, (Node *)sublink->testexpr);
pgqpJumbleQuery(jstate, castNode(Query, sublink->subselect));
} break;
case T_FieldSelect: {
FieldSelect *fs = (FieldSelect *)node;
PGQP_APP_JUMB(fs->fieldnum);
pgqpJumbleExpr(jstate, (Node *)fs->arg);
} break;
case T_FieldStore: {
FieldStore *fstore = (FieldStore *)node;
pgqpJumbleExpr(jstate, (Node *)fstore->arg);
pgqpJumbleExpr(jstate, (Node *)fstore->newvals);
} break;
case T_RelabelType: {
RelabelType *rt = (RelabelType *)node;
PGQP_APP_JUMB(rt->resulttype);
pgqpJumbleExpr(jstate, (Node *)rt->arg);
} break;
case T_CoerceViaIO: {
CoerceViaIO *cio = (CoerceViaIO *)node;
PGQP_APP_JUMB(cio->resulttype);
pgqpJumbleExpr(jstate, (Node *)cio->arg);
} break;
case T_ArrayCoerceExpr: {
ArrayCoerceExpr *acexpr = (ArrayCoerceExpr *)node;
PGQP_APP_JUMB(acexpr->resulttype);
pgqpJumbleExpr(jstate, (Node *)acexpr->arg);
pgqpJumbleExpr(jstate, (Node *)acexpr->elemexpr);
} break;
case T_ConvertRowtypeExpr: {
ConvertRowtypeExpr *crexpr = (ConvertRowtypeExpr *)node;
PGQP_APP_JUMB(crexpr->resulttype);
pgqpJumbleExpr(jstate, (Node *)crexpr->arg);
} break;
case T_CollateExpr: {
CollateExpr *ce = (CollateExpr *)node;
PGQP_APP_JUMB(ce->collOid);
pgqpJumbleExpr(jstate, (Node *)ce->arg);
} break;
case T_CaseExpr: {
CaseExpr *caseexpr = (CaseExpr *)node;
pgqpJumbleExpr(jstate, (Node *)caseexpr->arg);
foreach (temp, caseexpr->args) {
CaseWhen *when = lfirst_node(CaseWhen, temp);
pgqpJumbleExpr(jstate, (Node *)when->expr);
pgqpJumbleExpr(jstate, (Node *)when->result);
}
pgqpJumbleExpr(jstate, (Node *)caseexpr->defresult);
} break;
case T_CaseTestExpr: {
CaseTestExpr *ct = (CaseTestExpr *)node;
PGQP_APP_JUMB(ct->typeId);
} break;
case T_ArrayExpr:
pgqpJumbleExpr(jstate, (Node *)((ArrayExpr *)node)->elements);
break;
case T_RowExpr:
pgqpJumbleExpr(jstate, (Node *)((RowExpr *)node)->args);
break;
case T_RowCompareExpr: {
RowCompareExpr *rcexpr = (RowCompareExpr *)node;
PGQP_APP_JUMB(rcexpr->rctype);
pgqpJumbleExpr(jstate, (Node *)rcexpr->largs);
pgqpJumbleExpr(jstate, (Node *)rcexpr->rargs);
} break;
case T_CoalesceExpr:
pgqpJumbleExpr(jstate, (Node *)((CoalesceExpr *)node)->args);
break;
case T_MinMaxExpr: {
MinMaxExpr *mmexpr = (MinMaxExpr *)node;
PGQP_APP_JUMB(mmexpr->op);
pgqpJumbleExpr(jstate, (Node *)mmexpr->args);
} break;
case T_SQLValueFunction: {
SQLValueFunction *svf = (SQLValueFunction *)node;
PGQP_APP_JUMB(svf->op);
/* type is fully determined by op */
PGQP_APP_JUMB(svf->typmod);
} break;
case T_XmlExpr: {
XmlExpr *xexpr = (XmlExpr *)node;
PGQP_APP_JUMB(xexpr->op);
pgqpJumbleExpr(jstate, (Node *)xexpr->named_args);
pgqpJumbleExpr(jstate, (Node *)xexpr->args);
} break;
case T_NullTest: {
NullTest *nt = (NullTest *)node;
PGQP_APP_JUMB(nt->nulltesttype);
pgqpJumbleExpr(jstate, (Node *)nt->arg);
} break;
case T_BooleanTest: {
BooleanTest *bt = (BooleanTest *)node;
PGQP_APP_JUMB(bt->booltesttype);
pgqpJumbleExpr(jstate, (Node *)bt->arg);
} break;
case T_CoerceToDomain: {
CoerceToDomain *cd = (CoerceToDomain *)node;
PGQP_APP_JUMB(cd->resulttype);
pgqpJumbleExpr(jstate, (Node *)cd->arg);
} break;
case T_CoerceToDomainValue: {
CoerceToDomainValue *cdv = (CoerceToDomainValue *)node;
PGQP_APP_JUMB(cdv->typeId);
} break;
case T_SetToDefault: {
SetToDefault *sd = (SetToDefault *)node;
PGQP_APP_JUMB(sd->typeId);
} break;
case T_CurrentOfExpr: {
CurrentOfExpr *ce = (CurrentOfExpr *)node;
PGQP_APP_JUMB(ce->cvarno);
if (ce->cursor_name)
PGQP_APP_JUMB_STRING(ce->cursor_name);
PGQP_APP_JUMB(ce->cursor_param);
} break;
case T_NextValueExpr: {
NextValueExpr *nve = (NextValueExpr *)node;
PGQP_APP_JUMB(nve->seqid);
PGQP_APP_JUMB(nve->typeId);
} break;
case T_InferenceElem: {
InferenceElem *ie = (InferenceElem *)node;
PGQP_APP_JUMB(ie->infercollid);
PGQP_APP_JUMB(ie->inferopclass);
pgqpJumbleExpr(jstate, ie->expr);
} break;
case T_TargetEntry: {
TargetEntry *tle = (TargetEntry *)node;
PGQP_APP_JUMB(tle->resno);
PGQP_APP_JUMB(tle->ressortgroupref);
pgqpJumbleExpr(jstate, (Node *)tle->expr);
} break;
case T_RangeTblRef: {
RangeTblRef *rtr = (RangeTblRef *)node;
PGQP_APP_JUMB(rtr->rtindex);
} break;
case T_JoinExpr: {
JoinExpr *join = (JoinExpr *)node;
PGQP_APP_JUMB(join->jointype);
PGQP_APP_JUMB(join->isNatural);
PGQP_APP_JUMB(join->rtindex);
pgqpJumbleExpr(jstate, join->larg);
pgqpJumbleExpr(jstate, join->rarg);
pgqpJumbleExpr(jstate, join->quals);
} break;
case T_FromExpr: {
FromExpr *from = (FromExpr *)node;
pgqpJumbleExpr(jstate, (Node *)from->fromlist);
pgqpJumbleExpr(jstate, from->quals);
} break;
case T_OnConflictExpr: {
OnConflictExpr *conf = (OnConflictExpr *)node;
PGQP_APP_JUMB(conf->action);
pgqpJumbleExpr(jstate, (Node *)conf->arbiterElems);
pgqpJumbleExpr(jstate, conf->arbiterWhere);
pgqpJumbleExpr(jstate, (Node *)conf->onConflictSet);
pgqpJumbleExpr(jstate, conf->onConflictWhere);
PGQP_APP_JUMB(conf->constraint);
PGQP_APP_JUMB(conf->exclRelIndex);
pgqpJumbleExpr(jstate, (Node *)conf->exclRelTlist);
} break;
case T_List:
foreach (temp, (List *)node) {
pgqpJumbleExpr(jstate, (Node *)lfirst(temp));
}
break;
case T_IntList:
foreach (temp, (List *)node) {
PGQP_APP_JUMB(lfirst_int(temp));
}
break;
case T_SortGroupClause: {
SortGroupClause *sgc = (SortGroupClause *)node;
PGQP_APP_JUMB(sgc->tleSortGroupRef);
PGQP_APP_JUMB(sgc->eqop);
PGQP_APP_JUMB(sgc->sortop);
PGQP_APP_JUMB(sgc->nulls_first);
} break;
case T_GroupingSet: {
GroupingSet *gsnode = (GroupingSet *)node;
pgqpJumbleExpr(jstate, (Node *)gsnode->content);
} break;
case T_WindowClause: {
WindowClause *wc = (WindowClause *)node;
PGQP_APP_JUMB(wc->winref);
PGQP_APP_JUMB(wc->frameOptions);
pgqpJumbleExpr(jstate, (Node *)wc->partitionClause);
pgqpJumbleExpr(jstate, (Node *)wc->orderClause);
pgqpJumbleExpr(jstate, wc->startOffset);
pgqpJumbleExpr(jstate, wc->endOffset);
} break;
case T_CommonTableExpr: {
CommonTableExpr *cte = (CommonTableExpr *)node;
/* we store the string name because RTE_CTE RTEs need it */
PGQP_APP_JUMB_STRING(cte->ctename);
#if PG_VERSION_NUM >= 120000
PGQP_APP_JUMB(cte->ctematerialized);
#endif
pgqpJumbleQuery(jstate, castNode(Query, cte->ctequery));
} break;
case T_SetOperationStmt: {
SetOperationStmt *setop = (SetOperationStmt *)node;
PGQP_APP_JUMB(setop->op);
PGQP_APP_JUMB(setop->all);
pgqpJumbleExpr(jstate, setop->larg);
pgqpJumbleExpr(jstate, setop->rarg);
} break;
case T_RangeTblFunction: {
RangeTblFunction *rtfunc = (RangeTblFunction *)node;
pgqpJumbleExpr(jstate, rtfunc->funcexpr);
} break;
case T_TableFunc: {
TableFunc *tablefunc = (TableFunc *)node;
pgqpJumbleExpr(jstate, tablefunc->docexpr);
pgqpJumbleExpr(jstate, tablefunc->rowexpr);
pgqpJumbleExpr(jstate, (Node *)tablefunc->colexprs);
} break;
case T_TableSampleClause: {
TableSampleClause *tsc = (TableSampleClause *)node;
PGQP_APP_JUMB(tsc->tsmhandler);
pgqpJumbleExpr(jstate, (Node *)tsc->args);
pgqpJumbleExpr(jstate, (Node *)tsc->repeatable);
} break;
default:
/* Only a warning, since we can stumble along anyway */
elog(WARNING, "unrecognized node type: %d", (int)nodeTag(node));
break;
}
}
/*
* Record location of constant within query string of query tree
* that is currently being walked.
*/
void pgqpRecordConstLocation(pgqpJumbleState *jstate, int location) {
/* -1 indicates unknown or undefined location */
if (location >= 0) {
/* enlarge array if needed */
if (jstate->clocations_count >= jstate->clocations_buf_size) {
jstate->clocations_buf_size *= 2;
jstate->clocations = (pgqpLocationLen *)repalloc(
jstate->clocations,
jstate->clocations_buf_size * sizeof(pgqpLocationLen));
}
jstate->clocations[jstate->clocations_count].location = location;
/* initialize lengths to -1 to simplify pgqp_fill_in_constant_lengths */
jstate->clocations[jstate->clocations_count].length = -1;
jstate->clocations_count++;
}
}
/*
* Generate a normalized version of the query string that will be used to
* represent all similar queries.
*
* Note that the normalized representation may well vary depending on
* just which "equivalent" query is used to create the hashtable entry.
* We assume this is OK.
*
* If query_loc > 0, then "query" has been advanced by that much compared to
* the original string start, so we need to translate the provided locations
* to compensate. (This lets us avoid re-scanning statements before the one
* of interest, so it's worth doing.)
*
* *query_len_p contains the input string length, and is updated with
* the result string length on exit. The resulting string might be longer
* or shorter depending on what happens with replacement of constants.
*
* Returns a palloc'd string.
*/
char *pgqp_gen_normquery(pgqpJumbleState *jstate, const char *query, int query_loc,
int *query_len_p) {
char *norm_query;
int query_len = *query_len_p;
int i, norm_query_buflen, /* Space allowed for norm_query */
len_to_wrt, /* Length (in bytes) to write */
quer_loc = 0, /* Source query byte location */
n_quer_loc = 0, /* Normalized query byte location */
last_off = 0, /* Offset from start for previous tok */
last_tok_len = 0; /* Length (in bytes) of that tok */
/*
* Get constants' lengths (core system only gives us locations). Note
* this also ensures the items are sorted by location.
*/
pgqp_fill_in_constant_lengths(jstate, query, query_loc);
/*
* Allow for $n symbols to be longer than the constants they replace.
* Constants must take at least one byte in text form, while a $n symbol
* certainly isn't more than 11 bytes, even if n reaches INT_MAX. We
* could refine that limit based on the max value of n for the current
* query, but it hardly seems worth any extra effort to do so.
*/
norm_query_buflen = query_len + jstate->clocations_count * 10;
/* Allocate result buffer */
norm_query = palloc(norm_query_buflen + 1);
for (i = 0; i < jstate->clocations_count; i++) {
int off, /* Offset from start for cur tok */
tok_len; /* Length (in bytes) of that tok */
off = jstate->clocations[i].location;
/* Adjust recorded location if we're dealing with partial string */
off -= query_loc;
tok_len = jstate->clocations[i].length;
if (tok_len < 0)
continue; /* ignore any duplicates */
/* Copy next chunk (what precedes the next constant) */
len_to_wrt = off - last_off;
len_to_wrt -= last_tok_len;
pgqpAssert(len_to_wrt >= 0);
memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
n_quer_loc += len_to_wrt;
/* And insert a param symbol in place of the constant token */
n_quer_loc += sprintf(norm_query + n_quer_loc, "$%d",
i + 1 + jstate->highest_extern_param_id);
quer_loc = off + tok_len;
last_off = off;
last_tok_len = tok_len;
}
/*
* We've copied up until the last ignorable constant. Copy over the
* remaining bytes of the original query string.
*/
len_to_wrt = query_len - quer_loc;
pgqpAssert(len_to_wrt >= 0);
memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
n_quer_loc += len_to_wrt;
pgqpAssert(n_quer_loc <= norm_query_buflen);
norm_query[n_quer_loc] = '\0';
*query_len_p = n_quer_loc;
return norm_query;
}
/*
* Given a valid SQL string and an array of constant-location records,
* fill in the textual lengths of those constants.
*
* The constants may use any allowed constant syntax, such as float literals,
* bit-strings, single-quoted strings and dollar-quoted strings. This is
* accomplished by using the public API for the core scanner.
*
* It is the caller's job to ensure that the string is a valid SQL statement
* with constants at the indicated locations. Since in practice the string
* has already been parsed, and the locations that the caller provides will
* have originated from within the authoritative parser, this should not be
* a problem.
*
* Duplicate constant pointers are possible, and will have their lengths
* marked as '-1', so that they are later ignored. (Actually, we assume the
* lengths were initialized as -1 to start with, and don't change them here.)
*
* If query_loc > 0, then "query" has been advanced by that much compared to
* the original string start, so we need to translate the provided locations
* to compensate. (This lets us avoid re-scanning statements before the one
* of interest, so it's worth doing.)
*
* N.B. There is an assumption that a '-' character at a Const location begins
* a negative numeric constant. This precludes there ever being another
* reason for a constant to start with a '-'.
*/
void pgqp_fill_in_constant_lengths(pgqpJumbleState *jstate, const char *query,
int query_loc) {
pgqpLocationLen *locs;
core_yyscan_t yyscanner;
core_yy_extra_type yyextra;
core_YYSTYPE yylval;
YYLTYPE yylloc;
int last_loc = -1;
int i;
/*
* Sort the records by location so that we can process them in order while
* scanning the query text.
*/
if (jstate->clocations_count > 1)
qsort(jstate->clocations, jstate->clocations_count, sizeof(pgqpLocationLen),
pgqp_comp_location);
locs = jstate->clocations;
/* initialize the flex scanner --- should match raw_parser() */
yyscanner = scanner_init(query, &yyextra,
#if PG_VERSION_NUM >= 120000
&ScanKeywords, ScanKeywordTokens
#else
ScanKeywords, NumScanKeywords
#endif
);
/* we don't want to re-emit any escape string warnings */
yyextra.escape_string_warning = false;
/* Search for each constant, in sequence */
for (i = 0; i < jstate->clocations_count; i++) {
int loc = locs[i].location;
int tok;
/* Adjust recorded location if we're dealing with partial string */
loc -= query_loc;
pgqpAssert(loc >= 0);
if (loc <= last_loc)
continue; /* Duplicate constant, ignore */
/* Lex tokens until we find the desired constant */
for (;;) {
tok = core_yylex(&yylval, &yylloc, yyscanner);
/* We should not hit end-of-string, but if we do, behave sanely */
if (tok == 0)
break; /* out of inner for-loop */
/*
* We should find the token position exactly, but if we somehow
* run past it, work with that.
*/
if (yylloc >= loc) {
if (query[loc] == '-') {
/*
* It's a negative value - this is the one and only case
* where we replace more than a single token.
*
* Do not compensate for the core system's special-case
* adjustment of location to that of the leading '-'
* operator in the event of a negative constant. It is
* also useful for our purposes to start from the minus
* symbol. In this way, queries like "select * from foo
* where bar = 1" and "select * from foo where bar = -2"
* will have identical normalized query strings.
*/
tok = core_yylex(&yylval, &yylloc, yyscanner);
if (tok == 0)
break; /* out of inner for-loop */
}
/*
* We now rely on the assumption that flex has placed a zero
* byte after the text of the current token in scanbuf.
*/
locs[i].length = strlen(yyextra.scanbuf + loc);
break; /* out of inner for-loop */
}
}
/* If we hit end-of-string, give up, leaving remaining lengths -1 */
if (tok == 0)
break;
last_loc = loc;
}
scanner_finish(yyscanner);
}
/*
* pgqp_comp_location: comparator for qsorting pgqpLocationLen structs by location
*/
int pgqp_comp_location(const void *a, const void *b) {
int l = ((const pgqpLocationLen *)a)->location;
int r = ((const pgqpLocationLen *)b)->location;
if (l < r)
return -1;
else if (l > r)
return +1;
else
return 0;
}
#else
char *pgqp_gen_normquery(JumbleState *jstate, const char *query, int query_loc,
int *query_len_p) {
char *norm_query;
int query_len = *query_len_p;
int i, norm_query_buflen, /* Space allowed for norm_query */
len_to_wrt, /* Length (in bytes) to write */
quer_loc = 0, /* Source query byte location */
n_quer_loc = 0, /* Normalized query byte location */
last_off = 0, /* Offset from start for previous tok */
last_tok_len = 0; /* Length (in bytes) of that tok */
/*
* Get constants' lengths (core system only gives us locations). Note
* this also ensures the items are sorted by location.
*/
pgqp_fill_in_constant_lengths(jstate, query, query_loc);
/*
* Allow for $n symbols to be longer than the constants they replace.
* Constants must take at least one byte in text form, while a $n symbol
* certainly isn't more than 11 bytes, even if n reaches INT_MAX. We
* could refine that limit based on the max value of n for the current
* query, but it hardly seems worth any extra effort to do so.
*/
norm_query_buflen = query_len + jstate->clocations_count * 10;
/* Allocate result buffer */
norm_query = palloc(norm_query_buflen + 1);
for (i = 0; i < jstate->clocations_count; i++) {
int off, /* Offset from start for cur tok */
tok_len; /* Length (in bytes) of that tok */
off = jstate->clocations[i].location;
/* Adjust recorded location if we're dealing with partial string */
off -= query_loc;
tok_len = jstate->clocations[i].length;
if (tok_len < 0)
continue; /* ignore any duplicates */
/* Copy next chunk (what precedes the next constant) */
len_to_wrt = off - last_off;
len_to_wrt -= last_tok_len;
pgqpAssert(len_to_wrt >= 0);
memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
n_quer_loc += len_to_wrt;
/* And insert a param symbol in place of the constant token */
n_quer_loc += sprintf(norm_query + n_quer_loc, "$%d",
i + 1 + jstate->highest_extern_param_id);
quer_loc = off + tok_len;
last_off = off;
last_tok_len = tok_len;
}
/*
* We've copied up until the last ignorable constant. Copy over the
* remaining bytes of the original query string.
*/
len_to_wrt = query_len - quer_loc;
pgqpAssert(len_to_wrt >= 0);
memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
n_quer_loc += len_to_wrt;
pgqpAssert(n_quer_loc <= norm_query_buflen);
norm_query[n_quer_loc] = '\0';
*query_len_p = n_quer_loc;
return norm_query;
};
/*
* Given a valid SQL string and an array of constant-location records,
* fill in the textual lengths of those constants.
*
* The constants may use any allowed constant syntax, such as float literals,
* bit-strings, single-quoted strings and dollar-quoted strings. This is
* accomplished by using the public API for the core scanner.
*
* It is the caller's job to ensure that the string is a valid SQL statement
* with constants at the indicated locations. Since in practice the string
* has already been parsed, and the locations that the caller provides will
* have originated from within the authoritative parser, this should not be
* a problem.
*
* Duplicate constant pointers are possible, and will have their lengths
* marked as '-1', so that they are later ignored. (Actually, we assume the
* lengths were initialized as -1 to start with, and don't change them here.)
*
* If query_loc > 0, then "query" has been advanced by that much compared to
* the original string start, so we need to translate the provided locations
* to compensate. (This lets us avoid re-scanning statements before the one
* of interest, so it's worth doing.)
*
* N.B. There is an assumption that a '-' character at a Const location begins
* a negative numeric constant. This precludes there ever being another
* reason for a constant to start with a '-'.
*/
void pgqp_fill_in_constant_lengths(JumbleState *jstate, const char *query,
int query_loc) {
LocationLen *locs;
core_yyscan_t yyscanner;
core_yy_extra_type yyextra;
core_YYSTYPE yylval;
YYLTYPE yylloc;
int last_loc = -1;
int i;
/*
* Sort the records by location so that we can process them in order while
* scanning the query text.
*/
if (jstate->clocations_count > 1)
qsort(jstate->clocations, jstate->clocations_count, sizeof(LocationLen),
pgqp_comp_location);
locs = jstate->clocations;
/* initialize the flex scanner --- should match raw_parser() */
yyscanner = scanner_init(query, &yyextra, &ScanKeywords, ScanKeywordTokens);
/* we don't want to re-emit any escape string warnings */
yyextra.escape_string_warning = false;
/* Search for each constant, in sequence */
for (i = 0; i < jstate->clocations_count; i++) {
int loc = locs[i].location;
int tok;
/* Adjust recorded location if we're dealing with partial string */
loc -= query_loc;
pgqpAssert(loc >= 0);
if (loc <= last_loc)
continue; /* Duplicate constant, ignore */
/* Lex tokens until we find the desired constant */
for (;;) {
tok = core_yylex(&yylval, &yylloc, yyscanner);
/* We should not hit end-of-string, but if we do, behave sanely */
if (tok == 0)
break; /* out of inner for-loop */
/*
* We should find the token position exactly, but if we somehow
* run past it, work with that.
*/
if (yylloc >= loc) {
if (query[loc] == '-') {
/*
* It's a negative value - this is the one and only case
* where we replace more than a single token.
*
* Do not compensate for the core system's special-case
* adjustment of location to that of the leading '-'
* operator in the event of a negative constant. It is
* also useful for our purposes to start from the minus
* symbol. In this way, queries like "select * from foo
* where bar = 1" and "select * from foo where bar = -2"
* will have identical normalized query strings.
*/
tok = core_yylex(&yylval, &yylloc, yyscanner);
if (tok == 0)
break; /* out of inner for-loop */
}
/*