-
Notifications
You must be signed in to change notification settings - Fork 26
/
pg_qualstats.c
2620 lines (2268 loc) · 69 KB
/
pg_qualstats.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_qualstats.c
* Track frequently used quals.
*
* This extension works by installing a hooks on executor.
* The ExecutorStart hook will enable some instrumentation for the
* queries (INSTRUMENT_ROWS and INSTRUMENT_BUFFERS).
*
* The ExecutorEnd hook will look for every qual in the query, and
* stores the quals of the form:
* - EXPR OPERATOR CONSTANT
* - EXPR OPERATOR EXPR
*
* If pg_stat_statements is available, the statistics will be
* aggregated by queryid, and a not-normalized statement will be
* stored for each different queryid. This can allow third part tools
* to do some work on a real query easily.
*
* The implementation is heavily inspired by pg_stat_statements
*
* Copyright (c) 2014,2017 Ronan Dunklau
* Copyright (c) 2018-2024, The Powa-Team
*-------------------------------------------------------------------------
*/
#include <limits.h>
#include <math.h>
#include "postgres.h"
#include "access/hash.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 90600
#include "access/parallel.h"
#endif
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 110000
#include "catalog/pg_authid.h"
#endif
#if PG_VERSION_NUM >= 110000
#include "catalog/pg_authid_d.h"
#endif
#include "catalog/pg_class.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#if PG_VERSION_NUM >= 150000
#include "common/pg_prng.h"
#endif
#include "fmgr.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "nodes/nodeFuncs.h"
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/planner.h"
#include "parser/analyze.h"
#include "parser/parse_node.h"
#include "parser/parsetree.h"
#if PG_VERSION_NUM >= 150000
#include "postmaster/autovacuum.h"
#endif
#include "postmaster/postmaster.h"
#if PG_VERSION_NUM >= 150000
#include "replication/walsender.h"
#endif
#include "storage/ipc.h"
#include "storage/lwlock.h"
#if PG_VERSION_NUM >= 100000
#include "storage/shmem.h"
#endif
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/tuplestore.h"
PG_MODULE_MAGIC;
#define PGQS_NAME_COLUMNS 7 /* number of column added when using
* pg_qualstats_column SRF */
#define PGQS_USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
#define PGQS_MAX_DEFAULT 1000 /* default pgqs_max value */
#define PGQS_MAX_LOCAL_ENTRIES (pgqs_max * 0.2) /* do not track more of
* 20% of possible entries
* in shared mem */
#define PGQS_CONSTANT_SIZE 80 /* Truncate constant representation at 80 */
#define PGQS_FLAGS (INSTRUMENT_ROWS|INSTRUMENT_BUFFERS)
#define PGQS_RATIO 0
#define PGQS_NUM 1
#define PGQS_LWL_ACQUIRE(lock, mode) if (!pgqs_backend) { \
LWLockAcquire(lock, mode); \
}
#define PGQS_LWL_RELEASE(lock) if (!pgqs_backend) { \
LWLockRelease(lock); \
}
#if PG_VERSION_NUM < 170000
#define MyProcNumber MyBackendId
#define ParallelLeaderProcNumber ParallelLeaderBackendId
#endif
#if PG_VERSION_NUM < 140000
#define ParallelLeaderBackendId ParallelMasterBackendId
#endif
/*
* Extension version number, for supporting older extension versions' objects
*/
typedef enum pgqsVersion
{
PGQS_V1_0 = 0,
PGQS_V2_0
} pgqsVersion;
/*---- Function declarations ----*/
extern PGDLLEXPORT void _PG_init(void);
extern PGDLLEXPORT Datum pg_qualstats_reset(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_qualstats(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_qualstats_2_0(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_qualstats_names(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_qualstats_names_2_0(PG_FUNCTION_ARGS);
static Datum pg_qualstats_common(PG_FUNCTION_ARGS, pgqsVersion api_version,
bool include_names);
extern PGDLLEXPORT Datum pg_qualstats_example_query(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_qualstats_example_queries(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_qualstats_reset);
PG_FUNCTION_INFO_V1(pg_qualstats);
PG_FUNCTION_INFO_V1(pg_qualstats_2_0);
PG_FUNCTION_INFO_V1(pg_qualstats_names);
PG_FUNCTION_INFO_V1(pg_qualstats_names_2_0);
PG_FUNCTION_INFO_V1(pg_qualstats_example_query);
PG_FUNCTION_INFO_V1(pg_qualstats_example_queries);
static void pgqs_backend_mode_startup(void);
#if PG_VERSION_NUM >= 150000
static void pgqs_shmem_request(void);
#endif
static void pgqs_shmem_startup(void);
static void pgqs_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgqs_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
#if PG_VERSION_NUM >= 90600
uint64 count
#else
long count
#endif
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
, bool execute_once
#endif
);
static void pgqs_ExecutorFinish(QueryDesc *queryDesc);
static void pgqs_ExecutorEnd(QueryDesc *queryDesc);
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;
#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 uint32 pgqs_hash_fn(const void *key, Size keysize);
#if PG_VERSION_NUM < 90500
static uint32 pgqs_uint32_hashfn(const void *key, Size keysize);
#endif
static bool pgqs_backend = false;
static int pgqs_query_size;
static int pgqs_max = PGQS_MAX_DEFAULT; /* max # statements to track */
static bool pgqs_track_pgcatalog; /* track queries on pg_catalog */
static bool pgqs_resolve_oids; /* resolve oids */
static bool pgqs_enabled;
static bool pgqs_track_constants;
static double pgqs_sample_rate;
static int pgqs_min_err_ratio;
static int pgqs_min_err_num;
static int query_is_sampled; /* Is the current query sampled, per backend */
static int nesting_level = 0; /* Current nesting depth of ExecutorRun calls */
static bool pgqs_assign_sample_rate_check_hook(double *newval, void **extra, GucSource source);
#if PG_VERSION_NUM > 90600
static void pgqs_set_query_sampled(bool sample);
#endif
static bool pgqs_is_query_sampled(void);
/*---- Data structures declarations ----*/
typedef struct pgqsSharedState
{
#if PG_VERSION_NUM >= 90400
LWLock *lock; /* protects counters hashtable
* search/modification */
LWLock *querylock; /* protects query hashtable
* search/modification */
#else
LWLockId lock; /* protects counters hashtable
* search/modification */
LWLockId querylock; /* protects query hashtable
* search/modification */
#endif
#if PG_VERSION_NUM >= 90600
LWLock *sampledlock; /* protects sampled array search/modification */
bool sampled[FLEXIBLE_ARRAY_MEMBER]; /* should we sample this
* query? */
#endif
} pgqsSharedState;
/* Since cff440d368, queryid becomes a uint64 internally. */
#if PG_VERSION_NUM >= 110000
typedef uint64 pgqs_queryid;
#else
typedef uint32 pgqs_queryid;
#endif
typedef struct pgqsHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
pgqs_queryid queryid; /* query identifier (if set by another plugin */
uint32 uniquequalnodeid; /* Hash of the const */
uint32 uniquequalid; /* Hash of the parent, including the consts */
char evaltype; /* Evaluation type. Can be 'f' to mean a qual
* executed after a scan, or 'i' for an
* indexqual */
} pgqsHashKey;
typedef struct pgqsNames
{
NameData rolname;
NameData datname;
NameData lrelname;
NameData lattname;
NameData opname;
NameData rrelname;
NameData rattname;
} pgqsNames;
typedef struct pgqsEntry
{
pgqsHashKey key;
Oid lrelid; /* LHS relation OID or NULL if not var */
AttrNumber lattnum; /* LHS attribute Number or NULL if not var */
Oid opoid; /* Operator OID */
Oid rrelid; /* RHS relation OID or NULL if not var */
AttrNumber rattnum; /* RHS attribute Number or NULL if not var */
char constvalue[PGQS_CONSTANT_SIZE]; /* Textual representation of
* the right hand constant, if
* any */
uint32 qualid; /* Hash of the parent AND expression if any, 0
* otherwise. */
uint32 qualnodeid; /* Hash of the node itself */
int64 count; /* # of operator execution */
int64 nbfiltered; /* # of lines discarded by the operator */
int position; /* content position in query text */
double usage; /* # of qual execution, used for deallocation */
double min_err_estim[2]; /* min estimation error ratio and num */
double max_err_estim[2]; /* max estimation error ratio and num */
double mean_err_estim[2]; /* mean estimation error ratio and num */
double sum_err_estim[2]; /* sum of variances in estimation error
* ratio and num */
int64 occurences; /* # of qual execution, 1 per query */
} pgqsEntry;
typedef struct pgqsEntryWithNames
{
pgqsEntry entry;
pgqsNames names;
} pgqsEntryWithNames;
typedef struct pgqsQueryStringHashKey
{
pgqs_queryid queryid;
} pgqsQueryStringHashKey;
typedef struct pgqsQueryStringEntry
{
pgqsQueryStringHashKey key;
/*
* Imperatively at the end of the struct This is actually of length
* query_size, which is track_activity_query_size
*/
char querytext[1];
} pgqsQueryStringEntry;
/*
* Transient state of the query tree walker - for the meaning of the counters,
* see pgqsEntry comments.
*/
typedef struct pgqsWalkerContext
{
pgqs_queryid queryId;
List *rtable;
PlanState *planstate;
PlanState *inner_planstate;
PlanState *outer_planstate;
List *outer_tlist;
List *inner_tlist;
List *index_tlist;
uint32 qualid;
uint32 uniquequalid; /* Hash of the parent, including the consts */
int64 count;
int64 nbfiltered;
double err_estim[2];
int nentries; /* number of entries found so far */
char evaltype;
const char *querytext;
} pgqsWalkerContext;
static bool pgqs_whereclause_tree_walker(Node *node, pgqsWalkerContext *query);
static pgqsEntry *pgqs_process_opexpr(OpExpr *expr, pgqsWalkerContext *context);
static pgqsEntry *pgqs_process_scalararrayopexpr(ScalarArrayOpExpr *expr, pgqsWalkerContext *context);
static pgqsEntry *pgqs_process_booltest(BooleanTest *expr, pgqsWalkerContext *context);
static void pgqs_collectNodeStats(PlanState *planstate, List *ancestors, pgqsWalkerContext *context);
static void pgqs_collectMemberNodeStats(int nplans, PlanState **planstates, List *ancestors, pgqsWalkerContext *context);
static void pgqs_collectSubPlanStats(List *plans, List *ancestors, pgqsWalkerContext *context);
static uint32 hashExpr(Expr *expr, pgqsWalkerContext *context, bool include_const);
static void exprRepr(Expr *expr, StringInfo buffer, pgqsWalkerContext *context, bool include_const);
static void pgqs_set_planstates(PlanState *planstate, pgqsWalkerContext *context);
static Expr *pgqs_resolve_var(Var *var, pgqsWalkerContext *context);
static void pgqs_entry_dealloc(void);
static inline void pgqs_entry_init(pgqsEntry *entry);
static inline void pgqs_entry_copy_raw(pgqsEntry *dest, pgqsEntry *src);
static void pgqs_entry_err_estim(pgqsEntry *e, double *err_estim, int64 occurences);
static void pgqs_queryentry_dealloc(void);
static void pgqs_localentry_dealloc(int nvictims);
static void pgqs_fillnames(pgqsEntryWithNames *entry);
static Size pgqs_memsize(void);
#if PG_VERSION_NUM >= 90600
static Size pgqs_sampled_array_size(void);
#endif
/* Global Hash */
static HTAB *pgqs_hash = NULL;
static HTAB *pgqs_query_examples_hash = NULL;
static pgqsSharedState *pgqs = NULL;
/* Local Hash */
static HTAB *pgqs_localhash = NULL;
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
{
elog(WARNING, "Without shared_preload_libraries, only current backend stats will be available.");
pgqs_backend = true;
}
else
{
pgqs_backend = false;
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgqs_shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgqs_shmem_startup;
}
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgqs_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgqs_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgqs_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgqs_ExecutorEnd;
DefineCustomBoolVariable("pg_qualstats.enabled",
"Enable / Disable pg_qualstats",
NULL,
&pgqs_enabled,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_qualstats.track_constants",
"Enable / Disable pg_qualstats constants tracking",
NULL,
&pgqs_track_constants,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_qualstats.max",
"Sets the maximum number of statements tracked by pg_qualstats.",
NULL,
&pgqs_max,
PGQS_MAX_DEFAULT,
100,
INT_MAX,
pgqs_backend ? PGC_USERSET : PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
if (!pgqs_backend)
DefineCustomBoolVariable("pg_qualstats.resolve_oids",
"Store names alongside the oid. Eats MUCH more space!",
NULL,
&pgqs_resolve_oids,
false,
PGC_POSTMASTER,
0,
NULL,
NULL,
NULL);
DefineCustomBoolVariable("pg_qualstats.track_pg_catalog",
"Track quals on system catalogs too.",
NULL,
&pgqs_track_pgcatalog,
false,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomRealVariable("pg_qualstats.sample_rate",
"Sampling rate. 1 means every query, 0.2 means 1 in five queries",
NULL,
&pgqs_sample_rate,
-1,
-1,
1,
PGC_USERSET,
0,
pgqs_assign_sample_rate_check_hook,
NULL,
NULL);
DefineCustomIntVariable("pg_qualstats.min_err_estimate_ratio",
"Error estimation ratio threshold to save quals",
NULL,
&pgqs_min_err_ratio,
0,
0,
INT_MAX,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomIntVariable("pg_qualstats.min_err_estimate_num",
"Error estimation num threshold to save quals",
NULL,
&pgqs_min_err_num,
0,
0,
INT_MAX,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
EmitWarningsOnPlaceholders("pg_qualstats");
parse_int(GetConfigOption("track_activity_query_size", false, false),
&pgqs_query_size, 0, NULL);
if (!pgqs_backend)
{
#if PG_VERSION_NUM < 150000
RequestAddinShmemSpace(pgqs_memsize());
#if PG_VERSION_NUM >= 90600
RequestNamedLWLockTranche("pg_qualstats", 3);
#else
RequestAddinLWLocks(2);
#endif /* pg9.6+ */
#endif /* pg15- */
}
else
pgqs_backend_mode_startup();
}
/*
* Check that the sample ratio is in the correct interval
*/
static bool
pgqs_assign_sample_rate_check_hook(double *newval, void **extra, GucSource source)
{
double val = *newval;
if ((val < 0 && val != -1) || (val > 1))
return false;
if (val == -1)
*newval = 1. / MaxConnections;
return true;
}
#if PG_VERSION_NUM >= 90600
static void
pgqs_set_query_sampled(bool sample)
{
/* the decisions should only be made in leader */
Assert(!IsParallelWorker());
/* not supported in backend mode */
if (pgqs_backend)
return;
/* in worker processes we need to get the info from shared memory */
LWLockAcquire(pgqs->sampledlock, LW_EXCLUSIVE);
pgqs->sampled[MyProcNumber] = sample;
LWLockRelease(pgqs->sampledlock);
}
#endif
static bool
pgqs_is_query_sampled(void)
{
#if PG_VERSION_NUM >= 90600
bool sampled;
/* in leader we can just check the global variable */
if (!IsParallelWorker())
return query_is_sampled;
/* not supported in backend mode */
if (pgqs_backend)
return false;
/* in worker processes we need to get the info from shared memory */
PGQS_LWL_ACQUIRE(pgqs->sampledlock, LW_SHARED);
sampled = pgqs->sampled[ParallelLeaderProcNumber];
PGQS_LWL_RELEASE(pgqs->sampledlock);
return sampled;
#else
return query_is_sampled;
#endif
}
/*
* Do catalog search to replace oids with corresponding objects name
*/
void
pgqs_fillnames(pgqsEntryWithNames *entry)
{
#if PG_VERSION_NUM >= 110000
#define GET_ATTNAME(r, a) get_attname(r, a, false)
#else
#define GET_ATTNAME(r, a) get_attname(r, a)
#endif
#if PG_VERSION_NUM >= 90500
namestrcpy(&(entry->names.rolname), GetUserNameFromId(entry->entry.key.userid, true));
#else
namestrcpy(&(entry->names.rolname), GetUserNameFromId(entry->entry.key.userid));
#endif
namestrcpy(&(entry->names.datname), get_database_name(entry->entry.key.dbid));
if (entry->entry.lrelid != InvalidOid)
{
namestrcpy(&(entry->names.lrelname),
get_rel_name(entry->entry.lrelid));
namestrcpy(&(entry->names.lattname),
GET_ATTNAME(entry->entry.lrelid, entry->entry.lattnum));
}
if (entry->entry.opoid != InvalidOid)
namestrcpy(&(entry->names.opname), get_opname(entry->entry.opoid));
if (entry->entry.rrelid != InvalidOid)
{
namestrcpy(&(entry->names.rrelname),
get_rel_name(entry->entry.rrelid));
namestrcpy(&(entry->names.rattname),
GET_ATTNAME(entry->entry.rrelid, entry->entry.rattnum));
}
#undef GET_ATTNAME
}
/*
* Request rows and buffers instrumentation if pgqs is enabled
*/
static void
pgqs_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
/* Setup instrumentation */
if (pgqs_enabled)
{
/*
* For rate sampling, randomly choose top-level statement. Either all
* nested statements will be explained or none will.
*/
if (nesting_level == 0
#if PG_VERSION_NUM >= 90600
&& (!IsParallelWorker())
#endif
)
{
#if PG_VERSION_NUM >= 150000
query_is_sampled = (pg_prng_double(&pg_global_prng_state) <
pgqs_sample_rate);
#else
query_is_sampled = (random() <= (MAX_RANDOM_VALUE *
pgqs_sample_rate));
#endif
#if PG_VERSION_NUM >= 90600
pgqs_set_query_sampled(query_is_sampled);
#endif
}
if (pgqs_is_query_sampled())
queryDesc->instrument_options |= PGQS_FLAGS;
}
if (prev_ExecutorStart)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
}
/*
* ExecutorRun hook: all we need do is track nesting depth
*/
static void
pgqs_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
#if PG_VERSION_NUM >= 90600
uint64 count
#else
long count
#endif
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
,bool execute_once
#endif
)
{
nesting_level++;
PG_TRY();
{
if (prev_ExecutorRun)
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
prev_ExecutorRun(queryDesc, direction, count, execute_once);
#else
prev_ExecutorRun(queryDesc, direction, count);
#endif
else
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
standard_ExecutorRun(queryDesc, direction, count, execute_once);
#else
standard_ExecutorRun(queryDesc, direction, count);
#endif
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* ExecutorFinish hook: all we need do is track nesting depth
*/
static void
pgqs_ExecutorFinish(QueryDesc *queryDesc)
{
nesting_level++;
PG_TRY();
{
if (prev_ExecutorFinish)
prev_ExecutorFinish(queryDesc);
else
standard_ExecutorFinish(queryDesc);
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
/*
* Save a non normalized query for the queryid if no one already exists, and
* do all the stat collecting job
*/
static void
pgqs_ExecutorEnd(QueryDesc *queryDesc)
{
pgqsQueryStringHashKey queryKey;
bool found;
if ((pgqs || pgqs_backend) && pgqs_enabled && pgqs_is_query_sampled()
#if PG_VERSION_NUM >= 90600
&& (!IsParallelWorker())
#endif
/*
* multiple ExecutorStart/ExecutorEnd can be interleaved, so when sampling
* is activated there's no guarantee that pgqs_is_query_sampled() will
* only detect queries that were actually sampled (thus having the
* required instrumentation set up). To avoid such cases, we double check
* that we have the required instrumentation set up. That won't exactly
* detect the sampled queries, but that should be close enough and avoid
* adding to much complexity.
*/
&& (queryDesc->instrument_options & PGQS_FLAGS) == PGQS_FLAGS
)
{
HASHCTL info;
pgqsEntry *localentry;
HASH_SEQ_STATUS local_hash_seq;
/* We need to switch to the per-query memory context */
MemoryContext oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
pgqsWalkerContext *context = palloc(sizeof(pgqsWalkerContext));
context->queryId = queryDesc->plannedstmt->queryId;
context->rtable = queryDesc->plannedstmt->rtable;
context->count = 0;
context->qualid = 0;
context->uniquequalid = 0;
context->nbfiltered = 0;
context->evaltype = 0;
context->nentries = 0;
context->querytext = queryDesc->sourceText;
queryKey.queryid = context->queryId;
/* keep an unormalized query example for each queryid if needed */
if (pgqs_track_constants)
{
/* Lookup the hash table entry with a shared lock. */
PGQS_LWL_ACQUIRE(pgqs->querylock, LW_SHARED);
hash_search_with_hash_value(pgqs_query_examples_hash, &queryKey,
context->queryId,
HASH_FIND, &found);
/* Create the new entry if not present */
if (!found)
{
pgqsQueryStringEntry *queryEntry;
bool excl_found;
/* Need exclusive lock to add a new hashtable entry - promote */
PGQS_LWL_RELEASE(pgqs->querylock);
PGQS_LWL_ACQUIRE(pgqs->querylock, LW_EXCLUSIVE);
while (hash_get_num_entries(pgqs_query_examples_hash) >= pgqs_max)
pgqs_queryentry_dealloc();
queryEntry = (pgqsQueryStringEntry *) hash_search_with_hash_value(pgqs_query_examples_hash, &queryKey,
context->queryId,
HASH_ENTER, &excl_found);
/* Make sure it wasn't added by another backend */
if (!excl_found)
strncpy(queryEntry->querytext, context->querytext, pgqs_query_size);
}
PGQS_LWL_RELEASE(pgqs->querylock);
}
/* create local hash table if it hasn't been created yet */
if (!pgqs_localhash)
{
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgqsHashKey);
if (pgqs_resolve_oids)
info.entrysize = sizeof(pgqsEntryWithNames);
else
info.entrysize = sizeof(pgqsEntry);
info.hash = pgqs_hash_fn;
pgqs_localhash = hash_create("pgqs_localhash",
50,
&info,
HASH_ELEM | HASH_FUNCTION);
}
/* retrieve quals informations, main work starts from here */
pgqs_collectNodeStats(queryDesc->planstate, NIL, context);
/* if any quals found, store them in shared memory */
if (context->nentries)
{
/*
* Before acquiring exlusive lwlock, check if there's enough room
* to store local hash. Also, do not remove more than 20% of
* maximum number of entries in shared memory (wether they are
* used or not). This should not happen since we shouldn't store
* that much entries in localhash in the first place.
*/
int nvictims = hash_get_num_entries(pgqs_localhash) -
PGQS_MAX_LOCAL_ENTRIES;
if (nvictims > 0)
pgqs_localentry_dealloc(nvictims);
PGQS_LWL_ACQUIRE(pgqs->lock, LW_EXCLUSIVE);
while (hash_get_num_entries(pgqs_hash) +
hash_get_num_entries(pgqs_localhash) >= pgqs_max)
pgqs_entry_dealloc();
hash_seq_init(&local_hash_seq, pgqs_localhash);
while ((localentry = hash_seq_search(&local_hash_seq)) != NULL)
{
pgqsEntry *newEntry = (pgqsEntry *) hash_search(pgqs_hash,
&localentry->key,
HASH_ENTER, &found);
if (!found)
{
/* raw copy the local entry */
pgqs_entry_copy_raw(newEntry, localentry);
}
else
{
/* only update counters value */
newEntry->count += localentry->count;
newEntry->nbfiltered += localentry->nbfiltered;
newEntry->usage += localentry->usage;
/* compute estimation error min, max, mean and variance */
pgqs_entry_err_estim(newEntry, localentry->mean_err_estim,
localentry->occurences);
}
/* cleanup local hash */
hash_search(pgqs_localhash, &localentry->key, HASH_REMOVE, NULL);
}
PGQS_LWL_RELEASE(pgqs->lock);
}
MemoryContextSwitchTo(oldcxt);
}
if (prev_ExecutorEnd)
prev_ExecutorEnd(queryDesc);
else
standard_ExecutorEnd(queryDesc);
}
/*
* qsort comparator for sorting into increasing usage order
*/
static int
entry_cmp(const void *lhs, const void *rhs)
{
double l_usage = (*(pgqsEntry *const *) lhs)->usage;
double r_usage = (*(pgqsEntry *const *) rhs)->usage;
if (l_usage < r_usage)
return -1;
else if (l_usage > r_usage)
return +1;
else
return 0;
}
/*
* Deallocate least used entries.
* Caller must hold an exlusive lock on pgqs->lock
*/
static void
pgqs_entry_dealloc(void)
{
HASH_SEQ_STATUS hash_seq;
pgqsEntry **entries;
pgqsEntry *entry;
int nvictims;
int i;
int base_size;
/*
* Sort entries by usage and deallocate PGQS_USAGE_DEALLOC_PERCENT of
* them. While we're scanning the table, apply the decay factor to the
* usage values.
* pgqs_resolve_oids is irrelevant here as the array stores pointers
* instead of entries. The struct member used for the sort are part of
* pgqsEntry.
*/
base_size = sizeof(pgqsEntry *);
entries = palloc(hash_get_num_entries(pgqs_hash) * base_size);
i = 0;
hash_seq_init(&hash_seq, pgqs_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
entries[i++] = entry;
entry->usage *= 0.99;
}
qsort(entries, i, base_size, entry_cmp);
nvictims = Max(10, i * PGQS_USAGE_DEALLOC_PERCENT / 100);
nvictims = Min(nvictims, i);
for (i = 0; i < nvictims; i++)
hash_search(pgqs_hash, &entries[i]->key, HASH_REMOVE, NULL);
pfree(entries);
}
/* Initialize all non-key fields of the given entry. */
static inline void
pgqs_entry_init(pgqsEntry *entry)
{
/* Note that pgqsNames if needed will be explicitly filled after this */
memset(&(entry->lrelid), 0, sizeof(pgqsEntry) - sizeof(pgqsHashKey));
}
/* Copy non-key and non-name fields from the given entry */
static inline void
pgqs_entry_copy_raw(pgqsEntry *dest, pgqsEntry *src)
{
/* Note that pgqsNames if needed will be explicitly filled after this */
memcpy(&(dest->lrelid),
&(src->lrelid),
(sizeof(pgqsEntry) - sizeof(pgqsHashKey)));
}
/*
* Accurately compute estimation error ratio and num variance using Welford's
* method. See <http://www.johndcook.com/blog/standard_deviation/>
* Also maintain min and max values.
*/
static void
pgqs_entry_err_estim(pgqsEntry *e, double *err_estim, int64 occurences)
{
int i;
e->occurences += occurences;
for (i = 0; i < 2; i++)
{
if ((e->occurences - occurences) == 0)
{
e->min_err_estim[i] = err_estim[i];
e->max_err_estim[i] = err_estim[i];
e->mean_err_estim[i] = err_estim[i];
}
else
{
double old_err = e->mean_err_estim[i];
e->mean_err_estim[i] +=
(err_estim[i] - old_err) / e->occurences;
e->sum_err_estim[i] +=
(err_estim[i] - old_err) * (err_estim[i] - e->mean_err_estim[i]);
}
/* calculate min/max counters */
if (e->min_err_estim[i] > err_estim[i])
e->min_err_estim[i] = err_estim[i];
if (e->max_err_estim[i] < err_estim[i])
e->max_err_estim[i] = err_estim[i];
}
}
/*
* Deallocate the first example query.
* Caller must hold an exlusive lock on pgqs->querylock
*/
static void
pgqs_queryentry_dealloc(void)
{
HASH_SEQ_STATUS hash_seq;
pgqsQueryStringEntry *entry;
hash_seq_init(&hash_seq, pgqs_query_examples_hash);
entry = hash_seq_search(&hash_seq);