Debian Codegraph @

contrib/pg_stat_statements/pg_stat_statements.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * pg_stat_statements.c
4 * Track statement planning and execution times as well as resource
5 * usage across a whole database cluster.
6 *
7 * Execution costs are totaled for each distinct source query, and kept in
8 * a shared hashtable. (We track only as many distinct queries as will fit
9 * in the designated amount of shared memory.)
10 *
11 * Starting in Postgres 9.2, this module normalized query entries. As of
12 * Postgres 14, the normalization is done by the core if compute_query_id is
13 * enabled, or optionally by third-party modules.
14 *
15 * To facilitate presenting entries to users, we create "representative" query
16 * strings in which constants are replaced with parameter symbols ($n), to
17 * make it clearer what a normalized entry can represent. To save on shared
18 * memory, and to avoid having to truncate oversized query strings, we store
19 * these strings in a temporary external query-texts file. Offsets into this
20 * file are kept in shared memory.
21 *
22 * Note about locking issues: to create or delete an entry in the shared
23 * hashtable, one must hold pgss->lock exclusively. Modifying any field
24 * in an entry except the counters requires the same. To look up an entry,
25 * one must hold the lock shared. To read or update the counters within
26 * an entry, one must hold the lock shared or exclusive (so the entry doesn't
27 * disappear!) and also take the entry's mutex spinlock.
28 * The shared state variable pgss->extent (the next free spot in the external
29 * query-text file) should be accessed only while holding either the
30 * pgss->mutex spinlock, or exclusive lock on pgss->lock. We use the mutex to
31 * allow reserving file space while holding only shared lock on pgss->lock.
32 * Rewriting the entire external query-text file, eg for garbage collection,
33 * requires holding pgss->lock exclusively; this allows individual entries
34 * in the file to be read or written while holding only shared lock.
35 *
36 *
37 * Copyright (c) 2008-2025, PostgreSQL Global Development Group
38 *
39 * IDENTIFICATION
40 * contrib/pg_stat_statements/pg_stat_statements.c
41 *
42 *-------------------------------------------------------------------------
43 */
44 #include "postgres.h"
45
46 #include <math.h>
47 #include <sys/stat.h>
48 #include <unistd.h>
49
50 #include "access/parallel.h"
51 #include "catalog/pg_authid.h"
52 #include "common/int.h"
53 #include "executor/instrument.h"
54 #include "funcapi.h"
55 #include "jit/jit.h"
56 #include "mb/pg_wchar.h"
57 #include "miscadmin.h"
58 #include "nodes/queryjumble.h"
59 #include "optimizer/planner.h"
60 #include "parser/analyze.h"
61 #include "parser/scanner.h"
62 #include "pgstat.h"
63 #include "storage/fd.h"
64 #include "storage/ipc.h"
65 #include "storage/lwlock.h"
66 #include "storage/shmem.h"
67 #include "storage/spin.h"
68 #include "tcop/utility.h"
69 #include "utils/acl.h"
70 #include "utils/builtins.h"
71 #include "utils/memutils.h"
72 #include "utils/timestamp.h"
73
74 PG_MODULE_MAGIC_EXT(
75 .name = "pg_stat_statements",
76 .version = PG_VERSION
77 );
78
79 /* Location of permanent stats file (valid when database is shut down) */
80 #define PGSS_DUMP_FILE PGSTAT_STAT_PERMANENT_DIRECTORY "/pg_stat_statements.stat"
81
82 /*
83 * Location of external query text file.
84 */
85 #define PGSS_TEXT_FILE PG_STAT_TMP_DIR "/pgss_query_texts.stat"
86
87 /* Magic number identifying the stats file format */
88 static const uint32 PGSS_FILE_HEADER = 0x20220408;
89
90 /* PostgreSQL major version number, changes in which invalidate all entries */
91 static const uint32 PGSS_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
92
93 /* XXX: Should USAGE_EXEC reflect execution time and/or buffer usage? */
94 #define USAGE_EXEC(duration) (1.0)
95 #define USAGE_INIT (1.0) /* including initial planning */
96 #define ASSUMED_MEDIAN_INIT (10.0) /* initial assumed median usage */
97 #define ASSUMED_LENGTH_INIT 1024 /* initial assumed mean query length */
98 #define USAGE_DECREASE_FACTOR (0.99) /* decreased every entry_dealloc */
99 #define STICKY_DECREASE_FACTOR (0.50) /* factor for sticky entries */
100 #define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
101 #define IS_STICKY(c) ((c.calls[PGSS_PLAN] + c.calls[PGSS_EXEC]) == 0)
102
103 /*
104 * Extension version number, for supporting older extension versions' objects
105 */
106 typedef enum pgssVersion
107 {
108 PGSS_V1_0 = 0,
109 PGSS_V1_1,
110 PGSS_V1_2,
111 PGSS_V1_3,
112 PGSS_V1_8,
113 PGSS_V1_9,
114 PGSS_V1_10,
115 PGSS_V1_11,
116 PGSS_V1_12,
117 } pgssVersion;
118
119 typedef enum pgssStoreKind
120 {
121 PGSS_INVALID = -1,
122
123 /*
124 * PGSS_PLAN and PGSS_EXEC must be respectively 0 and 1 as they're used to
125 * reference the underlying values in the arrays in the Counters struct,
126 * and this order is required in pg_stat_statements_internal().
127 */
128 PGSS_PLAN = 0,
129 PGSS_EXEC,
130 } pgssStoreKind;
131
132 #define PGSS_NUMKIND (PGSS_EXEC + 1)
133
134 /*
135 * Hashtable key that defines the identity of a hashtable entry. We separate
136 * queries by user and by database even if they are otherwise identical.
137 *
138 * If you add a new key to this struct, make sure to teach pgss_store() to
139 * zero the padding bytes. Otherwise, things will break, because pgss_hash is
140 * created using HASH_BLOBS, and thus tag_hash is used to hash this.
141
142 */
143 typedef struct pgssHashKey
144 {
145 Oid userid; /* user OID */
146 Oid dbid; /* database OID */
147 int64 queryid; /* query identifier */
148 bool toplevel; /* query executed at top level */
149 } pgssHashKey;
150
151 /*
152 * The actual stats counters kept within pgssEntry.
153 */
154 typedef struct Counters
155 {
156 int64 calls[PGSS_NUMKIND]; /* # of times planned/executed */
157 double total_time[PGSS_NUMKIND]; /* total planning/execution time,
158 * in msec */
159 double min_time[PGSS_NUMKIND]; /* minimum planning/execution time in
160 * msec since min/max reset */
161 double max_time[PGSS_NUMKIND]; /* maximum planning/execution time in
162 * msec since min/max reset */
163 double mean_time[PGSS_NUMKIND]; /* mean planning/execution time in
164 * msec */
165 double sum_var_time[PGSS_NUMKIND]; /* sum of variances in
166 * planning/execution time in msec */
167 int64 rows; /* total # of retrieved or affected rows */
168 int64 shared_blks_hit; /* # of shared buffer hits */
169 int64 shared_blks_read; /* # of shared disk blocks read */
170 int64 shared_blks_dirtied; /* # of shared disk blocks dirtied */
171 int64 shared_blks_written; /* # of shared disk blocks written */
172 int64 local_blks_hit; /* # of local buffer hits */
173 int64 local_blks_read; /* # of local disk blocks read */
174 int64 local_blks_dirtied; /* # of local disk blocks dirtied */
175 int64 local_blks_written; /* # of local disk blocks written */
176 int64 temp_blks_read; /* # of temp blocks read */
177 int64 temp_blks_written; /* # of temp blocks written */
178 double shared_blk_read_time; /* time spent reading shared blocks,
179 * in msec */
180 double shared_blk_write_time; /* time spent writing shared blocks,
181 * in msec */
182 double local_blk_read_time; /* time spent reading local blocks, in
183 * msec */
184 double local_blk_write_time; /* time spent writing local blocks, in
185 * msec */
186 double temp_blk_read_time; /* time spent reading temp blocks, in msec */
187 double temp_blk_write_time; /* time spent writing temp blocks, in
188 * msec */
189 double usage; /* usage factor */
190 int64 wal_records; /* # of WAL records generated */
191 int64 wal_fpi; /* # of WAL full page images generated */
192 uint64 wal_bytes; /* total amount of WAL generated in bytes */
193 int64 wal_buffers_full; /* # of times the WAL buffers became full */
194 int64 jit_functions; /* total number of JIT functions emitted */
195 double jit_generation_time; /* total time to generate jit code */
196 int64 jit_inlining_count; /* number of times inlining time has been
197 * > 0 */
198 double jit_deform_time; /* total time to deform tuples in jit code */
199 int64 jit_deform_count; /* number of times deform time has been >
200 * 0 */
201
202 double jit_inlining_time; /* total time to inline jit code */
203 int64 jit_optimization_count; /* number of times optimization time
204 * has been > 0 */
205 double jit_optimization_time; /* total time to optimize jit code */
206 int64 jit_emission_count; /* number of times emission time has been
207 * > 0 */
208 double jit_emission_time; /* total time to emit jit code */
209 int64 parallel_workers_to_launch; /* # of parallel workers planned
210 * to be launched */
211 int64 parallel_workers_launched; /* # of parallel workers actually
212 * launched */
213 } Counters;
214
215 /*
216 * Global statistics for pg_stat_statements
217 */
218 typedef struct pgssGlobalStats
219 {
220 int64 dealloc; /* # of times entries were deallocated */
221 TimestampTz stats_reset; /* timestamp with all stats reset */
222 } pgssGlobalStats;
223
224 /*
225 * Statistics per statement
226 *
227 * Note: in event of a failure in garbage collection of the query text file,
228 * we reset query_offset to zero and query_len to -1. This will be seen as
229 * an invalid state by qtext_fetch().
230 */
231 typedef struct pgssEntry
232 {
233 pgssHashKey key; /* hash key of entry - MUST BE FIRST */
234 Counters counters; /* the statistics for this query */
235 Size query_offset; /* query text offset in external file */
236 int query_len; /* # of valid bytes in query string, or -1 */
237 int encoding; /* query text encoding */
238 TimestampTz stats_since; /* timestamp of entry allocation */
239 TimestampTz minmax_stats_since; /* timestamp of last min/max values reset */
240 slock_t mutex; /* protects the counters only */
241 } pgssEntry;
242
243 /*
244 * Global shared state
245 */
246 typedef struct pgssSharedState
247 {
248 LWLock *lock; /* protects hashtable search/modification */
249 double cur_median_usage; /* current median usage in hashtable */
250 Size mean_query_len; /* current mean entry text length */
251 slock_t mutex; /* protects following fields only: */
252 Size extent; /* current extent of query file */
253 int n_writers; /* number of active writers to query file */
254 int gc_count; /* query file garbage collection cycle count */
255 pgssGlobalStats stats; /* global statistics for pgss */
256 } pgssSharedState;
257
258 /*---- Local variables ----*/
259
260 /* Current nesting depth of planner/ExecutorRun/ProcessUtility calls */
261 static int nesting_level = 0;
262
263 /* Saved hook values */
264 static shmem_request_hook_type prev_shmem_request_hook = NULL;
265 static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
266 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
267 static planner_hook_type prev_planner_hook = NULL;
268 static ExecutorStart_hook_type prev_ExecutorStart = NULL;
269 static ExecutorRun_hook_type prev_ExecutorRun = NULL;
270 static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
271 static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
272 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
273
274 /* Links to shared memory state */
275 static pgssSharedState *pgss = NULL;
276 static HTAB *pgss_hash = NULL;
277
278 /*---- GUC variables ----*/
279
280 typedef enum
281 {
282 PGSS_TRACK_NONE, /* track no statements */
283 PGSS_TRACK_TOP, /* only top level statements */
284 PGSS_TRACK_ALL, /* all statements, including nested ones */
285 } PGSSTrackLevel;
286
287 static const struct config_enum_entry track_options[] =
288 {
289 {"none", PGSS_TRACK_NONE, false},
290 {"top", PGSS_TRACK_TOP, false},
291 {"all", PGSS_TRACK_ALL, false},
292 {NULL, 0, false}
293 };
294
295 static int pgss_max = 5000; /* max # statements to track */
296 static int pgss_track = PGSS_TRACK_TOP; /* tracking level */
297 static bool pgss_track_utility = true; /* whether to track utility commands */
298 static bool pgss_track_planning = false; /* whether to track planning
299 * duration */
300 static bool pgss_save = true; /* whether to save stats across shutdown */
301
302 #define pgss_enabled(level) \
303 (!IsParallelWorker() && \
304 (pgss_track == PGSS_TRACK_ALL || \
305 (pgss_track == PGSS_TRACK_TOP && (level) == 0)))
306
307 #define record_gc_qtexts() \
308 do { \
309 SpinLockAcquire(&pgss->mutex); \
310 pgss->gc_count++; \
311 SpinLockRelease(&pgss->mutex); \
312 } while(0)
313
314 /*---- Function declarations ----*/
315
316 PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
317 PG_FUNCTION_INFO_V1(pg_stat_statements_reset_1_7);
318 PG_FUNCTION_INFO_V1(pg_stat_statements_reset_1_11);
319 PG_FUNCTION_INFO_V1(pg_stat_statements_1_2);
320 PG_FUNCTION_INFO_V1(pg_stat_statements_1_3);
321 PG_FUNCTION_INFO_V1(pg_stat_statements_1_8);
322 PG_FUNCTION_INFO_V1(pg_stat_statements_1_9);
323 PG_FUNCTION_INFO_V1(pg_stat_statements_1_10);
324 PG_FUNCTION_INFO_V1(pg_stat_statements_1_11);
325 PG_FUNCTION_INFO_V1(pg_stat_statements_1_12);
326 PG_FUNCTION_INFO_V1(pg_stat_statements);
327 PG_FUNCTION_INFO_V1(pg_stat_statements_info);
328
329 static void pgss_shmem_request(void);
330 static void pgss_shmem_startup(void);
331 static void pgss_shmem_shutdown(int code, Datum arg);
332 static void pgss_post_parse_analyze(ParseState *pstate, Query *query,
333 JumbleState *jstate);
334 static PlannedStmt *pgss_planner(Query *parse,
335 const char *query_string,
336 int cursorOptions,
337 ParamListInfo boundParams);
338 static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags);
339 static void pgss_ExecutorRun(QueryDesc *queryDesc,
340 ScanDirection direction,
341 uint64 count);
342 static void pgss_ExecutorFinish(QueryDesc *queryDesc);
343 static void pgss_ExecutorEnd(QueryDesc *queryDesc);
344 static void pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
345 bool readOnlyTree,
346 ProcessUtilityContext context, ParamListInfo params,
347 QueryEnvironment *queryEnv,
348 DestReceiver *dest, QueryCompletion *qc);
349 static void pgss_store(const char *query, int64 queryId,
350 int query_location, int query_len,
351 pgssStoreKind kind,
352 double total_time, uint64 rows,
353 const BufferUsage *bufusage,
354 const WalUsage *walusage,
355 const struct JitInstrumentation *jitusage,
356 JumbleState *jstate,
357 int parallel_workers_to_launch,
358 int parallel_workers_launched);
359 static void pg_stat_statements_internal(FunctionCallInfo fcinfo,
360 pgssVersion api_version,
361 bool showtext);
362 static Size pgss_memsize(void);
363 static pgssEntry *entry_alloc(pgssHashKey *key, Size query_offset, int query_len,
364 int encoding, bool sticky);
365 static void entry_dealloc(void);
366 static bool qtext_store(const char *query, int query_len,
367 Size *query_offset, int *gc_count);
368 static char *qtext_load_file(Size *buffer_size);
369 static char *qtext_fetch(Size query_offset, int query_len,
370 char *buffer, Size buffer_size);
371 static bool need_gc_qtexts(void);
372 static void gc_qtexts(void);
373 static TimestampTz entry_reset(Oid userid, Oid dbid, int64 queryid, bool minmax_only);
374 static char *generate_normalized_query(JumbleState *jstate, const char *query,
375 int query_loc, int *query_len_p);
376 static void fill_in_constant_lengths(JumbleState *jstate, const char *query,
377 int query_loc);
378 static int comp_location(const void *a, const void *b);
379
380
381 /*
382 * Module load callback
383 */
384 void
385 _PG_init(void)
386 {
387 /*
388 * In order to create our shared memory area, we have to be loaded via
389 * shared_preload_libraries. If not, fall out without hooking into any of
390 * the main system. (We don't throw error here because it seems useful to
391 * allow the pg_stat_statements functions to be created even when the
392 * module isn't active. The functions must protect themselves against
393 * being called then, however.)
394 */
395 if (!process_shared_preload_libraries_in_progress)
396 return;
397
398 /*
399 * Inform the postmaster that we want to enable query_id calculation if
400 * compute_query_id is set to auto.
401 */
402 EnableQueryId();
403
404 /*
405 * Define (or redefine) custom GUC variables.
406 */
407 DefineCustomIntVariable("pg_stat_statements.max",
408 "Sets the maximum number of statements tracked by pg_stat_statements.",
409 NULL,
410 &pgss_max,
411 5000,
412 100,
413 INT_MAX / 2,
414 PGC_POSTMASTER,
415 0,
416 NULL,
417 NULL,
418 NULL);
419
420 DefineCustomEnumVariable("pg_stat_statements.track",
421 "Selects which statements are tracked by pg_stat_statements.",
422 NULL,
423 &pgss_track,
424 PGSS_TRACK_TOP,
425 track_options,
426 PGC_SUSET,
427 0,
428 NULL,
429 NULL,
430 NULL);
431
432 DefineCustomBoolVariable("pg_stat_statements.track_utility",
433 "Selects whether utility commands are tracked by pg_stat_statements.",
434 NULL,
435 &pgss_track_utility,
436 true,
437 PGC_SUSET,
438 0,
439 NULL,
440 NULL,
441 NULL);
442
443 DefineCustomBoolVariable("pg_stat_statements.track_planning",
444 "Selects whether planning duration is tracked by pg_stat_statements.",
445 NULL,
446 &pgss_track_planning,
447 false,
448 PGC_SUSET,
449 0,
450 NULL,
451 NULL,
452 NULL);
453
454 DefineCustomBoolVariable("pg_stat_statements.save",
455 "Save pg_stat_statements statistics across server shutdowns.",
456 NULL,
457 &pgss_save,
458 true,
459 PGC_SIGHUP,
460 0,
461 NULL,
462 NULL,
463 NULL);
464
465 MarkGUCPrefixReserved("pg_stat_statements");
466
467 /*
468 * Install hooks.
469 */
470 prev_shmem_request_hook = shmem_request_hook;
471 shmem_request_hook = pgss_shmem_request;
472 prev_shmem_startup_hook = shmem_startup_hook;
473 shmem_startup_hook = pgss_shmem_startup;
474 prev_post_parse_analyze_hook = post_parse_analyze_hook;
475 post_parse_analyze_hook = pgss_post_parse_analyze;
476 prev_planner_hook = planner_hook;
477 planner_hook = pgss_planner;
478 prev_ExecutorStart = ExecutorStart_hook;
479 ExecutorStart_hook = pgss_ExecutorStart;
480 prev_ExecutorRun = ExecutorRun_hook;
481 ExecutorRun_hook = pgss_ExecutorRun;
482 prev_ExecutorFinish = ExecutorFinish_hook;
483 ExecutorFinish_hook = pgss_ExecutorFinish;
484 prev_ExecutorEnd = ExecutorEnd_hook;
485 ExecutorEnd_hook = pgss_ExecutorEnd;
486 prev_ProcessUtility = ProcessUtility_hook;
487 ProcessUtility_hook = pgss_ProcessUtility;
488 }
489
490 /*
491 * shmem_request hook: request additional shared resources. We'll allocate or
492 * attach to the shared resources in pgss_shmem_startup().
493 */
494 static void
495 pgss_shmem_request(void)
496 {
497 if (prev_shmem_request_hook)
498 prev_shmem_request_hook();
499
500 RequestAddinShmemSpace(pgss_memsize());
501 RequestNamedLWLockTranche("pg_stat_statements", 1);
502 }
503
504 /*
505 * shmem_startup hook: allocate or attach to shared memory,
506 * then load any pre-existing statistics from file.
507 * Also create and load the query-texts file, which is expected to exist
508 * (even if empty) while the module is enabled.
509 */
510 static void
511 pgss_shmem_startup(void)
512 {
513 bool found;
514 HASHCTL info;
515 FILE *file = NULL;
516 FILE *qfile = NULL;
517 uint32 header;
518 int32 num;
519 int32 pgver;
520 int32 i;
521 int buffer_size;
522 char *buffer = NULL;
523
524 if (prev_shmem_startup_hook)
525 prev_shmem_startup_hook();
526
527 /* reset in case this is a restart within the postmaster */
528 pgss = NULL;
529 pgss_hash = NULL;
530
531 /*
532 * Create or attach to the shared memory state, including hash table
533 */
534 LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
535
536 pgss = ShmemInitStruct("pg_stat_statements",
537 sizeof(pgssSharedState),
538 &found);
539
540 if (!found)
541 {
542 /* First time through ... */
543 pgss->lock = &(GetNamedLWLockTranche("pg_stat_statements"))->lock;
544 pgss->cur_median_usage = ASSUMED_MEDIAN_INIT;
545 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
546 SpinLockInit(&pgss->mutex);
547 pgss->extent = 0;
548 pgss->n_writers = 0;
549 pgss->gc_count = 0;
550 pgss->stats.dealloc = 0;
551 pgss->stats.stats_reset = GetCurrentTimestamp();
552 }
553
554 info.keysize = sizeof(pgssHashKey);
555 info.entrysize = sizeof(pgssEntry);
556 pgss_hash = ShmemInitHash("pg_stat_statements hash",
557 pgss_max, pgss_max,
558 &info,
559 HASH_ELEM | HASH_BLOBS);
560
561 LWLockRelease(AddinShmemInitLock);
562
563 /*
564 * If we're in the postmaster (or a standalone backend...), set up a shmem
565 * exit hook to dump the statistics to disk.
566 */
567 if (!IsUnderPostmaster)
568 on_shmem_exit(pgss_shmem_shutdown, (Datum) 0);
569
570 /*
571 * Done if some other process already completed our initialization.
572 */
573 if (found)
574 return;
575
576 /*
577 * Note: we don't bother with locks here, because there should be no other
578 * processes running when this code is reached.
579 */
580
581 /* Unlink query text file possibly left over from crash */
582 unlink(PGSS_TEXT_FILE);
583
584 /* Allocate new query text temp file */
585 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
586 if (qfile == NULL)
587 goto write_error;
588
589 /*
590 * If we were told not to load old statistics, we're done. (Note we do
591 * not try to unlink any old dump file in this case. This seems a bit
592 * questionable but it's the historical behavior.)
593 */
594 if (!pgss_save)
595 {
596 FreeFile(qfile);
597 return;
598 }
599
600 /*
601 * Attempt to load old statistics from the dump file.
602 */
603 file = AllocateFile(PGSS_DUMP_FILE, PG_BINARY_R);
604 if (file == NULL)
605 {
606 if (errno != ENOENT)
607 goto read_error;
608 /* No existing persisted stats file, so we're done */
609 FreeFile(qfile);
610 return;
611 }
612
613 buffer_size = 2048;
614 buffer = (char *) palloc(buffer_size);
615
616 if (fread(&header, sizeof(uint32), 1, file) != 1 ||
617 fread(&pgver, sizeof(uint32), 1, file) != 1 ||
618 fread(&num, sizeof(int32), 1, file) != 1)
619 goto read_error;
620
621 if (header != PGSS_FILE_HEADER ||
622 pgver != PGSS_PG_MAJOR_VERSION)
623 goto data_error;
624
625 for (i = 0; i < num; i++)
626 {
627 pgssEntry temp;
628 pgssEntry *entry;
629 Size query_offset;
630
631 if (fread(&temp, sizeof(pgssEntry), 1, file) != 1)
632 goto read_error;
633
634 /* Encoding is the only field we can easily sanity-check */
635 if (!PG_VALID_BE_ENCODING(temp.encoding))
636 goto data_error;
637
638 /* Resize buffer as needed */
639 if (temp.query_len >= buffer_size)
640 {
641 buffer_size = Max(buffer_size * 2, temp.query_len + 1);
642 buffer = repalloc(buffer, buffer_size);
643 }
644
645 if (fread(buffer, 1, temp.query_len + 1, file) != temp.query_len + 1)
646 goto read_error;
647
648 /* Should have a trailing null, but let's make sure */
649 buffer[temp.query_len] = '\0';
650
651 /* Skip loading "sticky" entries */
652 if (IS_STICKY(temp.counters))
653 continue;
654
655 /* Store the query text */
656 query_offset = pgss->extent;
657 if (fwrite(buffer, 1, temp.query_len + 1, qfile) != temp.query_len + 1)
658 goto write_error;
659 pgss->extent += temp.query_len + 1;
660
661 /* make the hashtable entry (discards old entries if too many) */
662 entry = entry_alloc(&temp.key, query_offset, temp.query_len,
663 temp.encoding,
664 false);
665
666 /* copy in the actual stats */
667 entry->counters = temp.counters;
668 entry->stats_since = temp.stats_since;
669 entry->minmax_stats_since = temp.minmax_stats_since;
670 }
671
672 /* Read global statistics for pg_stat_statements */
673 if (fread(&pgss->stats, sizeof(pgssGlobalStats), 1, file) != 1)
674 goto read_error;
675
676 pfree(buffer);
677 FreeFile(file);
678 FreeFile(qfile);
679
680 /*
681 * Remove the persisted stats file so it's not included in
682 * backups/replication standbys, etc. A new file will be written on next
683 * shutdown.
684 *
685 * Note: it's okay if the PGSS_TEXT_FILE is included in a basebackup,
686 * because we remove that file on startup; it acts inversely to
687 * PGSS_DUMP_FILE, in that it is only supposed to be around when the
688 * server is running, whereas PGSS_DUMP_FILE is only supposed to be around
689 * when the server is not running. Leaving the file creates no danger of
690 * a newly restored database having a spurious record of execution costs,
691 * which is what we're really concerned about here.
692 */
693 unlink(PGSS_DUMP_FILE);
694
695 return;
696
697 read_error:
698 ereport(LOG,
699 (errcode_for_file_access(),
700 errmsg("could not read file \"%s\": %m",
701 PGSS_DUMP_FILE)));
702 goto fail;
703 data_error:
704 ereport(LOG,
705 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
706 errmsg("ignoring invalid data in file \"%s\"",
707 PGSS_DUMP_FILE)));
708 goto fail;
709 write_error:
710 ereport(LOG,
711 (errcode_for_file_access(),
712 errmsg("could not write file \"%s\": %m",
713 PGSS_TEXT_FILE)));
714 fail:
715 if (buffer)
716 pfree(buffer);
717 if (file)
718 FreeFile(file);
719 if (qfile)
720 FreeFile(qfile);
721 /* If possible, throw away the bogus file; ignore any error */
722 unlink(PGSS_DUMP_FILE);
723
724 /*
725 * Don't unlink PGSS_TEXT_FILE here; it should always be around while the
726 * server is running with pg_stat_statements enabled
727 */
728 }
729
730 /*
731 * shmem_shutdown hook: Dump statistics into file.
732 *
733 * Note: we don't bother with acquiring lock, because there should be no
734 * other processes running when this is called.
735 */
736 static void
737 pgss_shmem_shutdown(int code, Datum arg)
738 {
739 FILE *file;
740 char *qbuffer = NULL;
741 Size qbuffer_size = 0;
742 HASH_SEQ_STATUS hash_seq;
743 int32 num_entries;
744 pgssEntry *entry;
745
746 /* Don't try to dump during a crash. */
747 if (code)
748 return;
749
750 /* Safety check ... shouldn't get here unless shmem is set up. */
751 if (!pgss || !pgss_hash)
752 return;
753
754 /* Don't dump if told not to. */
755 if (!pgss_save)
756 return;
757
758 file = AllocateFile(PGSS_DUMP_FILE ".tmp", PG_BINARY_W);
759 if (file == NULL)
760 goto error;
761
762 if (fwrite(&PGSS_FILE_HEADER, sizeof(uint32), 1, file) != 1)
763 goto error;
764 if (fwrite(&PGSS_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
765 goto error;
766 num_entries = hash_get_num_entries(pgss_hash);
767 if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
768 goto error;
769
770 qbuffer = qtext_load_file(&qbuffer_size);
771 if (qbuffer == NULL)
772 goto error;
773
774 /*
775 * When serializing to disk, we store query texts immediately after their
776 * entry data. Any orphaned query texts are thereby excluded.
777 */
778 hash_seq_init(&hash_seq, pgss_hash);
779 while ((entry = hash_seq_search(&hash_seq)) != NULL)
780 {
781 int len = entry->query_len;
782 char *qstr = qtext_fetch(entry->query_offset, len,
783 qbuffer, qbuffer_size);
784
785 if (qstr == NULL)
786 continue; /* Ignore any entries with bogus texts */
787
788 if (fwrite(entry, sizeof(pgssEntry), 1, file) != 1 ||
789 fwrite(qstr, 1, len + 1, file) != len + 1)
790 {
791 /* note: we assume hash_seq_term won't change errno */
792 hash_seq_term(&hash_seq);
793 goto error;
794 }
795 }
796
797 /* Dump global statistics for pg_stat_statements */
798 if (fwrite(&pgss->stats, sizeof(pgssGlobalStats), 1, file) != 1)
799 goto error;
800
801 pfree(qbuffer);
802 qbuffer = NULL;
803
804 if (FreeFile(file))
805 {
806 file = NULL;
807 goto error;
808 }
809
810 /*
811 * Rename file into place, so we atomically replace any old one.
812 */
813 (void) durable_rename(PGSS_DUMP_FILE ".tmp", PGSS_DUMP_FILE, LOG);
814
815 /* Unlink query-texts file; it's not needed while shutdown */
816 unlink(PGSS_TEXT_FILE);
817
818 return;
819
820 error:
821 ereport(LOG,
822 (errcode_for_file_access(),
823 errmsg("could not write file \"%s\": %m",
824 PGSS_DUMP_FILE ".tmp")));
825 if (qbuffer)
826 pfree(qbuffer);
827 if (file)
828 FreeFile(file);
829 unlink(PGSS_DUMP_FILE ".tmp");
830 unlink(PGSS_TEXT_FILE);
831 }
832
833 /*
834 * Post-parse-analysis hook: mark query with a queryId
835 */
836 static void
837 pgss_post_parse_analyze(ParseState *pstate, Query *query, JumbleState *jstate)
838 {
839 if (prev_post_parse_analyze_hook)
840 prev_post_parse_analyze_hook(pstate, query, jstate);
841
842 /* Safety check... */
843 if (!pgss || !pgss_hash || !pgss_enabled(nesting_level))
844 return;
845
846 /*
847 * If it's EXECUTE, clear the queryId so that stats will accumulate for
848 * the underlying PREPARE. But don't do this if we're not tracking
849 * utility statements, to avoid messing up another extension that might be
850 * tracking them.
851 */
852 if (query->utilityStmt)
853 {
854 if (pgss_track_utility && IsA(query->utilityStmt, ExecuteStmt))
855 {
856 query->queryId = INT64CONST(0);
857 return;
858 }
859 }
860
861 /*
862 * If query jumbling were able to identify any ignorable constants, we
863 * immediately create a hash table entry for the query, so that we can
864 * record the normalized form of the query string. If there were no such
865 * constants, the normalized string would be the same as the query text
866 * anyway, so there's no need for an early entry.
867 */
868 if (jstate && jstate->clocations_count > 0)
869 pgss_store(pstate->p_sourcetext,
870 query->queryId,
871 query->stmt_location,
872 query->stmt_len,
873 PGSS_INVALID,
874 0,
875 0,
876 NULL,
877 NULL,
878 NULL,
879 jstate,
880 0,
881 0);
882 }
883
884 /*
885 * Planner hook: forward to regular planner, but measure planning time
886 * if needed.
887 */
888 static PlannedStmt *
889 pgss_planner(Query *parse,
890 const char *query_string,
891 int cursorOptions,
892 ParamListInfo boundParams)
893 {
894 PlannedStmt *result;
895
896 /*
897 * We can't process the query if no query_string is provided, as
898 * pgss_store needs it. We also ignore query without queryid, as it would
899 * be treated as a utility statement, which may not be the case.
900 */
901 if (pgss_enabled(nesting_level)
902 && pgss_track_planning && query_string
903 && parse->queryId != INT64CONST(0))
904 {
905 instr_time start;
906 instr_time duration;
907 BufferUsage bufusage_start,
908 bufusage;
909 WalUsage walusage_start,
910 walusage;
911
912 /* We need to track buffer usage as the planner can access them. */
913 bufusage_start = pgBufferUsage;
914
915 /*
916 * Similarly the planner could write some WAL records in some cases
917 * (e.g. setting a hint bit with those being WAL-logged)
918 */
919 walusage_start = pgWalUsage;
920 INSTR_TIME_SET_CURRENT(start);
921
922 nesting_level++;
923 PG_TRY();
924 {
925 if (prev_planner_hook)
926 result = prev_planner_hook(parse, query_string, cursorOptions,
927 boundParams);
928 else
929 result = standard_planner(parse, query_string, cursorOptions,
930 boundParams);
931 }
932 PG_FINALLY();
933 {
934 nesting_level--;
935 }
936 PG_END_TRY();
937
938 INSTR_TIME_SET_CURRENT(duration);
939 INSTR_TIME_SUBTRACT(duration, start);
940
941 /* calc differences of buffer counters. */
942 memset(&bufusage, 0, sizeof(BufferUsage));
943 BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
944
945 /* calc differences of WAL counters. */
946 memset(&walusage, 0, sizeof(WalUsage));
947 WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
948
949 pgss_store(query_string,
950 parse->queryId,
951 parse->stmt_location,
952 parse->stmt_len,
953 PGSS_PLAN,
954 INSTR_TIME_GET_MILLISEC(duration),
955 0,
956 &bufusage,
957 &walusage,
958 NULL,
959 NULL,
960 0,
961 0);
962 }
963 else
964 {
965 /*
966 * Even though we're not tracking plan time for this statement, we
967 * must still increment the nesting level, to ensure that functions
968 * evaluated during planning are not seen as top-level calls.
969 */
970 nesting_level++;
971 PG_TRY();
972 {
973 if (prev_planner_hook)
974 result = prev_planner_hook(parse, query_string, cursorOptions,
975 boundParams);
976 else
977 result = standard_planner(parse, query_string, cursorOptions,
978 boundParams);
979 }
980 PG_FINALLY();
981 {
982 nesting_level--;
983 }
984 PG_END_TRY();
985 }
986
987 return result;
988 }
989
990 /*
991 * ExecutorStart hook: start up tracking if needed
992 */
993 static void
994 pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
995 {
996 if (prev_ExecutorStart)
997 prev_ExecutorStart(queryDesc, eflags);
998 else
999 standard_ExecutorStart(queryDesc, eflags);
1000
1001 /*
1002 * If query has queryId zero, don't track it. This prevents double
1003 * counting of optimizable statements that are directly contained in
1004 * utility statements.
1005 */
1006 if (pgss_enabled(nesting_level) && queryDesc->plannedstmt->queryId != INT64CONST(0))
1007 {
1008 /*
1009 * Set up to track total elapsed time in ExecutorRun. Make sure the
1010 * space is allocated in the per-query context so it will go away at
1011 * ExecutorEnd.
1012 */
1013 if (queryDesc->totaltime == NULL)
1014 {
1015 MemoryContext oldcxt;
1016
1017 oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
1018 queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL, false);
1019 MemoryContextSwitchTo(oldcxt);
1020 }
1021 }
1022 }
1023
1024 /*
1025 * ExecutorRun hook: all we need do is track nesting depth
1026 */
1027 static void
1028 pgss_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
1029 {
1030 nesting_level++;
1031 PG_TRY();
1032 {
1033 if (prev_ExecutorRun)
1034 prev_ExecutorRun(queryDesc, direction, count);
1035 else
1036 standard_ExecutorRun(queryDesc, direction, count);
1037 }
1038 PG_FINALLY();
1039 {
1040 nesting_level--;
1041 }
1042 PG_END_TRY();
1043 }
1044
1045 /*
1046 * ExecutorFinish hook: all we need do is track nesting depth
1047 */
1048 static void
1049 pgss_ExecutorFinish(QueryDesc *queryDesc)
1050 {
1051 nesting_level++;
1052 PG_TRY();
1053 {
1054 if (prev_ExecutorFinish)
1055 prev_ExecutorFinish(queryDesc);
1056 else
1057 standard_ExecutorFinish(queryDesc);
1058 }
1059 PG_FINALLY();
1060 {
1061 nesting_level--;
1062 }
1063 PG_END_TRY();
1064 }
1065
1066 /*
1067 * ExecutorEnd hook: store results if needed
1068 */
1069 static void
1070 pgss_ExecutorEnd(QueryDesc *queryDesc)
1071 {
1072 int64 queryId = queryDesc->plannedstmt->queryId;
1073
1074 if (queryId != INT64CONST(0) && queryDesc->totaltime &&
1075 pgss_enabled(nesting_level))
1076 {
1077 /*
1078 * Make sure stats accumulation is done. (Note: it's okay if several
1079 * levels of hook all do this.)
1080 */
1081 InstrEndLoop(queryDesc->totaltime);
1082
1083 pgss_store(queryDesc->sourceText,
1084 queryId,
1085 queryDesc->plannedstmt->stmt_location,
1086 queryDesc->plannedstmt->stmt_len,
1087 PGSS_EXEC,
1088 queryDesc->totaltime->total * 1000.0, /* convert to msec */
1089 queryDesc->estate->es_total_processed,
1090 &queryDesc->totaltime->bufusage,
1091 &queryDesc->totaltime->walusage,
1092 queryDesc->estate->es_jit ? &queryDesc->estate->es_jit->instr : NULL,
1093 NULL,
1094 queryDesc->estate->es_parallel_workers_to_launch,
1095 queryDesc->estate->es_parallel_workers_launched);
1096 }
1097
1098 if (prev_ExecutorEnd)
1099 prev_ExecutorEnd(queryDesc);
1100 else
1101 standard_ExecutorEnd(queryDesc);
1102 }
1103
1104 /*
1105 * ProcessUtility hook
1106 */
1107 static void
1108 pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
1109 bool readOnlyTree,
1110 ProcessUtilityContext context,
1111 ParamListInfo params, QueryEnvironment *queryEnv,
1112 DestReceiver *dest, QueryCompletion *qc)
1113 {
1114 Node *parsetree = pstmt->utilityStmt;
1115 int64 saved_queryId = pstmt->queryId;
1116 int saved_stmt_location = pstmt->stmt_location;
1117 int saved_stmt_len = pstmt->stmt_len;
1118 bool enabled = pgss_track_utility && pgss_enabled(nesting_level);
1119
1120 /*
1121 * Force utility statements to get queryId zero. We do this even in cases
1122 * where the statement contains an optimizable statement for which a
1123 * queryId could be derived (such as EXPLAIN or DECLARE CURSOR). For such
1124 * cases, runtime control will first go through ProcessUtility and then
1125 * the executor, and we don't want the executor hooks to do anything,
1126 * since we are already measuring the statement's costs at the utility
1127 * level.
1128 *
1129 * Note that this is only done if pg_stat_statements is enabled and
1130 * configured to track utility statements, in the unlikely possibility
1131 * that user configured another extension to handle utility statements
1132 * only.
1133 */
1134 if (enabled)
1135 pstmt->queryId = INT64CONST(0);
1136
1137 /*
1138 * If it's an EXECUTE statement, we don't track it and don't increment the
1139 * nesting level. This allows the cycles to be charged to the underlying
1140 * PREPARE instead (by the Executor hooks), which is much more useful.
1141 *
1142 * We also don't track execution of PREPARE. If we did, we would get one
1143 * hash table entry for the PREPARE (with hash calculated from the query
1144 * string), and then a different one with the same query string (but hash
1145 * calculated from the query tree) would be used to accumulate costs of
1146 * ensuing EXECUTEs. This would be confusing. Since PREPARE doesn't
1147 * actually run the planner (only parse+rewrite), its costs are generally
1148 * pretty negligible and it seems okay to just ignore it.
1149 */
1150 if (enabled &&
1151 !IsA(parsetree, ExecuteStmt) &&
1152 !IsA(parsetree, PrepareStmt))
1153 {
1154 instr_time start;
1155 instr_time duration;
1156 uint64 rows;
1157 BufferUsage bufusage_start,
1158 bufusage;
1159 WalUsage walusage_start,
1160 walusage;
1161
1162 bufusage_start = pgBufferUsage;
1163 walusage_start = pgWalUsage;
1164 INSTR_TIME_SET_CURRENT(start);
1165
1166 nesting_level++;
1167 PG_TRY();
1168 {
1169 if (prev_ProcessUtility)
1170 prev_ProcessUtility(pstmt, queryString, readOnlyTree,
1171 context, params, queryEnv,
1172 dest, qc);
1173 else
1174 standard_ProcessUtility(pstmt, queryString, readOnlyTree,
1175 context, params, queryEnv,
1176 dest, qc);
1177 }
1178 PG_FINALLY();
1179 {
1180 nesting_level--;
1181 }
1182 PG_END_TRY();
1183
1184 /*
1185 * CAUTION: do not access the *pstmt data structure again below here.
1186 * If it was a ROLLBACK or similar, that data structure may have been
1187 * freed. We must copy everything we still need into local variables,
1188 * which we did above.
1189 *
1190 * For the same reason, we can't risk restoring pstmt->queryId to its
1191 * former value, which'd otherwise be a good idea.
1192 */
1193
1194 INSTR_TIME_SET_CURRENT(duration);
1195 INSTR_TIME_SUBTRACT(duration, start);
1196
1197 /*
1198 * Track the total number of rows retrieved or affected by the utility
1199 * statements of COPY, FETCH, CREATE TABLE AS, CREATE MATERIALIZED
1200 * VIEW, REFRESH MATERIALIZED VIEW and SELECT INTO.
1201 */
1202 rows = (qc && (qc->commandTag == CMDTAG_COPY ||
1203 qc->commandTag == CMDTAG_FETCH ||
1204 qc->commandTag == CMDTAG_SELECT ||
1205 qc->commandTag == CMDTAG_REFRESH_MATERIALIZED_VIEW)) ?
1206 qc->nprocessed : 0;
1207
1208 /* calc differences of buffer counters. */
1209 memset(&bufusage, 0, sizeof(BufferUsage));
1210 BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
1211
1212 /* calc differences of WAL counters. */
1213 memset(&walusage, 0, sizeof(WalUsage));
1214 WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
1215
1216 pgss_store(queryString,
1217 saved_queryId,
1218 saved_stmt_location,
1219 saved_stmt_len,
1220 PGSS_EXEC,
1221 INSTR_TIME_GET_MILLISEC(duration),
1222 rows,
1223 &bufusage,
1224 &walusage,
1225 NULL,
1226 NULL,
1227 0,
1228 0);
1229 }
1230 else
1231 {
1232 /*
1233 * Even though we're not tracking execution time for this statement,
1234 * we must still increment the nesting level, to ensure that functions
1235 * evaluated within it are not seen as top-level calls. But don't do
1236 * so for EXECUTE; that way, when control reaches pgss_planner or
1237 * pgss_ExecutorStart, we will treat the costs as top-level if
1238 * appropriate. Likewise, don't bump for PREPARE, so that parse
1239 * analysis will treat the statement as top-level if appropriate.
1240 *
1241 * To be absolutely certain we don't mess up the nesting level,
1242 * evaluate the bump_level condition just once.
1243 */
1244 bool bump_level =
1245 !IsA(parsetree, ExecuteStmt) &&
1246 !IsA(parsetree, PrepareStmt);
1247
1248 if (bump_level)
1249 nesting_level++;
1250 PG_TRY();
1251 {
1252 if (prev_ProcessUtility)
1253 prev_ProcessUtility(pstmt, queryString, readOnlyTree,
1254 context, params, queryEnv,
1255 dest, qc);
1256 else
1257 standard_ProcessUtility(pstmt, queryString, readOnlyTree,
1258 context, params, queryEnv,
1259 dest, qc);
1260 }
1261 PG_FINALLY();
1262 {
1263 if (bump_level)
1264 nesting_level--;
1265 }
1266 PG_END_TRY();
1267 }
1268 }
1269
1270 /*
1271 * Store some statistics for a statement.
1272 *
1273 * If jstate is not NULL then we're trying to create an entry for which
1274 * we have no statistics as yet; we just want to record the normalized
1275 * query string. total_time, rows, bufusage and walusage are ignored in this
1276 * case.
1277 *
1278 * If kind is PGSS_PLAN or PGSS_EXEC, its value is used as the array position
1279 * for the arrays in the Counters field.
1280 */
1281 static void
1282 pgss_store(const char *query, int64 queryId,
1283 int query_location, int query_len,
1284 pgssStoreKind kind,
1285 double total_time, uint64 rows,
1286 const BufferUsage *bufusage,
1287 const WalUsage *walusage,
1288 const struct JitInstrumentation *jitusage,
1289 JumbleState *jstate,
1290 int parallel_workers_to_launch,
1291 int parallel_workers_launched)
1292 {
1293 pgssHashKey key;
1294 pgssEntry *entry;
1295 char *norm_query = NULL;
1296 int encoding = GetDatabaseEncoding();
1297
1298 Assert(query != NULL);
1299
1300 /* Safety check... */
1301 if (!pgss || !pgss_hash)
1302 return;
1303
1304 /*
1305 * Nothing to do if compute_query_id isn't enabled and no other module
1306 * computed a query identifier.
1307 */
1308 if (queryId == INT64CONST(0))
1309 return;
1310
1311 /*
1312 * Confine our attention to the relevant part of the string, if the query
1313 * is a portion of a multi-statement source string, and update query
1314 * location and length if needed.
1315 */
1316 query = CleanQuerytext(query, &query_location, &query_len);
1317
1318 /* Set up key for hashtable search */
1319
1320 /* clear padding */
1321 memset(&key, 0, sizeof(pgssHashKey));
1322
1323 key.userid = GetUserId();
1324 key.dbid = MyDatabaseId;
1325 key.queryid = queryId;
1326 key.toplevel = (nesting_level == 0);
1327
1328 /* Lookup the hash table entry with shared lock. */
1329 LWLockAcquire(pgss->lock, LW_SHARED);
1330
1331 entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
1332
1333 /* Create new entry, if not present */
1334 if (!entry)
1335 {
1336 Size query_offset;
1337 int gc_count;
1338 bool stored;
1339 bool do_gc;
1340
1341 /*
1342 * Create a new, normalized query string if caller asked. We don't
1343 * need to hold the lock while doing this work. (Note: in any case,
1344 * it's possible that someone else creates a duplicate hashtable entry
1345 * in the interval where we don't hold the lock below. That case is
1346 * handled by entry_alloc.)
1347 */
1348 if (jstate)
1349 {
1350 LWLockRelease(pgss->lock);
1351 norm_query = generate_normalized_query(jstate, query,
1352 query_location,
1353 &query_len);
1354 LWLockAcquire(pgss->lock, LW_SHARED);
1355 }
1356
1357 /* Append new query text to file with only shared lock held */
1358 stored = qtext_store(norm_query ? norm_query : query, query_len,
1359 &query_offset, &gc_count);
1360
1361 /*
1362 * Determine whether we need to garbage collect external query texts
1363 * while the shared lock is still held. This micro-optimization
1364 * avoids taking the time to decide this while holding exclusive lock.
1365 */
1366 do_gc = need_gc_qtexts();
1367
1368 /* Need exclusive lock to make a new hashtable entry - promote */
1369 LWLockRelease(pgss->lock);
1370 LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
1371
1372 /*
1373 * A garbage collection may have occurred while we weren't holding the
1374 * lock. In the unlikely event that this happens, the query text we
1375 * stored above will have been garbage collected, so write it again.
1376 * This should be infrequent enough that doing it while holding
1377 * exclusive lock isn't a performance problem.
1378 */
1379 if (!stored || pgss->gc_count != gc_count)
1380 stored = qtext_store(norm_query ? norm_query : query, query_len,
1381 &query_offset, NULL);
1382
1383 /* If we failed to write to the text file, give up */
1384 if (!stored)
1385 goto done;
1386
1387 /* OK to create a new hashtable entry */
1388 entry = entry_alloc(&key, query_offset, query_len, encoding,
1389 jstate != NULL);
1390
1391 /* If needed, perform garbage collection while exclusive lock held */
1392 if (do_gc)
1393 gc_qtexts();
1394 }
1395
1396 /* Increment the counts, except when jstate is not NULL */
1397 if (!jstate)
1398 {
1399 Assert(kind == PGSS_PLAN || kind == PGSS_EXEC);
1400
1401 /*
1402 * Grab the spinlock while updating the counters (see comment about
1403 * locking rules at the head of the file)
1404 */
1405 SpinLockAcquire(&entry->mutex);
1406
1407 /* "Unstick" entry if it was previously sticky */
1408 if (IS_STICKY(entry->counters))
1409 entry->counters.usage = USAGE_INIT;
1410
1411 entry->counters.calls[kind] += 1;
1412 entry->counters.total_time[kind] += total_time;
1413
1414 if (entry->counters.calls[kind] == 1)
1415 {
1416 entry->counters.min_time[kind] = total_time;
1417 entry->counters.max_time[kind] = total_time;
1418 entry->counters.mean_time[kind] = total_time;
1419 }
1420 else
1421 {
1422 /*
1423 * Welford's method for accurately computing variance. See
1424 * <http://www.johndcook.com/blog/standard_deviation/>
1425 */
1426 double old_mean = entry->counters.mean_time[kind];
1427
1428 entry->counters.mean_time[kind] +=
1429 (total_time - old_mean) / entry->counters.calls[kind];
1430 entry->counters.sum_var_time[kind] +=
1431 (total_time - old_mean) * (total_time - entry->counters.mean_time[kind]);
1432
1433 /*
1434 * Calculate min and max time. min = 0 and max = 0 means that the
1435 * min/max statistics were reset
1436 */
1437 if (entry->counters.min_time[kind] == 0
1438 && entry->counters.max_time[kind] == 0)
1439 {
1440 entry->counters.min_time[kind] = total_time;
1441 entry->counters.max_time[kind] = total_time;
1442 }
1443 else
1444 {
1445 if (entry->counters.min_time[kind] > total_time)
1446 entry->counters.min_time[kind] = total_time;
1447 if (entry->counters.max_time[kind] < total_time)
1448 entry->counters.max_time[kind] = total_time;
1449 }
1450 }
1451 entry->counters.rows += rows;
1452 entry->counters.shared_blks_hit += bufusage->shared_blks_hit;
1453 entry->counters.shared_blks_read += bufusage->shared_blks_read;
1454 entry->counters.shared_blks_dirtied += bufusage->shared_blks_dirtied;
1455 entry->counters.shared_blks_written += bufusage->shared_blks_written;
1456 entry->counters.local_blks_hit += bufusage->local_blks_hit;
1457 entry->counters.local_blks_read += bufusage->local_blks_read;
1458 entry->counters.local_blks_dirtied += bufusage->local_blks_dirtied;
1459 entry->counters.local_blks_written += bufusage->local_blks_written;
1460 entry->counters.temp_blks_read += bufusage->temp_blks_read;
1461 entry->counters.temp_blks_written += bufusage->temp_blks_written;
1462 entry->counters.shared_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_read_time);
1463 entry->counters.shared_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_write_time);
1464 entry->counters.local_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->local_blk_read_time);
1465 entry->counters.local_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->local_blk_write_time);
1466 entry->counters.temp_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_read_time);
1467 entry->counters.temp_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_write_time);
1468 entry->counters.usage += USAGE_EXEC(total_time);
1469 entry->counters.wal_records += walusage->wal_records;
1470 entry->counters.wal_fpi += walusage->wal_fpi;
1471 entry->counters.wal_bytes += walusage->wal_bytes;
1472 entry->counters.wal_buffers_full += walusage->wal_buffers_full;
1473 if (jitusage)
1474 {
1475 entry->counters.jit_functions += jitusage->created_functions;
1476 entry->counters.jit_generation_time += INSTR_TIME_GET_MILLISEC(jitusage->generation_counter);
1477
1478 if (INSTR_TIME_GET_MILLISEC(jitusage->deform_counter))
1479 entry->counters.jit_deform_count++;
1480 entry->counters.jit_deform_time += INSTR_TIME_GET_MILLISEC(jitusage->deform_counter);
1481
1482 if (INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter))
1483 entry->counters.jit_inlining_count++;
1484 entry->counters.jit_inlining_time += INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter);
1485
1486 if (INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter))
1487 entry->counters.jit_optimization_count++;
1488 entry->counters.jit_optimization_time += INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter);
1489
1490 if (INSTR_TIME_GET_MILLISEC(jitusage->emission_counter))
1491 entry->counters.jit_emission_count++;
1492 entry->counters.jit_emission_time += INSTR_TIME_GET_MILLISEC(jitusage->emission_counter);
1493 }
1494
1495 /* parallel worker counters */
1496 entry->counters.parallel_workers_to_launch += parallel_workers_to_launch;
1497 entry->counters.parallel_workers_launched += parallel_workers_launched;
1498
1499 SpinLockRelease(&entry->mutex);
1500 }
1501
1502 done:
1503 LWLockRelease(pgss->lock);
1504
1505 /* We postpone this clean-up until we're out of the lock */
1506 if (norm_query)
1507 pfree(norm_query);
1508 }
1509
1510 /*
1511 * Reset statement statistics corresponding to userid, dbid, and queryid.
1512 */
1513 Datum
1514 pg_stat_statements_reset_1_7(PG_FUNCTION_ARGS)
1515 {
1516 Oid userid;
1517 Oid dbid;
1518 int64 queryid;
1519
1520 userid = PG_GETARG_OID(0);
1521 dbid = PG_GETARG_OID(1);
1522 queryid = PG_GETARG_INT64(2);
1523
1524 entry_reset(userid, dbid, queryid, false);
1525
1526 PG_RETURN_VOID();
1527 }
1528
1529 Datum
1530 pg_stat_statements_reset_1_11(PG_FUNCTION_ARGS)
1531 {
1532 Oid userid;
1533 Oid dbid;
1534 int64 queryid;
1535 bool minmax_only;
1536
1537 userid = PG_GETARG_OID(0);
1538 dbid = PG_GETARG_OID(1);
1539 queryid = PG_GETARG_INT64(2);
1540 minmax_only = PG_GETARG_BOOL(3);
1541
1542 PG_RETURN_TIMESTAMPTZ(entry_reset(userid, dbid, queryid, minmax_only));
1543 }
1544
1545 /*
1546 * Reset statement statistics.
1547 */
1548 Datum
1549 pg_stat_statements_reset(PG_FUNCTION_ARGS)
1550 {
1551 entry_reset(0, 0, 0, false);
1552
1553 PG_RETURN_VOID();
1554 }
1555
1556 /* Number of output arguments (columns) for various API versions */
1557 #define PG_STAT_STATEMENTS_COLS_V1_0 14
1558 #define PG_STAT_STATEMENTS_COLS_V1_1 18
1559 #define PG_STAT_STATEMENTS_COLS_V1_2 19
1560 #define PG_STAT_STATEMENTS_COLS_V1_3 23
1561 #define PG_STAT_STATEMENTS_COLS_V1_8 32
1562 #define PG_STAT_STATEMENTS_COLS_V1_9 33
1563 #define PG_STAT_STATEMENTS_COLS_V1_10 43
1564 #define PG_STAT_STATEMENTS_COLS_V1_11 49
1565 #define PG_STAT_STATEMENTS_COLS_V1_12 52
1566 #define PG_STAT_STATEMENTS_COLS 52 /* maximum of above */
1567
1568 /*
1569 * Retrieve statement statistics.
1570 *
1571 * The SQL API of this function has changed multiple times, and will likely
1572 * do so again in future. To support the case where a newer version of this
1573 * loadable module is being used with an old SQL declaration of the function,
1574 * we continue to support the older API versions. For 1.2 and later, the
1575 * expected API version is identified by embedding it in the C name of the
1576 * function. Unfortunately we weren't bright enough to do that for 1.1.
1577 */
1578 Datum
1579 pg_stat_statements_1_12(PG_FUNCTION_ARGS)
1580 {
1581 bool showtext = PG_GETARG_BOOL(0);
1582
1583 pg_stat_statements_internal(fcinfo, PGSS_V1_12, showtext);
1584
1585 return (Datum) 0;
1586 }
1587
1588 Datum
1589 pg_stat_statements_1_11(PG_FUNCTION_ARGS)
1590 {
1591 bool showtext = PG_GETARG_BOOL(0);
1592
1593 pg_stat_statements_internal(fcinfo, PGSS_V1_11, showtext);
1594
1595 return (Datum) 0;
1596 }
1597
1598 Datum
1599 pg_stat_statements_1_10(PG_FUNCTION_ARGS)
1600 {
1601 bool showtext = PG_GETARG_BOOL(0);
1602
1603 pg_stat_statements_internal(fcinfo, PGSS_V1_10, showtext);
1604
1605 return (Datum) 0;
1606 }
1607
1608 Datum
1609 pg_stat_statements_1_9(PG_FUNCTION_ARGS)
1610 {
1611 bool showtext = PG_GETARG_BOOL(0);
1612
1613 pg_stat_statements_internal(fcinfo, PGSS_V1_9, showtext);
1614
1615 return (Datum) 0;
1616 }
1617
1618 Datum
1619 pg_stat_statements_1_8(PG_FUNCTION_ARGS)
1620 {
1621 bool showtext = PG_GETARG_BOOL(0);
1622
1623 pg_stat_statements_internal(fcinfo, PGSS_V1_8, showtext);
1624
1625 return (Datum) 0;
1626 }
1627
1628 Datum
1629 pg_stat_statements_1_3(PG_FUNCTION_ARGS)
1630 {
1631 bool showtext = PG_GETARG_BOOL(0);
1632
1633 pg_stat_statements_internal(fcinfo, PGSS_V1_3, showtext);
1634
1635 return (Datum) 0;
1636 }
1637
1638 Datum
1639 pg_stat_statements_1_2(PG_FUNCTION_ARGS)
1640 {
1641 bool showtext = PG_GETARG_BOOL(0);
1642
1643 pg_stat_statements_internal(fcinfo, PGSS_V1_2, showtext);
1644
1645 return (Datum) 0;
1646 }
1647
1648 /*
1649 * Legacy entry point for pg_stat_statements() API versions 1.0 and 1.1.
1650 * This can be removed someday, perhaps.
1651 */
1652 Datum
1653 pg_stat_statements(PG_FUNCTION_ARGS)
1654 {
1655 /* If it's really API 1.1, we'll figure that out below */
1656 pg_stat_statements_internal(fcinfo, PGSS_V1_0, true);
1657
1658 return (Datum) 0;
1659 }
1660
1661 /* Common code for all versions of pg_stat_statements() */
1662 static void
1663 pg_stat_statements_internal(FunctionCallInfo fcinfo,
1664 pgssVersion api_version,
1665 bool showtext)
1666 {
1667 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1668 Oid userid = GetUserId();
1669 bool is_allowed_role = false;
1670 char *qbuffer = NULL;
1671 Size qbuffer_size = 0;
1672 Size extent = 0;
1673 int gc_count = 0;
1674 HASH_SEQ_STATUS hash_seq;
1675 pgssEntry *entry;
1676
1677 /*
1678 * Superusers or roles with the privileges of pg_read_all_stats members
1679 * are allowed
1680 */
1681 is_allowed_role = has_privs_of_role(userid, ROLE_PG_READ_ALL_STATS);
1682
1683 /* hash table must exist already */
1684 if (!pgss || !pgss_hash)
1685 ereport(ERROR,
1686 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1687 errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
1688
1689 InitMaterializedSRF(fcinfo, 0);
1690
1691 /*
1692 * Check we have the expected number of output arguments. Aside from
1693 * being a good safety check, we need a kluge here to detect API version
1694 * 1.1, which was wedged into the code in an ill-considered way.
1695 */
1696 switch (rsinfo->setDesc->natts)
1697 {
1698 case PG_STAT_STATEMENTS_COLS_V1_0:
1699 if (api_version != PGSS_V1_0)
1700 elog(ERROR, "incorrect number of output arguments");
1701 break;
1702 case PG_STAT_STATEMENTS_COLS_V1_1:
1703 /* pg_stat_statements() should have told us 1.0 */
1704 if (api_version != PGSS_V1_0)
1705 elog(ERROR, "incorrect number of output arguments");
1706 api_version = PGSS_V1_1;
1707 break;
1708 case PG_STAT_STATEMENTS_COLS_V1_2:
1709 if (api_version != PGSS_V1_2)
1710 elog(ERROR, "incorrect number of output arguments");
1711 break;
1712 case PG_STAT_STATEMENTS_COLS_V1_3:
1713 if (api_version != PGSS_V1_3)
1714 elog(ERROR, "incorrect number of output arguments");
1715 break;
1716 case PG_STAT_STATEMENTS_COLS_V1_8:
1717 if (api_version != PGSS_V1_8)
1718 elog(ERROR, "incorrect number of output arguments");
1719 break;
1720 case PG_STAT_STATEMENTS_COLS_V1_9:
1721 if (api_version != PGSS_V1_9)
1722 elog(ERROR, "incorrect number of output arguments");
1723 break;
1724 case PG_STAT_STATEMENTS_COLS_V1_10:
1725 if (api_version != PGSS_V1_10)
1726 elog(ERROR, "incorrect number of output arguments");
1727 break;
1728 case PG_STAT_STATEMENTS_COLS_V1_11:
1729 if (api_version != PGSS_V1_11)
1730 elog(ERROR, "incorrect number of output arguments");
1731 break;
1732 case PG_STAT_STATEMENTS_COLS_V1_12:
1733 if (api_version != PGSS_V1_12)
1734 elog(ERROR, "incorrect number of output arguments");
1735 break;
1736 default:
1737 elog(ERROR, "incorrect number of output arguments");
1738 }
1739
1740 /*
1741 * We'd like to load the query text file (if needed) while not holding any
1742 * lock on pgss->lock. In the worst case we'll have to do this again
1743 * after we have the lock, but it's unlikely enough to make this a win
1744 * despite occasional duplicated work. We need to reload if anybody
1745 * writes to the file (either a retail qtext_store(), or a garbage
1746 * collection) between this point and where we've gotten shared lock. If
1747 * a qtext_store is actually in progress when we look, we might as well
1748 * skip the speculative load entirely.
1749 */
1750 if (showtext)
1751 {
1752 int n_writers;
1753
1754 /* Take the mutex so we can examine variables */
1755 SpinLockAcquire(&pgss->mutex);
1756 extent = pgss->extent;
1757 n_writers = pgss->n_writers;
1758 gc_count = pgss->gc_count;
1759 SpinLockRelease(&pgss->mutex);
1760
1761 /* No point in loading file now if there are active writers */
1762 if (n_writers == 0)
1763 qbuffer = qtext_load_file(&qbuffer_size);
1764 }
1765
1766 /*
1767 * Get shared lock, load or reload the query text file if we must, and
1768 * iterate over the hashtable entries.
1769 *
1770 * With a large hash table, we might be holding the lock rather longer
1771 * than one could wish. However, this only blocks creation of new hash
1772 * table entries, and the larger the hash table the less likely that is to
1773 * be needed. So we can hope this is okay. Perhaps someday we'll decide
1774 * we need to partition the hash table to limit the time spent holding any
1775 * one lock.
1776 */
1777 LWLockAcquire(pgss->lock, LW_SHARED);
1778
1779 if (showtext)
1780 {
1781 /*
1782 * Here it is safe to examine extent and gc_count without taking the
1783 * mutex. Note that although other processes might change
1784 * pgss->extent just after we look at it, the strings they then write
1785 * into the file cannot yet be referenced in the hashtable, so we
1786 * don't care whether we see them or not.
1787 *
1788 * If qtext_load_file fails, we just press on; we'll return NULL for
1789 * every query text.
1790 */
1791 if (qbuffer == NULL ||
1792 pgss->extent != extent ||
1793 pgss->gc_count != gc_count)
1794 {
1795 if (qbuffer)
1796 pfree(qbuffer);
1797 qbuffer = qtext_load_file(&qbuffer_size);
1798 }
1799 }
1800
1801 hash_seq_init(&hash_seq, pgss_hash);
1802 while ((entry = hash_seq_search(&hash_seq)) != NULL)
1803 {
1804 Datum values[PG_STAT_STATEMENTS_COLS];
1805 bool nulls[PG_STAT_STATEMENTS_COLS];
1806 int i = 0;
1807 Counters tmp;
1808 double stddev;
1809 int64 queryid = entry->key.queryid;
1810 TimestampTz stats_since;
1811 TimestampTz minmax_stats_since;
1812
1813 memset(values, 0, sizeof(values));
1814 memset(nulls, 0, sizeof(nulls));
1815
1816 values[i++] = ObjectIdGetDatum(entry->key.userid);
1817 values[i++] = ObjectIdGetDatum(entry->key.dbid);
1818 if (api_version >= PGSS_V1_9)
1819 values[i++] = BoolGetDatum(entry->key.toplevel);
1820
1821 if (is_allowed_role || entry->key.userid == userid)
1822 {
1823 if (api_version >= PGSS_V1_2)
1824 values[i++] = Int64GetDatumFast(queryid);
1825
1826 if (showtext)
1827 {
1828 char *qstr = qtext_fetch(entry->query_offset,
1829 entry->query_len,
1830 qbuffer,
1831 qbuffer_size);
1832
1833 if (qstr)
1834 {
1835 char *enc;
1836
1837 enc = pg_any_to_server(qstr,
1838 entry->query_len,
1839 entry->encoding);
1840
1841 values[i++] = CStringGetTextDatum(enc);
1842
1843 if (enc != qstr)
1844 pfree(enc);
1845 }
1846 else
1847 {
1848 /* Just return a null if we fail to find the text */
1849 nulls[i++] = true;
1850 }
1851 }
1852 else
1853 {
1854 /* Query text not requested */
1855 nulls[i++] = true;
1856 }
1857 }
1858 else
1859 {
1860 /* Don't show queryid */
1861 if (api_version >= PGSS_V1_2)
1862 nulls[i++] = true;
1863
1864 /*
1865 * Don't show query text, but hint as to the reason for not doing
1866 * so if it was requested
1867 */
1868 if (showtext)
1869 values[i++] = CStringGetTextDatum("<insufficient privilege>");
1870 else
1871 nulls[i++] = true;
1872 }
1873
1874 /* copy counters to a local variable to keep locking time short */
1875 SpinLockAcquire(&entry->mutex);
1876 tmp = entry->counters;
1877 SpinLockRelease(&entry->mutex);
1878
1879 /*
1880 * The spinlock is not required when reading these two as they are
1881 * always updated when holding pgss->lock exclusively.
1882 */
1883 stats_since = entry->stats_since;
1884 minmax_stats_since = entry->minmax_stats_since;
1885
1886 /* Skip entry if unexecuted (ie, it's a pending "sticky" entry) */
1887 if (IS_STICKY(tmp))
1888 continue;
1889
1890 /* Note that we rely on PGSS_PLAN being 0 and PGSS_EXEC being 1. */
1891 for (int kind = 0; kind < PGSS_NUMKIND; kind++)
1892 {
1893 if (kind == PGSS_EXEC || api_version >= PGSS_V1_8)
1894 {
1895 values[i++] = Int64GetDatumFast(tmp.calls[kind]);
1896 values[i++] = Float8GetDatumFast(tmp.total_time[kind]);
1897 }
1898
1899 if ((kind == PGSS_EXEC && api_version >= PGSS_V1_3) ||
1900 api_version >= PGSS_V1_8)
1901 {
1902 values[i++] = Float8GetDatumFast(tmp.min_time[kind]);
1903 values[i++] = Float8GetDatumFast(tmp.max_time[kind]);
1904 values[i++] = Float8GetDatumFast(tmp.mean_time[kind]);
1905
1906 /*
1907 * Note we are calculating the population variance here, not
1908 * the sample variance, as we have data for the whole
1909 * population, so Bessel's correction is not used, and we
1910 * don't divide by tmp.calls - 1.
1911 */
1912 if (tmp.calls[kind] > 1)
1913 stddev = sqrt(tmp.sum_var_time[kind] / tmp.calls[kind]);
1914 else
1915 stddev = 0.0;
1916 values[i++] = Float8GetDatumFast(stddev);
1917 }
1918 }
1919 values[i++] = Int64GetDatumFast(tmp.rows);
1920 values[i++] = Int64GetDatumFast(tmp.shared_blks_hit);
1921 values[i++] = Int64GetDatumFast(tmp.shared_blks_read);
1922 if (api_version >= PGSS_V1_1)
1923 values[i++] = Int64GetDatumFast(tmp.shared_blks_dirtied);
1924 values[i++] = Int64GetDatumFast(tmp.shared_blks_written);
1925 values[i++] = Int64GetDatumFast(tmp.local_blks_hit);
1926 values[i++] = Int64GetDatumFast(tmp.local_blks_read);
1927 if (api_version >= PGSS_V1_1)
1928 values[i++] = Int64GetDatumFast(tmp.local_blks_dirtied);
1929 values[i++] = Int64GetDatumFast(tmp.local_blks_written);
1930 values[i++] = Int64GetDatumFast(tmp.temp_blks_read);
1931 values[i++] = Int64GetDatumFast(tmp.temp_blks_written);
1932 if (api_version >= PGSS_V1_1)
1933 {
1934 values[i++] = Float8GetDatumFast(tmp.shared_blk_read_time);
1935 values[i++] = Float8GetDatumFast(tmp.shared_blk_write_time);
1936 }
1937 if (api_version >= PGSS_V1_11)
1938 {
1939 values[i++] = Float8GetDatumFast(tmp.local_blk_read_time);
1940 values[i++] = Float8GetDatumFast(tmp.local_blk_write_time);
1941 }
1942 if (api_version >= PGSS_V1_10)
1943 {
1944 values[i++] = Float8GetDatumFast(tmp.temp_blk_read_time);
1945 values[i++] = Float8GetDatumFast(tmp.temp_blk_write_time);
1946 }
1947 if (api_version >= PGSS_V1_8)
1948 {
1949 char buf[256];
1950 Datum wal_bytes;
1951
1952 values[i++] = Int64GetDatumFast(tmp.wal_records);
1953 values[i++] = Int64GetDatumFast(tmp.wal_fpi);
1954
1955 snprintf(buf, sizeof buf, UINT64_FORMAT, tmp.wal_bytes);
1956
1957 /* Convert to numeric. */
1958 wal_bytes = DirectFunctionCall3(numeric_in,
1959 CStringGetDatum(buf),
1960 ObjectIdGetDatum(0),
1961 Int32GetDatum(-1));
1962 values[i++] = wal_bytes;
1963 }
1964 if (api_version >= PGSS_V1_12)
1965 {
1966 values[i++] = Int64GetDatumFast(tmp.wal_buffers_full);
1967 }
1968 if (api_version >= PGSS_V1_10)
1969 {
1970 values[i++] = Int64GetDatumFast(tmp.jit_functions);
1971 values[i++] = Float8GetDatumFast(tmp.jit_generation_time);
1972 values[i++] = Int64GetDatumFast(tmp.jit_inlining_count);
1973 values[i++] = Float8GetDatumFast(tmp.jit_inlining_time);
1974 values[i++] = Int64GetDatumFast(tmp.jit_optimization_count);
1975 values[i++] = Float8GetDatumFast(tmp.jit_optimization_time);
1976 values[i++] = Int64GetDatumFast(tmp.jit_emission_count);
1977 values[i++] = Float8GetDatumFast(tmp.jit_emission_time);
1978 }
1979 if (api_version >= PGSS_V1_11)
1980 {
1981 values[i++] = Int64GetDatumFast(tmp.jit_deform_count);
1982 values[i++] = Float8GetDatumFast(tmp.jit_deform_time);
1983 }
1984 if (api_version >= PGSS_V1_12)
1985 {
1986 values[i++] = Int64GetDatumFast(tmp.parallel_workers_to_launch);
1987 values[i++] = Int64GetDatumFast(tmp.parallel_workers_launched);
1988 }
1989 if (api_version >= PGSS_V1_11)
1990 {
1991 values[i++] = TimestampTzGetDatum(stats_since);
1992 values[i++] = TimestampTzGetDatum(minmax_stats_since);
1993 }
1994
1995 Assert(i == (api_version == PGSS_V1_0 ? PG_STAT_STATEMENTS_COLS_V1_0 :
1996 api_version == PGSS_V1_1 ? PG_STAT_STATEMENTS_COLS_V1_1 :
1997 api_version == PGSS_V1_2 ? PG_STAT_STATEMENTS_COLS_V1_2 :
1998 api_version == PGSS_V1_3 ? PG_STAT_STATEMENTS_COLS_V1_3 :
1999 api_version == PGSS_V1_8 ? PG_STAT_STATEMENTS_COLS_V1_8 :
2000 api_version == PGSS_V1_9 ? PG_STAT_STATEMENTS_COLS_V1_9 :
2001 api_version == PGSS_V1_10 ? PG_STAT_STATEMENTS_COLS_V1_10 :
2002 api_version == PGSS_V1_11 ? PG_STAT_STATEMENTS_COLS_V1_11 :
2003 api_version == PGSS_V1_12 ? PG_STAT_STATEMENTS_COLS_V1_12 :
2004 -1 /* fail if you forget to update this assert */ ));
2005
2006 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2007 }
2008
2009 LWLockRelease(pgss->lock);
2010
2011 if (qbuffer)
2012 pfree(qbuffer);
2013 }
2014
2015 /* Number of output arguments (columns) for pg_stat_statements_info */
2016 #define PG_STAT_STATEMENTS_INFO_COLS 2
2017
2018 /*
2019 * Return statistics of pg_stat_statements.
2020 */
2021 Datum
2022 pg_stat_statements_info(PG_FUNCTION_ARGS)
2023 {
2024 pgssGlobalStats stats;
2025 TupleDesc tupdesc;
2026 Datum values[PG_STAT_STATEMENTS_INFO_COLS] = {0};
2027 bool nulls[PG_STAT_STATEMENTS_INFO_COLS] = {0};
2028
2029 if (!pgss || !pgss_hash)
2030 ereport(ERROR,
2031 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2032 errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
2033
2034 /* Build a tuple descriptor for our result type */
2035 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2036 elog(ERROR, "return type must be a row type");
2037
2038 /* Read global statistics for pg_stat_statements */
2039 SpinLockAcquire(&pgss->mutex);
2040 stats = pgss->stats;
2041 SpinLockRelease(&pgss->mutex);
2042
2043 values[0] = Int64GetDatum(stats.dealloc);
2044 values[1] = TimestampTzGetDatum(stats.stats_reset);
2045
2046 PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
2047 }
2048
2049 /*
2050 * Estimate shared memory space needed.
2051 */
2052 static Size
2053 pgss_memsize(void)
2054 {
2055 Size size;
2056
2057 size = MAXALIGN(sizeof(pgssSharedState));
2058 size = add_size(size, hash_estimate_size(pgss_max, sizeof(pgssEntry)));
2059
2060 return size;
2061 }
2062
2063 /*
2064 * Allocate a new hashtable entry.
2065 * caller must hold an exclusive lock on pgss->lock
2066 *
2067 * "query" need not be null-terminated; we rely on query_len instead
2068 *
2069 * If "sticky" is true, make the new entry artificially sticky so that it will
2070 * probably still be there when the query finishes execution. We do this by
2071 * giving it a median usage value rather than the normal value. (Strictly
2072 * speaking, query strings are normalized on a best effort basis, though it
2073 * would be difficult to demonstrate this even under artificial conditions.)
2074 *
2075 * Note: despite needing exclusive lock, it's not an error for the target
2076 * entry to already exist. This is because pgss_store releases and
2077 * reacquires lock after failing to find a match; so someone else could
2078 * have made the entry while we waited to get exclusive lock.
2079 */
2080 static pgssEntry *
2081 entry_alloc(pgssHashKey *key, Size query_offset, int query_len, int encoding,
2082 bool sticky)
2083 {
2084 pgssEntry *entry;
2085 bool found;
2086
2087 /* Make space if needed */
2088 while (hash_get_num_entries(pgss_hash) >= pgss_max)
2089 entry_dealloc();
2090
2091 /* Find or create an entry with desired hash code */
2092 entry = (pgssEntry *) hash_search(pgss_hash, key, HASH_ENTER, &found);
2093
2094 if (!found)
2095 {
2096 /* New entry, initialize it */
2097
2098 /* reset the statistics */
2099 memset(&entry->counters, 0, sizeof(Counters));
2100 /* set the appropriate initial usage count */
2101 entry->counters.usage = sticky ? pgss->cur_median_usage : USAGE_INIT;
2102 /* re-initialize the mutex each time ... we assume no one using it */
2103 SpinLockInit(&entry->mutex);
2104 /* ... and don't forget the query text metadata */
2105 Assert(query_len >= 0);
2106 entry->query_offset = query_offset;
2107 entry->query_len = query_len;
2108 entry->encoding = encoding;
2109 entry->stats_since = GetCurrentTimestamp();
2110 entry->minmax_stats_since = entry->stats_since;
2111 }
2112
2113 return entry;
2114 }
2115
2116 /*
2117 * qsort comparator for sorting into increasing usage order
2118 */
2119 static int
2120 entry_cmp(const void *lhs, const void *rhs)
2121 {
2122 double l_usage = (*(pgssEntry *const *) lhs)->counters.usage;
2123 double r_usage = (*(pgssEntry *const *) rhs)->counters.usage;
2124
2125 if (l_usage < r_usage)
2126 return -1;
2127 else if (l_usage > r_usage)
2128 return +1;
2129 else
2130 return 0;
2131 }
2132
2133 /*
2134 * Deallocate least-used entries.
2135 *
2136 * Caller must hold an exclusive lock on pgss->lock.
2137 */
2138 static void
2139 entry_dealloc(void)
2140 {
2141 HASH_SEQ_STATUS hash_seq;
2142 pgssEntry **entries;
2143 pgssEntry *entry;
2144 int nvictims;
2145 int i;
2146 Size tottextlen;
2147 int nvalidtexts;
2148
2149 /*
2150 * Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them.
2151 * While we're scanning the table, apply the decay factor to the usage
2152 * values, and update the mean query length.
2153 *
2154 * Note that the mean query length is almost immediately obsolete, since
2155 * we compute it before not after discarding the least-used entries.
2156 * Hopefully, that doesn't affect the mean too much; it doesn't seem worth
2157 * making two passes to get a more current result. Likewise, the new
2158 * cur_median_usage includes the entries we're about to zap.
2159 */
2160
2161 entries = palloc(hash_get_num_entries(pgss_hash) * sizeof(pgssEntry *));
2162
2163 i = 0;
2164 tottextlen = 0;
2165 nvalidtexts = 0;
2166
2167 hash_seq_init(&hash_seq, pgss_hash);
2168 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2169 {
2170 entries[i++] = entry;
2171 /* "Sticky" entries get a different usage decay rate. */
2172 if (IS_STICKY(entry->counters))
2173 entry->counters.usage *= STICKY_DECREASE_FACTOR;
2174 else
2175 entry->counters.usage *= USAGE_DECREASE_FACTOR;
2176 /* In the mean length computation, ignore dropped texts. */
2177 if (entry->query_len >= 0)
2178 {
2179 tottextlen += entry->query_len + 1;
2180 nvalidtexts++;
2181 }
2182 }
2183
2184 /* Sort into increasing order by usage */
2185 qsort(entries, i, sizeof(pgssEntry *), entry_cmp);
2186
2187 /* Record the (approximate) median usage */
2188 if (i > 0)
2189 pgss->cur_median_usage = entries[i / 2]->counters.usage;
2190 /* Record the mean query length */
2191 if (nvalidtexts > 0)
2192 pgss->mean_query_len = tottextlen / nvalidtexts;
2193 else
2194 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2195
2196 /* Now zap an appropriate fraction of lowest-usage entries */
2197 nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
2198 nvictims = Min(nvictims, i);
2199
2200 for (i = 0; i < nvictims; i++)
2201 {
2202 hash_search(pgss_hash, &entries[i]->key, HASH_REMOVE, NULL);
2203 }
2204
2205 pfree(entries);
2206
2207 /* Increment the number of times entries are deallocated */
2208 SpinLockAcquire(&pgss->mutex);
2209 pgss->stats.dealloc += 1;
2210 SpinLockRelease(&pgss->mutex);
2211 }
2212
2213 /*
2214 * Given a query string (not necessarily null-terminated), allocate a new
2215 * entry in the external query text file and store the string there.
2216 *
2217 * If successful, returns true, and stores the new entry's offset in the file
2218 * into *query_offset. Also, if gc_count isn't NULL, *gc_count is set to the
2219 * number of garbage collections that have occurred so far.
2220 *
2221 * On failure, returns false.
2222 *
2223 * At least a shared lock on pgss->lock must be held by the caller, so as
2224 * to prevent a concurrent garbage collection. Share-lock-holding callers
2225 * should pass a gc_count pointer to obtain the number of garbage collections,
2226 * so that they can recheck the count after obtaining exclusive lock to
2227 * detect whether a garbage collection occurred (and removed this entry).
2228 */
2229 static bool
2230 qtext_store(const char *query, int query_len,
2231 Size *query_offset, int *gc_count)
2232 {
2233 Size off;
2234 int fd;
2235
2236 /*
2237 * We use a spinlock to protect extent/n_writers/gc_count, so that
2238 * multiple processes may execute this function concurrently.
2239 */
2240 SpinLockAcquire(&pgss->mutex);
2241 off = pgss->extent;
2242 pgss->extent += query_len + 1;
2243 pgss->n_writers++;
2244 if (gc_count)
2245 *gc_count = pgss->gc_count;
2246 SpinLockRelease(&pgss->mutex);
2247
2248 *query_offset = off;
2249
2250 /*
2251 * Don't allow the file to grow larger than what qtext_load_file can
2252 * (theoretically) handle. This has been seen to be reachable on 32-bit
2253 * platforms.
2254 */
2255 if (unlikely(query_len >= MaxAllocHugeSize - off))
2256 {
2257 errno = EFBIG; /* not quite right, but it'll do */
2258 fd = -1;
2259 goto error;
2260 }
2261
2262 /* Now write the data into the successfully-reserved part of the file */
2263 fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDWR | O_CREAT | PG_BINARY);
2264 if (fd < 0)
2265 goto error;
2266
2267 if (pg_pwrite(fd, query, query_len, off) != query_len)
2268 goto error;
2269 if (pg_pwrite(fd, "\0", 1, off + query_len) != 1)
2270 goto error;
2271
2272 CloseTransientFile(fd);
2273
2274 /* Mark our write complete */
2275 SpinLockAcquire(&pgss->mutex);
2276 pgss->n_writers--;
2277 SpinLockRelease(&pgss->mutex);
2278
2279 return true;
2280
2281 error:
2282 ereport(LOG,
2283 (errcode_for_file_access(),
2284 errmsg("could not write file \"%s\": %m",
2285 PGSS_TEXT_FILE)));
2286
2287 if (fd >= 0)
2288 CloseTransientFile(fd);
2289
2290 /* Mark our write complete */
2291 SpinLockAcquire(&pgss->mutex);
2292 pgss->n_writers--;
2293 SpinLockRelease(&pgss->mutex);
2294
2295 return false;
2296 }
2297
2298 /*
2299 * Read the external query text file into a palloc'd buffer.
2300 *
2301 * Returns NULL (without throwing an error) if unable to read, eg
2302 * file not there or insufficient memory.
2303 *
2304 * On success, the buffer size is also returned into *buffer_size.
2305 *
2306 * This can be called without any lock on pgss->lock, but in that case
2307 * the caller is responsible for verifying that the result is sane.
2308 */
2309 static char *
2310 qtext_load_file(Size *buffer_size)
2311 {
2312 char *buf;
2313 int fd;
2314 struct stat stat;
2315 Size nread;
2316
2317 fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDONLY | PG_BINARY);
2318 if (fd < 0)
2319 {
2320 if (errno != ENOENT)
2321 ereport(LOG,
2322 (errcode_for_file_access(),
2323 errmsg("could not read file \"%s\": %m",
2324 PGSS_TEXT_FILE)));
2325 return NULL;
2326 }
2327
2328 /* Get file length */
2329 if (fstat(fd, &stat))
2330 {
2331 ereport(LOG,
2332 (errcode_for_file_access(),
2333 errmsg("could not stat file \"%s\": %m",
2334 PGSS_TEXT_FILE)));
2335 CloseTransientFile(fd);
2336 return NULL;
2337 }
2338
2339 /* Allocate buffer; beware that off_t might be wider than size_t */
2340 if (stat.st_size <= MaxAllocHugeSize)
2341 buf = (char *) palloc_extended(stat.st_size, MCXT_ALLOC_HUGE | MCXT_ALLOC_NO_OOM);
2342 else
2343 buf = NULL;
2344 if (buf == NULL)
2345 {
2346 ereport(LOG,
2347 (errcode(ERRCODE_OUT_OF_MEMORY),
2348 errmsg("out of memory"),
2349 errdetail("Could not allocate enough memory to read file \"%s\".",
2350 PGSS_TEXT_FILE)));
2351 CloseTransientFile(fd);
2352 return NULL;
2353 }
2354
2355 /*
2356 * OK, slurp in the file. Windows fails if we try to read more than
2357 * INT_MAX bytes at once, and other platforms might not like that either,
2358 * so read a very large file in 1GB segments.
2359 */
2360 nread = 0;
2361 while (nread < stat.st_size)
2362 {
2363 int toread = Min(1024 * 1024 * 1024, stat.st_size - nread);
2364
2365 /*
2366 * If we get a short read and errno doesn't get set, the reason is
2367 * probably that garbage collection truncated the file since we did
2368 * the fstat(), so we don't log a complaint --- but we don't return
2369 * the data, either, since it's most likely corrupt due to concurrent
2370 * writes from garbage collection.
2371 */
2372 errno = 0;
2373 if (read(fd, buf + nread, toread) != toread)
2374 {
2375 if (errno)
2376 ereport(LOG,
2377 (errcode_for_file_access(),
2378 errmsg("could not read file \"%s\": %m",
2379 PGSS_TEXT_FILE)));
2380 pfree(buf);
2381 CloseTransientFile(fd);
2382 return NULL;
2383 }
2384 nread += toread;
2385 }
2386
2387 if (CloseTransientFile(fd) != 0)
2388 ereport(LOG,
2389 (errcode_for_file_access(),
2390 errmsg("could not close file \"%s\": %m", PGSS_TEXT_FILE)));
2391
2392 *buffer_size = nread;
2393 return buf;
2394 }
2395
2396 /*
2397 * Locate a query text in the file image previously read by qtext_load_file().
2398 *
2399 * We validate the given offset/length, and return NULL if bogus. Otherwise,
2400 * the result points to a null-terminated string within the buffer.
2401 */
2402 static char *
2403 qtext_fetch(Size query_offset, int query_len,
2404 char *buffer, Size buffer_size)
2405 {
2406 /* File read failed? */
2407 if (buffer == NULL)
2408 return NULL;
2409 /* Bogus offset/length? */
2410 if (query_len < 0 ||
2411 query_offset + query_len >= buffer_size)
2412 return NULL;
2413 /* As a further sanity check, make sure there's a trailing null */
2414 if (buffer[query_offset + query_len] != '\0')
2415 return NULL;
2416 /* Looks OK */
2417 return buffer + query_offset;
2418 }
2419
2420 /*
2421 * Do we need to garbage-collect the external query text file?
2422 *
2423 * Caller should hold at least a shared lock on pgss->lock.
2424 */
2425 static bool
2426 need_gc_qtexts(void)
2427 {
2428 Size extent;
2429
2430 /* Read shared extent pointer */
2431 SpinLockAcquire(&pgss->mutex);
2432 extent = pgss->extent;
2433 SpinLockRelease(&pgss->mutex);
2434
2435 /*
2436 * Don't proceed if file does not exceed 512 bytes per possible entry.
2437 *
2438 * Here and in the next test, 32-bit machines have overflow hazards if
2439 * pgss_max and/or mean_query_len are large. Force the multiplications
2440 * and comparisons to be done in uint64 arithmetic to forestall trouble.
2441 */
2442 if ((uint64) extent < (uint64) 512 * pgss_max)
2443 return false;
2444
2445 /*
2446 * Don't proceed if file is less than about 50% bloat. Nothing can or
2447 * should be done in the event of unusually large query texts accounting
2448 * for file's large size. We go to the trouble of maintaining the mean
2449 * query length in order to prevent garbage collection from thrashing
2450 * uselessly.
2451 */
2452 if ((uint64) extent < (uint64) pgss->mean_query_len * pgss_max * 2)
2453 return false;
2454
2455 return true;
2456 }
2457
2458 /*
2459 * Garbage-collect orphaned query texts in external file.
2460 *
2461 * This won't be called often in the typical case, since it's likely that
2462 * there won't be too much churn, and besides, a similar compaction process
2463 * occurs when serializing to disk at shutdown or as part of resetting.
2464 * Despite this, it seems prudent to plan for the edge case where the file
2465 * becomes unreasonably large, with no other method of compaction likely to
2466 * occur in the foreseeable future.
2467 *
2468 * The caller must hold an exclusive lock on pgss->lock.
2469 *
2470 * At the first sign of trouble we unlink the query text file to get a clean
2471 * slate (although existing statistics are retained), rather than risk
2472 * thrashing by allowing the same problem case to recur indefinitely.
2473 */
2474 static void
2475 gc_qtexts(void)
2476 {
2477 char *qbuffer;
2478 Size qbuffer_size;
2479 FILE *qfile = NULL;
2480 HASH_SEQ_STATUS hash_seq;
2481 pgssEntry *entry;
2482 Size extent;
2483 int nentries;
2484
2485 /*
2486 * When called from pgss_store, some other session might have proceeded
2487 * with garbage collection in the no-lock-held interim of lock strength
2488 * escalation. Check once more that this is actually necessary.
2489 */
2490 if (!need_gc_qtexts())
2491 return;
2492
2493 /*
2494 * Load the old texts file. If we fail (out of memory, for instance),
2495 * invalidate query texts. Hopefully this is rare. It might seem better
2496 * to leave things alone on an OOM failure, but the problem is that the
2497 * file is only going to get bigger; hoping for a future non-OOM result is
2498 * risky and can easily lead to complete denial of service.
2499 */
2500 qbuffer = qtext_load_file(&qbuffer_size);
2501 if (qbuffer == NULL)
2502 goto gc_fail;
2503
2504 /*
2505 * We overwrite the query texts file in place, so as to reduce the risk of
2506 * an out-of-disk-space failure. Since the file is guaranteed not to get
2507 * larger, this should always work on traditional filesystems; though we
2508 * could still lose on copy-on-write filesystems.
2509 */
2510 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2511 if (qfile == NULL)
2512 {
2513 ereport(LOG,
2514 (errcode_for_file_access(),
2515 errmsg("could not write file \"%s\": %m",
2516 PGSS_TEXT_FILE)));
2517 goto gc_fail;
2518 }
2519
2520 extent = 0;
2521 nentries = 0;
2522
2523 hash_seq_init(&hash_seq, pgss_hash);
2524 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2525 {
2526 int query_len = entry->query_len;
2527 char *qry = qtext_fetch(entry->query_offset,
2528 query_len,
2529 qbuffer,
2530 qbuffer_size);
2531
2532 if (qry == NULL)
2533 {
2534 /* Trouble ... drop the text */
2535 entry->query_offset = 0;
2536 entry->query_len = -1;
2537 /* entry will not be counted in mean query length computation */
2538 continue;
2539 }
2540
2541 if (fwrite(qry, 1, query_len + 1, qfile) != query_len + 1)
2542 {
2543 ereport(LOG,
2544 (errcode_for_file_access(),
2545 errmsg("could not write file \"%s\": %m",
2546 PGSS_TEXT_FILE)));
2547 hash_seq_term(&hash_seq);
2548 goto gc_fail;
2549 }
2550
2551 entry->query_offset = extent;
2552 extent += query_len + 1;
2553 nentries++;
2554 }
2555
2556 /*
2557 * Truncate away any now-unused space. If this fails for some odd reason,
2558 * we log it, but there's no need to fail.
2559 */
2560 if (ftruncate(fileno(qfile), extent) != 0)
2561 ereport(LOG,
2562 (errcode_for_file_access(),
2563 errmsg("could not truncate file \"%s\": %m",
2564 PGSS_TEXT_FILE)));
2565
2566 if (FreeFile(qfile))
2567 {
2568 ereport(LOG,
2569 (errcode_for_file_access(),
2570 errmsg("could not write file \"%s\": %m",
2571 PGSS_TEXT_FILE)));
2572 qfile = NULL;
2573 goto gc_fail;
2574 }
2575
2576 elog(DEBUG1, "pgss gc of queries file shrunk size from %zu to %zu",
2577 pgss->extent, extent);
2578
2579 /* Reset the shared extent pointer */
2580 pgss->extent = extent;
2581
2582 /*
2583 * Also update the mean query length, to be sure that need_gc_qtexts()
2584 * won't still think we have a problem.
2585 */
2586 if (nentries > 0)
2587 pgss->mean_query_len = extent / nentries;
2588 else
2589 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2590
2591 pfree(qbuffer);
2592
2593 /*
2594 * OK, count a garbage collection cycle. (Note: even though we have
2595 * exclusive lock on pgss->lock, we must take pgss->mutex for this, since
2596 * other processes may examine gc_count while holding only the mutex.
2597 * Also, we have to advance the count *after* we've rewritten the file,
2598 * else other processes might not realize they read a stale file.)
2599 */
2600 record_gc_qtexts();
2601
2602 return;
2603
2604 gc_fail:
2605 /* clean up resources */
2606 if (qfile)
2607 FreeFile(qfile);
2608 if (qbuffer)
2609 pfree(qbuffer);
2610
2611 /*
2612 * Since the contents of the external file are now uncertain, mark all
2613 * hashtable entries as having invalid texts.
2614 */
2615 hash_seq_init(&hash_seq, pgss_hash);
2616 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2617 {
2618 entry->query_offset = 0;
2619 entry->query_len = -1;
2620 }
2621
2622 /*
2623 * Destroy the query text file and create a new, empty one
2624 */
2625 (void) unlink(PGSS_TEXT_FILE);
2626 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2627 if (qfile == NULL)
2628 ereport(LOG,
2629 (errcode_for_file_access(),
2630 errmsg("could not recreate file \"%s\": %m",
2631 PGSS_TEXT_FILE)));
2632 else
2633 FreeFile(qfile);
2634
2635 /* Reset the shared extent pointer */
2636 pgss->extent = 0;
2637
2638 /* Reset mean_query_len to match the new state */
2639 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2640
2641 /*
2642 * Bump the GC count even though we failed.
2643 *
2644 * This is needed to make concurrent readers of file without any lock on
2645 * pgss->lock notice existence of new version of file. Once readers
2646 * subsequently observe a change in GC count with pgss->lock held, that
2647 * forces a safe reopen of file. Writers also require that we bump here,
2648 * of course. (As required by locking protocol, readers and writers don't
2649 * trust earlier file contents until gc_count is found unchanged after
2650 * pgss->lock acquired in shared or exclusive mode respectively.)
2651 */
2652 record_gc_qtexts();
2653 }
2654
2655 #define SINGLE_ENTRY_RESET(e) \
2656 if (e) { \
2657 if (minmax_only) { \
2658 /* When requested reset only min/max statistics of an entry */ \
2659 for (int kind = 0; kind < PGSS_NUMKIND; kind++) \
2660 { \
2661 e->counters.max_time[kind] = 0; \
2662 e->counters.min_time[kind] = 0; \
2663 } \
2664 e->minmax_stats_since = stats_reset; \
2665 } \
2666 else \
2667 { \
2668 /* Remove the key otherwise */ \
2669 hash_search(pgss_hash, &e->key, HASH_REMOVE, NULL); \
2670 num_remove++; \
2671 } \
2672 }
2673
2674 /*
2675 * Reset entries corresponding to parameters passed.
2676 */
2677 static TimestampTz
2678 entry_reset(Oid userid, Oid dbid, int64 queryid, bool minmax_only)
2679 {
2680 HASH_SEQ_STATUS hash_seq;
2681 pgssEntry *entry;
2682 FILE *qfile;
2683 long num_entries;
2684 long num_remove = 0;
2685 pgssHashKey key;
2686 TimestampTz stats_reset;
2687
2688 if (!pgss || !pgss_hash)
2689 ereport(ERROR,
2690 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2691 errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
2692
2693 LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
2694 num_entries = hash_get_num_entries(pgss_hash);
2695
2696 stats_reset = GetCurrentTimestamp();
2697
2698 if (userid != 0 && dbid != 0 && queryid != INT64CONST(0))
2699 {
2700 /* If all the parameters are available, use the fast path. */
2701 memset(&key, 0, sizeof(pgssHashKey));
2702 key.userid = userid;
2703 key.dbid = dbid;
2704 key.queryid = queryid;
2705
2706 /*
2707 * Reset the entry if it exists, starting with the non-top-level
2708 * entry.
2709 */
2710 key.toplevel = false;
2711 entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
2712
2713 SINGLE_ENTRY_RESET(entry);
2714
2715 /* Also reset the top-level entry if it exists. */
2716 key.toplevel = true;
2717 entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
2718
2719 SINGLE_ENTRY_RESET(entry);
2720 }
2721 else if (userid != 0 || dbid != 0 || queryid != INT64CONST(0))
2722 {
2723 /* Reset entries corresponding to valid parameters. */
2724 hash_seq_init(&hash_seq, pgss_hash);
2725 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2726 {
2727 if ((!userid || entry->key.userid == userid) &&
2728 (!dbid || entry->key.dbid == dbid) &&
2729 (!queryid || entry->key.queryid == queryid))
2730 {
2731 SINGLE_ENTRY_RESET(entry);
2732 }
2733 }
2734 }
2735 else
2736 {
2737 /* Reset all entries. */
2738 hash_seq_init(&hash_seq, pgss_hash);
2739 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2740 {
2741 SINGLE_ENTRY_RESET(entry);
2742 }
2743 }
2744
2745 /* All entries are removed? */
2746 if (num_entries != num_remove)
2747 goto release_lock;
2748
2749 /*
2750 * Reset global statistics for pg_stat_statements since all entries are
2751 * removed.
2752 */
2753 SpinLockAcquire(&pgss->mutex);
2754 pgss->stats.dealloc = 0;
2755 pgss->stats.stats_reset = stats_reset;
2756 SpinLockRelease(&pgss->mutex);
2757
2758 /*
2759 * Write new empty query file, perhaps even creating a new one to recover
2760 * if the file was missing.
2761 */
2762 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2763 if (qfile == NULL)
2764 {
2765 ereport(LOG,
2766 (errcode_for_file_access(),
2767 errmsg("could not create file \"%s\": %m",
2768 PGSS_TEXT_FILE)));
2769 goto done;
2770 }
2771
2772 /* If ftruncate fails, log it, but it's not a fatal problem */
2773 if (ftruncate(fileno(qfile), 0) != 0)
2774 ereport(LOG,
2775 (errcode_for_file_access(),
2776 errmsg("could not truncate file \"%s\": %m",
2777 PGSS_TEXT_FILE)));
2778
2779 FreeFile(qfile);
2780
2781 done:
2782 pgss->extent = 0;
2783 /* This counts as a query text garbage collection for our purposes */
2784 record_gc_qtexts();
2785
2786 release_lock:
2787 LWLockRelease(pgss->lock);
2788
2789 return stats_reset;
2790 }
2791
2792 /*
2793 * Generate a normalized version of the query string that will be used to
2794 * represent all similar queries.
2795 *
2796 * Note that the normalized representation may well vary depending on
2797 * just which "equivalent" query is used to create the hashtable entry.
2798 * We assume this is OK.
2799 *
2800 * If query_loc > 0, then "query" has been advanced by that much compared to
2801 * the original string start, so we need to translate the provided locations
2802 * to compensate. (This lets us avoid re-scanning statements before the one
2803 * of interest, so it's worth doing.)
2804 *
2805 * *query_len_p contains the input string length, and is updated with
2806 * the result string length on exit. The resulting string might be longer
2807 * or shorter depending on what happens with replacement of constants.
2808 *
2809 * Returns a palloc'd string.
2810 */
2811 static char *
2812 generate_normalized_query(JumbleState *jstate, const char *query,
2813 int query_loc, int *query_len_p)
2814 {
2815 StringInfoData norm_query;
2816 int query_len = *query_len_p;
2817 int len_to_wrt, /* Length (in bytes) to write */
2818 quer_loc = 0, /* Source query byte location */
2819 last_off = 0, /* Offset from start for previous tok */
2820 last_tok_len = 0; /* Length (in bytes) of that tok */
2821 int num_constants_replaced = 0;
2822
2823 /*
2824 * Our output buffer is an expansible StringInfo, but avoid enlarging it
2825 * in most cases by reserving extra space for each constant location.
2826 */
2827 Assert(jstate->clocations_count > 0);
2828 initStringInfoExt(&norm_query, query_len + jstate->clocations_count * 10);
2829
2830 /*
2831 * Determine constants' lengths (core system only gives us locations), and
2832 * return a sorted copy of jstate's LocationLen data with lengths filled
2833 * in.
2834 */
2835 fill_in_constant_lengths(jstate, query, query_loc);
2836
2837 for (int i = 0; i < jstate->clocations_count; i++)
2838 {
2839 int off, /* Offset from start for cur tok */
2840 tok_len; /* Length (in bytes) of that tok */
2841
2842 /*
2843 * If we have an external param at this location, but no lists are
2844 * being squashed across the query, then we skip here; this will make
2845 * us print the characters found in the original query that represent
2846 * the parameter in the next iteration (or after the loop is done),
2847 * which is a bit odd but seems to work okay in most cases.
2848 */
2849 if (jstate->clocations[i].extern_param && !jstate->has_squashed_lists)
2850 continue;
2851
2852 off = jstate->clocations[i].location;
2853
2854 /* Adjust recorded location if we're dealing with partial string */
2855 off -= query_loc;
2856
2857 tok_len = jstate->clocations[i].length;
2858
2859 if (tok_len < 0)
2860 continue; /* ignore any duplicates */
2861
2862 /* Copy next chunk (what precedes the next constant) */
2863 len_to_wrt = off - last_off;
2864 len_to_wrt -= last_tok_len;
2865 Assert(len_to_wrt >= 0);
2866 appendBinaryStringInfo(&norm_query, query + quer_loc, len_to_wrt);
2867
2868 /*
2869 * And insert a param symbol in place of the constant token; and, if
2870 * we have a squashable list, insert a placeholder comment starting
2871 * from the list's second value.
2872 */
2873 appendStringInfo(&norm_query, "$%d%s",
2874 num_constants_replaced + 1 + jstate->highest_extern_param_id,
2875 jstate->clocations[i].squashed ? " /*, ... */" : "");
2876 num_constants_replaced++;
2877
2878 /* move forward */
2879 quer_loc = off + tok_len;
2880 last_off = off;
2881 last_tok_len = tok_len;
2882 }
2883
2884 /*
2885 * We've copied up until the last ignorable constant. Copy over the
2886 * remaining bytes of the original query string.
2887 */
2888 len_to_wrt = query_len - quer_loc;
2889
2890 Assert(len_to_wrt >= 0);
2891 appendBinaryStringInfo(&norm_query, query + quer_loc, len_to_wrt);
2892
2893 *query_len_p = norm_query.len;
2894 return norm_query.data;
2895 }
2896
2897 /*
2898 * Given a valid SQL string and an array of constant-location records,
2899 * fill in the textual lengths of those constants.
2900 *
2901 * The constants may use any allowed constant syntax, such as float literals,
2902 * bit-strings, single-quoted strings and dollar-quoted strings. This is
2903 * accomplished by using the public API for the core scanner.
2904 *
2905 * It is the caller's job to ensure that the string is a valid SQL statement
2906 * with constants at the indicated locations. Since in practice the string
2907 * has already been parsed, and the locations that the caller provides will
2908 * have originated from within the authoritative parser, this should not be
2909 * a problem.
2910 *
2911 * Multiple constants can have the same location. We reset lengths of those
2912 * past the first to -1 so that they can later be ignored.
2913 *
2914 * If query_loc > 0, then "query" has been advanced by that much compared to
2915 * the original string start, so we need to translate the provided locations
2916 * to compensate. (This lets us avoid re-scanning statements before the one
2917 * of interest, so it's worth doing.)
2918 *
2919 * N.B. There is an assumption that a '-' character at a Const location begins
2920 * a negative numeric constant. This precludes there ever being another
2921 * reason for a constant to start with a '-'.
2922 */
2923 static void
2924 fill_in_constant_lengths(JumbleState *jstate, const char *query,
2925 int query_loc)
2926 {
2927 LocationLen *locs;
2928 core_yyscan_t yyscanner;
2929 core_yy_extra_type yyextra;
2930 core_YYSTYPE yylval;
2931 YYLTYPE yylloc;
2932
2933 /*
2934 * Sort the records by location so that we can process them in order while
2935 * scanning the query text.
2936 */
2937 if (jstate->clocations_count > 1)
2938 qsort(jstate->clocations, jstate->clocations_count,
2939 sizeof(LocationLen), comp_location);
2940 locs = jstate->clocations;
2941
2942 /* initialize the flex scanner --- should match raw_parser() */
2943 yyscanner = scanner_init(query,
2944 &yyextra,
2945 &ScanKeywords,
2946 ScanKeywordTokens);
2947
2948 /* we don't want to re-emit any escape string warnings */
2949 yyextra.escape_string_warning = false;
2950
2951 /* Search for each constant, in sequence */
2952 for (int i = 0; i < jstate->clocations_count; i++)
2953 {
2954 int loc;
2955 int tok;
2956
2957 /* Ignore constants after the first one in the same location */
2958 if (i > 0 && locs[i].location == locs[i - 1].location)
2959 {
2960 locs[i].length = -1;
2961 continue;
2962 }
2963
2964 if (locs[i].squashed)
2965 continue; /* squashable list, ignore */
2966
2967 /* Adjust recorded location if we're dealing with partial string */
2968 loc = locs[i].location - query_loc;
2969 Assert(loc >= 0);
2970
2971 /*
2972 * We have a valid location for a constant that's not a dupe. Lex
2973 * tokens until we find the desired constant.
2974 */
2975 for (;;)
2976 {
2977 tok = core_yylex(&yylval, &yylloc, yyscanner);
2978
2979 /* We should not hit end-of-string, but if we do, behave sanely */
2980 if (tok == 0)
2981 break; /* out of inner for-loop */
2982
2983 /*
2984 * We should find the token position exactly, but if we somehow
2985 * run past it, work with that.
2986 */
2987 if (yylloc >= loc)
2988 {
2989 if (query[loc] == '-')
2990 {
2991 /*
2992 * It's a negative value - this is the one and only case
2993 * where we replace more than a single token.
2994 *
2995 * Do not compensate for the core system's special-case
2996 * adjustment of location to that of the leading '-'
2997 * operator in the event of a negative constant. It is
2998 * also useful for our purposes to start from the minus
2999 * symbol. In this way, queries like "select * from foo
3000 * where bar = 1" and "select * from foo where bar = -2"
3001 * will have identical normalized query strings.
3002 */
3003 tok = core_yylex(&yylval, &yylloc, yyscanner);
3004 if (tok == 0)
3005 break; /* out of inner for-loop */
3006 }
3007
3008 /*
3009 * We now rely on the assumption that flex has placed a zero
3010 * byte after the text of the current token in scanbuf.
3011 */
3012 locs[i].length = strlen(yyextra.scanbuf + loc);
3013 break; /* out of inner for-loop */
3014 }
3015 }
3016
3017 /* If we hit end-of-string, give up, leaving remaining lengths -1 */
3018 if (tok == 0)
3019 break;
3020 }
3021
3022 scanner_finish(yyscanner);
3023 }
3024
3025 /*
3026 * comp_location: comparator for qsorting LocationLen structs by location
3027 */
3028 static int
3029 comp_location(const void *a, const void *b)
3030 {
3031 int l = ((const LocationLen *) a)->location;
3032 int r = ((const LocationLen *) b)->location;
3033
3034 return pg_cmp_s32(l, r);
3035 }