-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpg_stat_query_plans.c
1557 lines (1365 loc) · 52.5 KB
/
pg_stat_query_plans.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_stat_query_plans.c
* Track statement planning and execution times as well as resource
* usage across a whole database cluster.
*
* Execution costs are totaled for each distinct source query, and kept in
* a shared hashtable. (We track only as many distinct queries as will fit
* in the designated amount of shared memory.)
*
* Like original pg_stat_query_plans this module normalized query entries. As of
* Postgres 14, the normalization is done by the core if compute_query_id is
* enabled, or optionally by third-party modules.
*
* To facilitate presenting entries to users, we create "representative" query
* strings in which constants are replaced with parameter symbols ($n), to
* make it clearer what a normalized entry can represent. To save on shared
* memory, and to avoid having to truncate oversized query strings, all texts
* are comoressed.
*
* Note about locking issues: to create or delete an entry in the shared
* hashtable, one must hold pgqp->lock exclusively. Modifying any field
* in an entry except the counters requires the same. To look up an entry,
* one must hold the lock shared. To read or update the counters within
* an entry, one must hold the lock shared or exclusive (so the entry doesn't
* disappear!) and also take the entry's mutex spinlock.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <math.h>
#include <sys/stat.h>
#include <unistd.h>
#include "access/parallel.h"
#include "catalog/pg_authid.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 "commands/explain.h"
#include "executor/instrument.h"
#include "funcapi.h"
#include "jit/jit.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/planner.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/scanner.h"
#include "parser/scansup.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/shmem.h"
#include "storage/spin.h"
#include "tcop/utility.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM >= 140000 && PG_VERSION_NUM < 160000
#include "utils/queryjumble.h"
#endif
#if PG_VERSION_NUM >= 160000
#include "nodes/queryjumble.h"
#endif
#if PG_VERSION_NUM < 120000
#include "access/htup_details.h"
#endif
#include "pg_stat_query_plans_common.h"
#include "pg_stat_query_plans_parser.h"
#include "pg_stat_query_plans_storage.h"
#include "pg_stat_query_plans_assert.h"
#include "utils/errcodes.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(pg_stat_query_plans_reset_queryid);
PG_FUNCTION_INFO_V1(pg_stat_query_plans_reset_minmax);
PG_FUNCTION_INFO_V1(pg_stat_query_plans_sql_1_0);
PG_FUNCTION_INFO_V1(pg_stat_query_plans_plans_1_0);
PG_FUNCTION_INFO_V1(pg_stat_query_plans_info);
/*---- Global variables ----*/
/* Current nesting depth of ExecutorRun+ProcessUtility calls */
int pgqp_exec_nested_level = 0;
/* Current nesting depth of planner calls */
int pgqp_plan_nested_level = 0;
const struct config_enum_entry track_options[] = {
{"none", PGQP_TRACK_NONE, false},
{"top", PGQP_TRACK_TOP, false},
{"all", PGQP_TRACK_ALL, false},
{NULL, 0, false}};
const struct config_enum_entry plan_formats[] = {
{"text", EXPLAIN_FORMAT_TEXT, false},
{"json", EXPLAIN_FORMAT_JSON, false},
{"yaml", EXPLAIN_FORMAT_YAML, false},
{"xml", EXPLAIN_FORMAT_XML, false},
{NULL, 0, false}};
const struct config_enum_entry text_encodings[] = {
{"plaintext", PGQP_PLAINTEXT, false},
{"pglz", PGQP_PGLZ, false},
{NULL, 0, false}};
/*---- Local vriables ----*/
/* Saved hook values in case of unload */
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
static planner_hook_type prev_planner_hook = NULL;
static ExecutorStart_hook_type prev_ExecutorStart = NULL;
static ExecutorRun_hook_type prev_ExecutorRun = NULL;
static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
/* Links to shared memory state */
pgqpSharedState *pgqp = NULL;
HTAB *pgqp_queries = NULL;
HTAB *pgqp_plans = NULL;
HTAB *pgqp_texts = NULL;
char *pgqp_storage = NULL;
const int MEAN_PLANS_PER_QUERY = 2;
int pgqp_max; /* max # statements to track */
int pgqp_max_plans; /* max # plans to track */
int pgqp_storage_memory; /* memory used to store plan and query texts */
int pgqp_max_query_len; /* maximum query text length */
int pgqp_max_plan_len; /* maximum execution plan text length */
int pgqp_track = PGQP_TRACK_ALL; /* tracking level */
int pgqp_encoding = PGQP_PGLZ; /* compress stored texts */
bool pgqp_track_utility; /* whether to track utility commands */
bool pgqp_track_planning; /* whether to track planning duration */
bool pgqp_track_plans; /* track execution plans or not */
bool pgqp_normalize_plans; /* Normalize plans so pans differ in constans have
the same planId */
int example_plan_format = EXPLAIN_FORMAT_JSON; /* Plan representation style */
bool example_log_verbose; /* Set VERBOSE for EXPLAIN on logging */
bool example_log_triggers; /* Log trigger trace in EXPLAIN */
/*---- Function declarations ----*/
void _PG_init(void);
void _PG_fini(void);
#if PG_VERSION_NUM >= 150000
static void pgqp_shmem_request(void);
#endif
static void pgqp_shmem_startup(void);
#if PG_VERSION_NUM >= 140000
static void pgqp_post_parse_analyze(ParseState *pstate, Query *query,
JumbleState *jstate);
#else
static void pgqp_post_parse_analyze(ParseState *pstate, Query *query);
#endif
#if PG_VERSION_NUM >= 130000
static PlannedStmt *pgqp_planner(Query *parse, const char *query_string,
int cursorOptions, ParamListInfo boundParams);
#endif
static void pgqp_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgqp_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
uint64 count, bool execute_once);
static void pgqp_ExecutorFinish(QueryDesc *queryDesc);
static void pgqp_ExecutorEnd(QueryDesc *queryDesc);
#if PG_VERSION_NUM >= 140000
static void pgqp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc);
#else
static void pgqp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
#if PG_VERSION_NUM >= 130000
QueryCompletion *qc
#else
char *qc
#endif
);
#endif
static int pgqp_add_counters_data(pgqpCounters *c, Datum values[0],
pgqpStoreKind start_kind);
static void pg_stat_query_plans_stat_internal(FunctionCallInfo fcinfo,
pgqpVersion api_version,
bool showtext);
static void pg_stat_query_plans_plan_internal(FunctionCallInfo fcinfo,
pgqpVersion api_version,
bool showtext);
static Size pgqp_memsize(void);
/*
* Module load callback
*/
void _PG_init(void) {
/*
* In order to create our shared memory area, we have to be loaded via
* shared_preload_libraries. If not, fall out without hooking into any of
* the main system. (We don't throw error here because it seems useful to
* allow the pg_stat_query_plans functions to be created even when the
* module isn't active. The functions must protect themselves against
* being called then, however.)
*/
if (!process_shared_preload_libraries_in_progress)
return;
/*
* Inform the postmaster that we want to enable query_id calculation if
* compute_query_id is set to auto.
*/
#if PG_VERSION_NUM >= 140000
EnableQueryId();
#endif
/*
* Define (or redefine) custom GUC variables.
*/
DefineCustomIntVariable(
"pg_stat_query_plans.max",
"Sets the maximum number of statements tracked by pg_stat_query_plans.",
NULL, &pgqp_max, 10000, 100, INT_MAX / 2, PGC_POSTMASTER, 0, NULL, NULL,
NULL);
DefineCustomIntVariable(
"pg_stat_query_plans.max_query_len",
"Sets the maximum length of query texts stored by pg_stat_query_plans.",
NULL, &pgqp_max_query_len, 4 * 1024 * 1024, 100, 6 * 1024 * 1024,
PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomIntVariable("pg_stat_query_plans.max_plan_size",
"Sets the maximum length of execution plan texts "
"stored by pg_stat_query_plans.",
NULL, &pgqp_max_plan_len, 6 * 1024 * 1024, 1024,
8 * 1024 * 1024, PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomIntVariable(
"pg_stat_query_plans.storage_memory",
"Sets the amount of memory used to store query and plan texts", NULL,
&pgqp_storage_memory, 256 * 1024 * 1024, 16 * 1024 * 1024, INT_MAX,
PGC_POSTMASTER, 0, NULL, NULL, NULL);
DefineCustomEnumVariable(
"pg_stat_query_plans.track",
"Selects which statements are tracked by pg_stat_query_plans.", NULL,
&pgqp_track, PGQP_TRACK_ALL, track_options, PGC_SUSET, 0, NULL, NULL,
NULL);
DefineCustomBoolVariable(
"pg_stat_query_plans.track_utility",
"Selects whether utility commands are tracked by pg_stat_query_plans.",
NULL, &pgqp_track_utility, true, PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomBoolVariable(
"pg_stat_query_plans.track_planning",
"Selects whether planning duration is tracked by pg_stat_query_plans.",
NULL, &pgqp_track_planning, false, PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomBoolVariable("pg_stat_query_plans.track_plans",
"Selects whether execution plans (texts and "
"statistics) is tracked by pg_stat_query_plans.",
NULL, &pgqp_track_plans, true, PGC_SUSET, 0, NULL,
NULL, NULL);
DefineCustomBoolVariable("pg_stat_query_plans.normalize_plans",
"Normalize plans - remove constants and unstable "
"values to generate the same planId.",
NULL, &pgqp_normalize_plans, true, PGC_SUSET, 0,
NULL, NULL, NULL);
DefineCustomEnumVariable("pg_stat_query_plans.pgqp_encoding",
"Set compression method for stored texts", NULL,
&pgqp_encoding, PGQP_PGLZ, text_encodings, PGC_SUSET,
0, NULL, NULL, NULL);
DefineCustomEnumVariable("pg_stat_query_plans.example_plan_format",
"Selects which format to be appied for plan "
"representation in pg_stat_query_plans.",
NULL, &example_plan_format, EXPLAIN_FORMAT_JSON,
plan_formats, PGC_SUSET, 0, NULL, NULL, NULL);
DefineCustomBoolVariable("pg_stat_query_plans.example_plan_verbose",
"Set VERBOSE for EXPLAIN on logging plan.", NULL,
&example_log_verbose, true, PGC_SUSET, 0, NULL, NULL,
NULL);
DefineCustomBoolVariable("pg_stat_query_plans.example_plan_triggers",
"Log trigger trace in EXPLAIN.", NULL,
&example_log_triggers, true, PGC_SUSET, 0, NULL,
NULL, NULL);
#if PG_VERSION_NUM >= 150000
MarkGUCPrefixReserved("pg_stat_query_plans");
#else
EmitWarningsOnPlaceholders("pg_stat_query_plans");
#endif
/*
* Install hooks.
*/
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgqp_shmem_request;
#else
/* Reserve memory there */
RequestAddinShmemSpace(pgqp_memsize());
RequestNamedLWLockTranche("pg_stat_query_plans", 1);
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgqp_shmem_startup;
prev_post_parse_analyze_hook = post_parse_analyze_hook;
post_parse_analyze_hook = pgqp_post_parse_analyze;
#if PG_VERSION_NUM >= 130000
prev_planner_hook = planner_hook;
planner_hook = pgqp_planner;
#endif
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgqp_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgqp_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgqp_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgqp_ExecutorEnd;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = pgqp_ProcessUtility;
}
/*
* Module unload callback
*/
void _PG_fini(void) {
/* Uninstall hooks. */
shmem_startup_hook = prev_shmem_startup_hook;
post_parse_analyze_hook = prev_post_parse_analyze_hook;
planner_hook = prev_planner_hook;
ExecutorStart_hook = prev_ExecutorStart;
ExecutorRun_hook = prev_ExecutorRun;
ExecutorFinish_hook = prev_ExecutorFinish;
ExecutorEnd_hook = prev_ExecutorEnd;
ProcessUtility_hook = prev_ProcessUtility;
}
#if PG_VERSION_NUM >= 150000
/*
* shmem_request hook: request additional shared resources. We'll allocate or
* attach to the shared resources in pgqp_shmem_startup().
*/
static void pgqp_shmem_request(void) {
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(pgqp_memsize());
RequestNamedLWLockTranche("pg_stat_query_plans", 1);
}
#endif
/*
* shmem_startup hook: allocate or attach to shared memory,
* then load any pre-existing statistics from file.
* Also create and load the query-texts file, which is expected to exist
* (even if empty) while the module is enabled.
*/
static void pgqp_shmem_startup(void) {
bool found;
HASHCTL info_queries;
HASHCTL info_plans;
HASHCTL info_texts;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pgqp = NULL;
pgqp_queries = NULL;
pgqp_plans = NULL;
pgqp_texts = NULL;
pgqp_storage = NULL;
/*
* Create or attach to the shared memory state, including hash table
*/
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
pgqp =
ShmemInitStruct("pg_stat_query_plans", sizeof(pgqpSharedState), &found);
if (!found) {
/* First time through ... */
pgqp->lock = &(GetNamedLWLockTranche("pg_stat_query_plans"))->lock;
// pgqp->memory_lock =
// &(GetNamedLWLockTranche("pg_stat_query_plans_memory"))->lock;
pgqp->storage_offset = 0;
pgqp->cur_median_usage = PGQP_ASSUMED_MEDIAN_INIT;
SpinLockInit(&pgqp->mutex);
pgqp->stats.dealloc = 0;
pgqp->stats.queries_wiped_out = 0;
pgqp->stats.plans_wiped_out = 0;
pgqp->stats.stats_reset = GetCurrentTimestamp();
pgqp->stats.queries_size = 0;
pgqp->stats.compressed_queries_size = 0;
pgqp->stats.plans_size = 0;
pgqp->stats.compressed_plans_size = 0;
pgqp->stats.dealloc_time_ms = 0;
pgqp->stats.gc_time_ms = 0;
}
info_queries.keysize = sizeof(pgqpQueryHashKey);
info_queries.entrysize = sizeof(pgqpEntry);
pgqp_queries = ShmemInitHash("pg_stat_query_plans hash", pgqp_max, pgqp_max,
&info_queries, HASH_ELEM | HASH_BLOBS);
pgqp_max_plans = pgqp_max * MEAN_PLANS_PER_QUERY;
info_plans.keysize = sizeof(pgqpPlanHashKey);
info_plans.entrysize = sizeof(pgqpPlanEntry);
pgqp_plans =
ShmemInitHash("pg_stat_query_plans_plans hash", pgqp_max_plans,
pgqp_max_plans, &info_plans, HASH_ELEM | HASH_BLOBS);
info_texts.keysize = sizeof(pgqpTextStorageKey);
info_texts.entrysize = sizeof(pgqpTextStorageEntry);
pgqp_texts = ShmemInitHash(
"pg_stat_query_plans texts", pgqp_max_plans*3 + pgqp_max,
pgqp_max_plans*3 + pgqp_max, &info_texts, HASH_ELEM | HASH_BLOBS);
pgqp_storage = ShmemInitStruct("pg_stat_query_plans storage",
pgqp_storage_memory, &found);
if (!found) {
/* Init storage */
memset(pgqp_storage, 0, pgqp_storage_memory);
}
LWLockRelease(AddinShmemInitLock);
return;
}
/*
* Post-parse-analysis hook: mark query with a queryId
*/
static void
#if PG_VERSION_NUM >= 140000
pgqp_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate)
#else
pgqp_post_parse_analyze(ParseState *pstate, Query *query)
#endif
{
#if PG_VERSION_NUM < 140000
pgqpJumbleState jstate;
#endif
if (prev_post_parse_analyze_hook)
#if PG_VERSION_NUM >= 140000
prev_post_parse_analyze_hook(pstate, query, jstate);
#else
prev_post_parse_analyze_hook(pstate, query);
#endif
/* Safety check... */
if (!pgqp || !pgqp_queries || !pgqp_plans || !pgqp_texts ||
!pgqp_enabled(pgqp_exec_nested_level))
return;
#if PG_VERSION_NUM < 140000
if (query->queryId != UINT64CONST(0))
return;
#endif
/*
* Clear queryId for prepared statements related utility, as those will
* inherit from the underlying statement's one (except DEALLOCATE which is
* entirely untracked).
*/
if (query->utilityStmt) {
if (pgqp_track_utility && !PGQP_HANDLED_UTILITY(query->utilityStmt))
query->queryId = UINT64CONST(0);
return;
}
#if PG_VERSION_NUM < 140000
/* Set up workspace for query jumbling */
jstate.jumble = (unsigned char *)palloc(JUMBLE_SIZE);
jstate.jumble_len = 0;
jstate.clocations_buf_size = 32;
jstate.clocations = (pgqpLocationLen *)palloc(jstate.clocations_buf_size *
sizeof(pgqpLocationLen));
jstate.clocations_count = 0;
jstate.highest_extern_param_id = 0;
/* Compute query ID and mark the Query node with it */
pgqpJumbleQuery(&jstate, query);
query->queryId =
DatumGetUInt64(hash_any_extended(jstate.jumble, jstate.jumble_len, 0));
/*
* If we are unlucky enough to get a hash of zero, use 1 instead, to
* prevent confusion with the utility-statement case.
*/
if (query->queryId == UINT64CONST(0))
query->queryId = UINT64CONST(1);
#endif
/*
* If query jumbling were able to identify any ignorable constants, we
* immediately create a hash table entry for the query, so that we can
* record the normalized form of the query string. If there were no such
* constants, the normalized string would be the same as the query text
* anyway, so there's no need for an early entry.
*/
#if PG_VERSION_NUM >= 140000
if (jstate && jstate->clocations_count > 0)
#else
if (jstate.clocations_count > 0)
#endif
pgqp_store(pstate->p_sourcetext, NULL, query->queryId, NULL,
query->stmt_location, query->stmt_len, PGQP_INVALID, 0, 0, NULL,
NULL, NULL,
#if PG_VERSION_NUM >= 140000
jstate
#else
&jstate
#endif
);
}
#if PG_VERSION_NUM >= 130000
/*
* Planner hook: forward to regular planner, but measure planning time
* if needed.
*/
static PlannedStmt *pgqp_planner(Query *parse, const char *query_string,
int cursorOptions, ParamListInfo boundParams) {
PlannedStmt *result;
/*
* We can't process the query if no query_string is provided, as
* pgqp_store needs it. We also ignore query without queryid, as it would
* be treated as a utility statement, which may not be the case.
*
* Note that planner_hook can be called from the planner itself, so we
* have a specific nesting level for the planner. However, utility
* commands containing optimizable statements can also call the planner,
* same for regular DML (for instance for underlying foreign key queries).
* So testing the planner nesting level only is not enough to detect real
* top level planner call.
*/
if (pgqp_enabled(pgqp_plan_nested_level + pgqp_exec_nested_level) &&
pgqp_track_planning && query_string && parse->queryId != UINT64CONST(0)) {
instr_time start;
instr_time duration;
BufferUsage bufusage_start, bufusage;
WalUsage walusage_start, walusage;
/* We need to track buffer usage as the planner can access them. */
bufusage_start = pgBufferUsage;
/*
* Similarly the planner could write some WAL records in some cases
* (e.g. setting a hint bit with those being WAL-logged)
*/
walusage_start = pgWalUsage;
INSTR_TIME_SET_CURRENT(start);
pgqp_plan_nested_level++;
PG_TRY();
{
if (prev_planner_hook)
result =
prev_planner_hook(parse, query_string, cursorOptions, boundParams);
else
result =
standard_planner(parse, query_string, cursorOptions, boundParams);
}
PG_FINALLY();
{ pgqp_plan_nested_level--; }
PG_END_TRY();
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
/* calc differences of buffer counters. */
memset(&bufusage, 0, sizeof(BufferUsage));
BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
/* calc differences of WAL counters. */
memset(&walusage, 0, sizeof(WalUsage));
WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
pgqp_store(query_string, NULL, parse->queryId, NULL, parse->stmt_location,
parse->stmt_len, PGQP_PLAN, INSTR_TIME_GET_MILLISEC(duration), 0,
&bufusage, &walusage, NULL, NULL);
} else {
if (prev_planner_hook)
result =
prev_planner_hook(parse, query_string, cursorOptions, boundParams);
else
result =
standard_planner(parse, query_string, cursorOptions, boundParams);
}
return result;
}
#endif
/*
* ExecutorStart hook: start up tracking if needed
*/
static void pgqp_ExecutorStart(QueryDesc *queryDesc, int eflags) {
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
/*
* If query has queryId zero, don't track it. This prevents double
* counting of optimizable statements that are directly contained in
* utility statements.
*/
if (pgqp_enabled(pgqp_exec_nested_level) &&
queryDesc->plannedstmt->queryId != UINT64CONST(0)) {
/*
* Set up to track total elapsed time in ExecutorRun. Make sure the
* space is allocated in the per-query context so it will go away at
* ExecutorEnd.
*/
if (queryDesc->totaltime == NULL) {
MemoryContext oldcxt;
oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
#if PG_VERSION_NUM >= 140000
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL, false);
#else
queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL);
#endif
MemoryContextSwitchTo(oldcxt);
}
}
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void pgqp_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction,
uint64 count, bool execute_once) {
pgqp_exec_nested_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
}
#if PG_VERSION_NUM < 130000
PG_CATCH();
{
pgqp_exec_nested_level--;
PG_RE_THROW();
}
#else
PG_FINALLY();
{ pgqp_exec_nested_level--; }
#endif
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void pgqp_ExecutorFinish(QueryDesc *queryDesc) {
pgqp_exec_nested_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
}
#if PG_VERSION_NUM < 130000
PG_CATCH();
{
pgqp_exec_nested_level--;
PG_RE_THROW();
}
#else
PG_FINALLY();
{ pgqp_exec_nested_level--; }
#endif
PG_END_TRY();
}
/*
* ExecutorEnd hook: store results if needed
*/
static void pgqp_ExecutorEnd(QueryDesc *queryDesc) {
uint64 queryId = queryDesc->plannedstmt->queryId;
ExplainState *es_planid;
StringInfo execution_plan = NULL;
MemoryContext myctx;
MemoryContext oldctx;
if (queryId != UINT64CONST(0) && queryDesc->totaltime &&
pgqp_enabled(pgqp_exec_nested_level)) {
/*
* Make sure stats accumulation is done. (Note: it's okay if several
* levels of hook all do this.)
*/
InstrEndLoop(queryDesc->totaltime);
/*
* Create new memory context to store intermediate data
*/
myctx = AllocSetContextCreate(CurrentMemoryContext, "PgssExecutorEndMemCtx", ALLOCSET_DEFAULT_SIZES);
oldctx = MemoryContextSwitchTo(myctx);
/*
* Calculate plan id value as hash os EXPLAIN PLAN text representation
* without costs and the number of rows. Changing costs does not mean
* changing execution plan - it could be changing statistics. Cost, the
* number of rows,width and other params will be stored in additional
* fields.
*/
if (pgqp_track_plans) {
es_planid = NewExplainState();
es_planid->costs = false;
es_planid->verbose = true;
es_planid->format = EXPLAIN_FORMAT_TEXT;
PG_TRY();
{
ExplainBeginOutput(es_planid);
ExplainPrintPlan(es_planid, queryDesc);
ExplainEndOutput(es_planid);
}
PG_CATCH();
{
resetStringInfo(es_planid->str);
appendStringInfo(es_planid->str, "Failed to generate plan info");
}
PG_END_TRY();
if (pgqp_normalize_plans) {
execution_plan = gen_normplan(es_planid->str->data);
} else {
execution_plan = es_planid->str;
}
}
pgqp_store(
queryDesc->sourceText, execution_plan, queryId, queryDesc,
queryDesc->plannedstmt->stmt_location, queryDesc->plannedstmt->stmt_len,
PGQP_EXEC, queryDesc->totaltime->total * 1000.0, /* convert to msec */
queryDesc->estate->es_processed, &queryDesc->totaltime->bufusage,
#if PG_VERSION_NUM >= 130000
&queryDesc->totaltime->walusage,
#else
NULL,
#endif
queryDesc->estate->es_jit ? &queryDesc->estate->es_jit->instr : NULL,
NULL);
/*
* Free context memory
*/
MemoryContextSwitchTo(oldctx);
MemoryContextDelete(myctx);
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
#if PG_VERSION_NUM >= 140000
/*
* ProcessUtility hook
*/
static void pgqp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
bool readOnlyTree,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
QueryCompletion *qc) {
Node *parsetree = pstmt->utilityStmt;
uint64 saved_queryId = pstmt->queryId;
/*
* Force utility statements to get queryId zero. We do this even in cases
* where the statement contains an optimizable statement for which a
* queryId could be derived (such as EXPLAIN or DECLARE CURSOR). For such
* cases, runtime control will first go through ProcessUtility and then
* the executor, and we don't want the executor hooks to do anything,
* since we are already measuring the statement's costs at the utility
* level.
*
* Note that this is only done if pg_stat_query_plans is enabled and
* configured to track utility statements, in the unlikely possibility
* that user configured another extension to handle utility statements
* only.
*/
if (pgqp_enabled(pgqp_exec_nested_level) && pgqp_track_utility)
pstmt->queryId = UINT64CONST(0);
/*
* If it's an EXECUTE statement, we don't track it and don't increment the
* nesting level. This allows the cycles to be charged to the underlying
* PREPARE instead (by the Executor hooks), which is much more useful.
*
* We also don't track execution of PREPARE. If we did, we would get one
* hash table entry for the PREPARE (with hash calculated from the query
* string), and then a different one with the same query string (but hash
* calculated from the query tree) would be used to accumulate costs of
* ensuing EXECUTEs. This would be confusing, and inconsistent with other
* cases where planning time is not included at all.
*
* Likewise, we don't track execution of DEALLOCATE.
*/
if (pgqp_track_utility && pgqp_enabled(pgqp_exec_nested_level) &&
PGQP_HANDLED_UTILITY(parsetree)) {
instr_time start;
instr_time duration;
uint64 rows;
BufferUsage bufusage_start, bufusage;
WalUsage walusage_start, walusage;
bufusage_start = pgBufferUsage;
walusage_start = pgWalUsage;
INSTR_TIME_SET_CURRENT(start);
pgqp_exec_nested_level++;
PG_TRY();
{
if (prev_ProcessUtility)
prev_ProcessUtility(pstmt, queryString, readOnlyTree, context, params,
queryEnv, dest, qc);
else
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context,
params, queryEnv, dest, qc);
}
PG_FINALLY();
{ pgqp_exec_nested_level--; }
PG_END_TRY();
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
/*
* Track the total number of rows retrieved or affected by the utility
* statements of COPY, FETCH, CREATE TABLE AS, CREATE MATERIALIZED
* VIEW, REFRESH MATERIALIZED VIEW and SELECT INTO.
*/
rows = (qc &&
(qc->commandTag == CMDTAG_COPY || qc->commandTag == CMDTAG_FETCH ||
qc->commandTag == CMDTAG_SELECT ||
qc->commandTag == CMDTAG_REFRESH_MATERIALIZED_VIEW))
? qc->nprocessed
: 0;
/* calc differences of buffer counters. */
memset(&bufusage, 0, sizeof(BufferUsage));
BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
/* calc differences of WAL counters. */
memset(&walusage, 0, sizeof(WalUsage));
WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
pgqp_store(queryString, NULL, saved_queryId, NULL, pstmt->stmt_location,
pstmt->stmt_len, PGQP_EXEC, INSTR_TIME_GET_MILLISEC(duration),
rows, &bufusage, &walusage, NULL, NULL);
} else {
if (prev_ProcessUtility)
prev_ProcessUtility(pstmt, queryString, readOnlyTree, context, params,
queryEnv, dest, qc);
else
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context, params,
queryEnv, dest, qc);
}
}
#else
/*
* ProcessUtility hook
*/
static void pgqp_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment *queryEnv, DestReceiver *dest,
#if PG_VERSION_NUM >= 130000
QueryCompletion *qc
#else
char *qc
#endif
) {
Node *parsetree = pstmt->utilityStmt;
/*
* If it's an EXECUTE statement, we don't track it and don't increment the
* nesting level. This allows the cycles to be charged to the underlying
* PREPARE instead (by the Executor hooks), which is much more useful.
*
* We also don't track execution of PREPARE. If we did, we would get one
* hash table entry for the PREPARE (with hash calculated from the query
* string), and then a different one with the same query string (but hash
* calculated from the query tree) would be used to accumulate costs of
* ensuing EXECUTEs. This would be confusing, and inconsistent with other
* cases where planning time is not included at all.
*
* Likewise, we don't track execution of DEALLOCATE.
*/
if (pgqp_track_utility && pgqp_enabled(pgqp_exec_nested_level) &&
!IsA(parsetree, ExecuteStmt) && !IsA(parsetree, PrepareStmt) &&
!IsA(parsetree, DeallocateStmt)) {
instr_time start;
instr_time duration;
uint64 rows;
BufferUsage bufusage_start, bufusage;
#if PG_VERSION_NUM >= 130000
WalUsage walusage_start, walusage;
#endif
bufusage_start = pgBufferUsage;
#if PG_VERSION_NUM >= 130000
walusage_start = pgWalUsage;
#endif
INSTR_TIME_SET_CURRENT(start);
pgqp_exec_nested_level++;
PG_TRY();
{
if (prev_ProcessUtility)
prev_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest,
qc);
else
standard_ProcessUtility(pstmt, queryString, context, params, queryEnv,
dest, qc);
}
#if PG_VERSION_NUM < 130000
PG_CATCH();
{
pgqp_exec_nested_level--;
PG_RE_THROW();
}
#else
PG_FINALLY();
{ pgqp_exec_nested_level--; }
#endif
PG_END_TRY();
INSTR_TIME_SET_CURRENT(duration);
INSTR_TIME_SUBTRACT(duration, start);
#if PG_VERSION_NUM >= 130000
rows = (qc && qc->commandTag == CMDTAG_COPY) ? qc->nprocessed : 0;
/* calc differences of buffer counters. */
memset(&bufusage, 0, sizeof(BufferUsage));
BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
/* calc differences of WAL counters. */
memset(&walusage, 0, sizeof(WalUsage));
WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
#else
/* parse command tag to retrieve the number of affected rows. */
if (qc && strncmp(qc, "COPY ", 5) == 0)
rows = pg_strtouint64(qc + 5, NULL, 10);
else
rows = 0;
/* calc differences of buffer counters. */
bufusage.shared_blks_hit =
pgBufferUsage.shared_blks_hit - bufusage_start.shared_blks_hit;
bufusage.shared_blks_read =
pgBufferUsage.shared_blks_read - bufusage_start.shared_blks_read;
bufusage.shared_blks_dirtied =
pgBufferUsage.shared_blks_dirtied - bufusage_start.shared_blks_dirtied;
bufusage.shared_blks_written =
pgBufferUsage.shared_blks_written - bufusage_start.shared_blks_written;
bufusage.local_blks_hit =
pgBufferUsage.local_blks_hit - bufusage_start.local_blks_hit;
bufusage.local_blks_read =
pgBufferUsage.local_blks_read - bufusage_start.local_blks_read;
bufusage.local_blks_dirtied =