Branch data Line data Source code
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-2026, 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/htup_details.h"
51 : : #include "access/parallel.h"
52 : : #include "catalog/pg_authid.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 "pgstat.h"
62 : : #include "storage/fd.h"
63 : : #include "storage/ipc.h"
64 : : #include "storage/lwlock.h"
65 : : #include "storage/shmem.h"
66 : : #include "storage/spin.h"
67 : : #include "tcop/utility.h"
68 : : #include "utils/acl.h"
69 : : #include "utils/builtins.h"
70 : : #include "utils/memutils.h"
71 : : #include "utils/timestamp.h"
72 : : #include "utils/tuplestore.h"
73 : :
74 : 10 : 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 = 0x20250731;
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 : : PGSS_V1_13,
118 : : } pgssVersion;
119 : :
120 : : typedef enum pgssStoreKind
121 : : {
122 : : PGSS_INVALID = -1,
123 : :
124 : : /*
125 : : * PGSS_PLAN and PGSS_EXEC must be respectively 0 and 1 as they're used to
126 : : * reference the underlying values in the arrays in the Counters struct,
127 : : * and this order is required in pg_stat_statements_internal().
128 : : */
129 : : PGSS_PLAN = 0,
130 : : PGSS_EXEC,
131 : : } pgssStoreKind;
132 : :
133 : : #define PGSS_NUMKIND (PGSS_EXEC + 1)
134 : :
135 : : /*
136 : : * Hashtable key that defines the identity of a hashtable entry. We separate
137 : : * queries by user and by database even if they are otherwise identical.
138 : : *
139 : : * If you add a new key to this struct, make sure to teach pgss_store() to
140 : : * zero the padding bytes. Otherwise, things will break, because pgss_hash is
141 : : * created using HASH_BLOBS, and thus tag_hash is used to hash this.
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 : : int64 generic_plan_calls; /* number of calls using a generic plan */
214 : : int64 custom_plan_calls; /* number of calls using a custom plan */
215 : : } Counters;
216 : :
217 : : /*
218 : : * Global statistics for pg_stat_statements
219 : : */
220 : : typedef struct pgssGlobalStats
221 : : {
222 : : int64 dealloc; /* # of times entries were deallocated */
223 : : TimestampTz stats_reset; /* timestamp with all stats reset */
224 : : } pgssGlobalStats;
225 : :
226 : : /*
227 : : * Statistics per statement
228 : : *
229 : : * Note: in event of a failure in garbage collection of the query text file,
230 : : * we reset query_offset to zero and query_len to -1. This will be seen as
231 : : * an invalid state by qtext_fetch().
232 : : */
233 : : typedef struct pgssEntry
234 : : {
235 : : pgssHashKey key; /* hash key of entry - MUST BE FIRST */
236 : : Counters counters; /* the statistics for this query */
237 : : Size query_offset; /* query text offset in external file */
238 : : int query_len; /* # of valid bytes in query string, or -1 */
239 : : int encoding; /* query text encoding */
240 : : TimestampTz stats_since; /* timestamp of entry allocation */
241 : : TimestampTz minmax_stats_since; /* timestamp of last min/max values reset */
242 : : slock_t mutex; /* protects the counters only */
243 : : } pgssEntry;
244 : :
245 : : /*
246 : : * Global shared state
247 : : */
248 : : typedef struct pgssSharedState
249 : : {
250 : : LWLockPadded lock; /* protects hashtable search/modification */
251 : : double cur_median_usage; /* current median usage in hashtable */
252 : : Size mean_query_len; /* current mean entry text length */
253 : : slock_t mutex; /* protects following fields only: */
254 : : Size extent; /* current extent of query file */
255 : : int n_writers; /* number of active writers to query file */
256 : : int gc_count; /* query file garbage collection cycle count */
257 : : pgssGlobalStats stats; /* global statistics for pgss */
258 : : } pgssSharedState;
259 : :
260 : : /* Links to shared memory state */
261 : : static pgssSharedState *pgss;
262 : : static HTAB *pgss_hash;
263 : :
264 : : static void pgss_shmem_request(void *arg);
265 : : static void pgss_shmem_init(void *arg);
266 : :
267 : : static const ShmemCallbacks pgss_shmem_callbacks = {
268 : : .request_fn = pgss_shmem_request,
269 : : .init_fn = pgss_shmem_init,
270 : : };
271 : :
272 : : /*---- Local variables ----*/
273 : :
274 : : /* Current nesting depth of planner/ExecutorRun/ProcessUtility calls */
275 : : static int nesting_level = 0;
276 : :
277 : : /* Saved hook values */
278 : : static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
279 : : static planner_hook_type prev_planner_hook = NULL;
280 : : static ExecutorStart_hook_type prev_ExecutorStart = NULL;
281 : : static ExecutorRun_hook_type prev_ExecutorRun = NULL;
282 : : static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
283 : : static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
284 : : static ProcessUtility_hook_type prev_ProcessUtility = NULL;
285 : :
286 : : /*---- GUC variables ----*/
287 : :
288 : : typedef enum
289 : : {
290 : : PGSS_TRACK_NONE, /* track no statements */
291 : : PGSS_TRACK_TOP, /* only top level statements */
292 : : PGSS_TRACK_ALL, /* all statements, including nested ones */
293 : : } PGSSTrackLevel;
294 : :
295 : : static const struct config_enum_entry track_options[] =
296 : : {
297 : : {"none", PGSS_TRACK_NONE, false},
298 : : {"top", PGSS_TRACK_TOP, false},
299 : : {"all", PGSS_TRACK_ALL, false},
300 : : {NULL, 0, false}
301 : : };
302 : :
303 : : static int pgss_max = 5000; /* max # statements to track */
304 : : static int pgss_track = PGSS_TRACK_TOP; /* tracking level */
305 : : static bool pgss_track_utility = true; /* whether to track utility commands */
306 : : static bool pgss_track_planning = false; /* whether to track planning
307 : : * duration */
308 : : static bool pgss_save = true; /* whether to save stats across shutdown */
309 : :
310 : : #define pgss_enabled(level) \
311 : : (!IsParallelWorker() && \
312 : : (pgss_track == PGSS_TRACK_ALL || \
313 : : (pgss_track == PGSS_TRACK_TOP && (level) == 0)))
314 : :
315 : : #define record_gc_qtexts() \
316 : : do { \
317 : : SpinLockAcquire(&pgss->mutex); \
318 : : pgss->gc_count++; \
319 : : SpinLockRelease(&pgss->mutex); \
320 : : } while(0)
321 : :
322 : : /*---- Function declarations ----*/
323 : :
324 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
325 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_reset_1_7);
326 : 20 : PG_FUNCTION_INFO_V1(pg_stat_statements_reset_1_11);
327 : 0 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_2);
328 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_3);
329 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_8);
330 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_9);
331 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_10);
332 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_11);
333 : 6 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_12);
334 : 24 : PG_FUNCTION_INFO_V1(pg_stat_statements_1_13);
335 : 0 : PG_FUNCTION_INFO_V1(pg_stat_statements);
336 : 8 : PG_FUNCTION_INFO_V1(pg_stat_statements_info);
337 : :
338 : : static void pgss_shmem_shutdown(int code, Datum arg);
339 : : static void pgss_post_parse_analyze(ParseState *pstate, Query *query,
340 : : const JumbleState *jstate);
341 : : static PlannedStmt *pgss_planner(Query *parse,
342 : : const char *query_string,
343 : : int cursorOptions,
344 : : ParamListInfo boundParams,
345 : : ExplainState *es);
346 : : static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags);
347 : : static void pgss_ExecutorRun(QueryDesc *queryDesc,
348 : : ScanDirection direction,
349 : : uint64 count);
350 : : static void pgss_ExecutorFinish(QueryDesc *queryDesc);
351 : : static void pgss_ExecutorEnd(QueryDesc *queryDesc);
352 : : static void pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
353 : : bool readOnlyTree,
354 : : ProcessUtilityContext context, ParamListInfo params,
355 : : QueryEnvironment *queryEnv,
356 : : DestReceiver *dest, QueryCompletion *qc);
357 : : static void pgss_store(const char *query, int64 queryId,
358 : : int query_location, int query_len,
359 : : pgssStoreKind kind,
360 : : double total_time, uint64 rows,
361 : : const BufferUsage *bufusage,
362 : : const WalUsage *walusage,
363 : : const struct JitInstrumentation *jitusage,
364 : : const JumbleState *jstate,
365 : : int parallel_workers_to_launch,
366 : : int parallel_workers_launched,
367 : : PlannedStmtOrigin planOrigin);
368 : : static void pg_stat_statements_internal(FunctionCallInfo fcinfo,
369 : : pgssVersion api_version,
370 : : bool showtext);
371 : : static pgssEntry *entry_alloc(pgssHashKey *key, Size query_offset, int query_len,
372 : : int encoding, bool sticky);
373 : : static void entry_dealloc(void);
374 : : static bool qtext_store(const char *query, int query_len,
375 : : Size *query_offset, int *gc_count);
376 : : static char *qtext_load_file(Size *buffer_size);
377 : : static char *qtext_fetch(Size query_offset, int query_len,
378 : : char *buffer, Size buffer_size);
379 : : static bool need_gc_qtexts(void);
380 : : static void gc_qtexts(void);
381 : : static TimestampTz entry_reset(Oid userid, Oid dbid, int64 queryid, bool minmax_only);
382 : : static char *generate_normalized_query(const JumbleState *jstate,
383 : : const char *query,
384 : : int query_loc, int *query_len_p);
385 : :
386 : : /*
387 : : * Module load callback
388 : : */
389 : : void
390 : 10 : _PG_init(void)
391 : : {
392 : : /*
393 : : * In order to create our shared memory area, we have to be loaded via
394 : : * shared_preload_libraries. If not, fall out without hooking into any of
395 : : * the main system. (We don't throw error here because it seems useful to
396 : : * allow the pg_stat_statements functions to be created even when the
397 : : * module isn't active. The functions must protect themselves against
398 : : * being called then, however.)
399 : : */
400 [ + + ]: 10 : if (!process_shared_preload_libraries_in_progress)
401 : 1 : return;
402 : :
403 : : /*
404 : : * Inform the postmaster that we want to enable query_id calculation if
405 : : * compute_query_id is set to auto.
406 : : */
407 : 9 : EnableQueryId();
408 : :
409 : : /*
410 : : * Define (or redefine) custom GUC variables.
411 : : */
412 : 9 : DefineCustomIntVariable("pg_stat_statements.max",
413 : : "Sets the maximum number of statements tracked by pg_stat_statements.",
414 : : NULL,
415 : : &pgss_max,
416 : : 5000,
417 : : 100,
418 : : INT_MAX / 2,
419 : : PGC_POSTMASTER,
420 : : 0,
421 : : NULL,
422 : : NULL,
423 : : NULL);
424 : :
425 : 9 : DefineCustomEnumVariable("pg_stat_statements.track",
426 : : "Selects which statements are tracked by pg_stat_statements.",
427 : : NULL,
428 : : &pgss_track,
429 : : PGSS_TRACK_TOP,
430 : : track_options,
431 : : PGC_SUSET,
432 : : 0,
433 : : NULL,
434 : : NULL,
435 : : NULL);
436 : :
437 : 9 : DefineCustomBoolVariable("pg_stat_statements.track_utility",
438 : : "Selects whether utility commands are tracked by pg_stat_statements.",
439 : : NULL,
440 : : &pgss_track_utility,
441 : : true,
442 : : PGC_SUSET,
443 : : 0,
444 : : NULL,
445 : : NULL,
446 : : NULL);
447 : :
448 : 9 : DefineCustomBoolVariable("pg_stat_statements.track_planning",
449 : : "Selects whether planning duration is tracked by pg_stat_statements.",
450 : : NULL,
451 : : &pgss_track_planning,
452 : : false,
453 : : PGC_SUSET,
454 : : 0,
455 : : NULL,
456 : : NULL,
457 : : NULL);
458 : :
459 : 9 : DefineCustomBoolVariable("pg_stat_statements.save",
460 : : "Save pg_stat_statements statistics across server shutdowns.",
461 : : NULL,
462 : : &pgss_save,
463 : : true,
464 : : PGC_SIGHUP,
465 : : 0,
466 : : NULL,
467 : : NULL,
468 : : NULL);
469 : :
470 : 9 : MarkGUCPrefixReserved("pg_stat_statements");
471 : :
472 : : /*
473 : : * Register our shared memory needs.
474 : : */
475 : 9 : RegisterShmemCallbacks(&pgss_shmem_callbacks);
476 : :
477 : : /*
478 : : * Install hooks.
479 : : */
480 : 9 : prev_post_parse_analyze_hook = post_parse_analyze_hook;
481 : 9 : post_parse_analyze_hook = pgss_post_parse_analyze;
482 : 9 : prev_planner_hook = planner_hook;
483 : 9 : planner_hook = pgss_planner;
484 : 9 : prev_ExecutorStart = ExecutorStart_hook;
485 : 9 : ExecutorStart_hook = pgss_ExecutorStart;
486 : 9 : prev_ExecutorRun = ExecutorRun_hook;
487 : 9 : ExecutorRun_hook = pgss_ExecutorRun;
488 : 9 : prev_ExecutorFinish = ExecutorFinish_hook;
489 : 9 : ExecutorFinish_hook = pgss_ExecutorFinish;
490 : 9 : prev_ExecutorEnd = ExecutorEnd_hook;
491 : 9 : ExecutorEnd_hook = pgss_ExecutorEnd;
492 : 9 : prev_ProcessUtility = ProcessUtility_hook;
493 : 9 : ProcessUtility_hook = pgss_ProcessUtility;
494 : : }
495 : :
496 : : /*
497 : : * shmem request callback: Request shared memory resources.
498 : : *
499 : : * This is called at postmaster startup. Note that the shared memory isn't
500 : : * allocated here yet, this merely register our needs.
501 : : *
502 : : * In EXEC_BACKEND mode, this is also called in each backend, to re-attach to
503 : : * the shared memory area that was already initialized.
504 : : */
505 : : static void
506 : 11 : pgss_shmem_request(void *arg)
507 : : {
508 : 11 : ShmemRequestHash(.name = "pg_stat_statements hash",
509 : : .nelems = (int64) pgss_max,
510 : : .hash_info.keysize = sizeof(pgssHashKey),
511 : : .hash_info.entrysize = sizeof(pgssEntry),
512 : : .hash_flags = HASH_ELEM | HASH_BLOBS,
513 : : .ptr = &pgss_hash,
514 : : );
515 : 11 : ShmemRequestStruct(.name = "pg_stat_statements",
516 : : .size = sizeof(pgssSharedState),
517 : : .ptr = (void **) &pgss,
518 : : );
519 : 11 : }
520 : :
521 : : /*
522 : : * shmem init callback: Initialize our shared memory data structures at
523 : : * postmaster startup.
524 : : *
525 : : * Load any pre-existing statistics from file. Also create and load the
526 : : * query-texts file, which is expected to exist (even if empty) while the
527 : : * module is enabled.
528 : : */
529 : : static void
530 : 11 : pgss_shmem_init(void *arg)
531 : : {
532 : : int tranche_id;
533 : 11 : FILE *file = NULL;
534 : 11 : FILE *qfile = NULL;
535 : : uint32 header;
536 : : int64 num;
537 : : uint32 pgver;
538 : : int buffer_size;
539 : 11 : char *buffer = NULL;
540 : :
541 : : /*
542 : : * We already checked that we're loaded from shared_preload_libraries in
543 : : * _PG_init(), so we should not get here after postmaster startup.
544 : : */
545 : : Assert(!IsUnderPostmaster);
546 : :
547 : : /*
548 : : * Initialize the shmem area with no statistics.
549 : : */
550 : 11 : tranche_id = LWLockNewTrancheId("pg_stat_statements");
551 : 11 : LWLockInitialize(&pgss->lock.lock, tranche_id);
552 : 11 : pgss->cur_median_usage = ASSUMED_MEDIAN_INIT;
553 : 11 : pgss->mean_query_len = ASSUMED_LENGTH_INIT;
554 : 11 : SpinLockInit(&pgss->mutex);
555 : 11 : pgss->extent = 0;
556 : 11 : pgss->n_writers = 0;
557 : 11 : pgss->gc_count = 0;
558 : 11 : pgss->stats.dealloc = 0;
559 : 11 : pgss->stats.stats_reset = GetCurrentTimestamp();
560 : :
561 : : /* The hash table must've also been initialized by now */
562 : : Assert(pgss_hash != NULL);
563 : :
564 : : /*
565 : : * Set up a shmem exit hook to dump the statistics to disk on postmaster
566 : : * (or standalone backend) exit.
567 : : */
568 : 11 : on_shmem_exit(pgss_shmem_shutdown, (Datum) 0);
569 : :
570 : : /*
571 : : * Load any pre-existing statistics from file.
572 : : *
573 : : * Note: we don't bother with locks here, because there should be no other
574 : : * processes running when this code is reached.
575 : : */
576 : :
577 : : /* Unlink query text file possibly left over from crash */
578 : 11 : unlink(PGSS_TEXT_FILE);
579 : :
580 : : /* Allocate new query text temp file */
581 : 11 : qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
582 [ - + ]: 11 : if (qfile == NULL)
583 : 0 : goto write_error;
584 : :
585 : : /*
586 : : * If we were told not to load old statistics, we're done. (Note we do
587 : : * not try to unlink any old dump file in this case. This seems a bit
588 : : * questionable but it's the historical behavior.)
589 : : */
590 [ + + ]: 11 : if (!pgss_save)
591 : : {
592 : 1 : FreeFile(qfile);
593 : 11 : return;
594 : : }
595 : :
596 : : /*
597 : : * Attempt to load old statistics from the dump file.
598 : : */
599 : 10 : file = AllocateFile(PGSS_DUMP_FILE, PG_BINARY_R);
600 [ + + ]: 10 : if (file == NULL)
601 : : {
602 [ - + ]: 7 : if (errno != ENOENT)
603 : 0 : goto read_error;
604 : : /* No existing persisted stats file, so we're done */
605 : 7 : FreeFile(qfile);
606 : 7 : return;
607 : : }
608 : :
609 : 3 : buffer_size = 2048;
610 : 3 : buffer = (char *) palloc(buffer_size);
611 : :
612 [ + - + - ]: 6 : if (fread(&header, sizeof(uint32), 1, file) != 1 ||
613 [ - + ]: 6 : fread(&pgver, sizeof(uint32), 1, file) != 1 ||
614 : 3 : fread(&num, sizeof(int64), 1, file) != 1)
615 : 0 : goto read_error;
616 : :
617 [ + - ]: 3 : if (header != PGSS_FILE_HEADER ||
618 [ - + ]: 3 : pgver != PGSS_PG_MAJOR_VERSION)
619 : 0 : goto data_error;
620 : :
621 [ + + ]: 29523 : for (int64 i = 0; i < num; i++)
622 : : {
623 : : pgssEntry temp;
624 : : pgssEntry *entry;
625 : : Size query_offset;
626 : :
627 [ - + ]: 29520 : if (fread(&temp, sizeof(pgssEntry), 1, file) != 1)
628 : 0 : goto read_error;
629 : :
630 : : /* Encoding is the only field we can easily sanity-check */
631 [ + - + - : 29520 : if (!PG_VALID_BE_ENCODING(temp.encoding))
- + ]
632 : 0 : goto data_error;
633 : :
634 : : /* Resize buffer as needed */
635 [ + + ]: 29520 : if (temp.query_len >= buffer_size)
636 : : {
637 : 1 : buffer_size = Max(buffer_size * 2, temp.query_len + 1);
638 : 1 : buffer = repalloc(buffer, buffer_size);
639 : : }
640 : :
641 [ - + ]: 29520 : if (fread(buffer, 1, temp.query_len + 1, file) != temp.query_len + 1)
642 : 0 : goto read_error;
643 : :
644 : : /* Should have a trailing null, but let's make sure */
645 : 29520 : buffer[temp.query_len] = '\0';
646 : :
647 : : /* Skip loading "sticky" entries */
648 [ + + ]: 29520 : if (IS_STICKY(temp.counters))
649 : 806 : continue;
650 : :
651 : : /* Store the query text */
652 : 28714 : query_offset = pgss->extent;
653 [ - + ]: 28714 : if (fwrite(buffer, 1, temp.query_len + 1, qfile) != temp.query_len + 1)
654 : 0 : goto write_error;
655 : 28714 : pgss->extent += temp.query_len + 1;
656 : :
657 : : /* make the hashtable entry (discards old entries if too many) */
658 : 28714 : entry = entry_alloc(&temp.key, query_offset, temp.query_len,
659 : : temp.encoding,
660 : : false);
661 : :
662 : : /* copy in the actual stats */
663 : 28714 : entry->counters = temp.counters;
664 : 28714 : entry->stats_since = temp.stats_since;
665 : 28714 : entry->minmax_stats_since = temp.minmax_stats_since;
666 : : }
667 : :
668 : : /* Read global statistics for pg_stat_statements */
669 [ - + ]: 3 : if (fread(&pgss->stats, sizeof(pgssGlobalStats), 1, file) != 1)
670 : 0 : goto read_error;
671 : :
672 : 3 : pfree(buffer);
673 : 3 : FreeFile(file);
674 : 3 : FreeFile(qfile);
675 : :
676 : : /*
677 : : * Remove the persisted stats file so it's not included in
678 : : * backups/replication standbys, etc. A new file will be written on next
679 : : * shutdown.
680 : : *
681 : : * Note: it's okay if the PGSS_TEXT_FILE is included in a basebackup,
682 : : * because we remove that file on startup; it acts inversely to
683 : : * PGSS_DUMP_FILE, in that it is only supposed to be around when the
684 : : * server is running, whereas PGSS_DUMP_FILE is only supposed to be around
685 : : * when the server is not running. Leaving the file creates no danger of
686 : : * a newly restored database having a spurious record of execution costs,
687 : : * which is what we're really concerned about here.
688 : : */
689 : 3 : unlink(PGSS_DUMP_FILE);
690 : :
691 : 3 : return;
692 : :
693 : 0 : read_error:
694 [ # # ]: 0 : ereport(LOG,
695 : : (errcode_for_file_access(),
696 : : errmsg("could not read file \"%s\": %m",
697 : : PGSS_DUMP_FILE)));
698 : 0 : goto fail;
699 : 0 : data_error:
700 [ # # ]: 0 : ereport(LOG,
701 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
702 : : errmsg("ignoring invalid data in file \"%s\"",
703 : : PGSS_DUMP_FILE)));
704 : 0 : goto fail;
705 : 0 : write_error:
706 [ # # ]: 0 : ereport(LOG,
707 : : (errcode_for_file_access(),
708 : : errmsg("could not write file \"%s\": %m",
709 : : PGSS_TEXT_FILE)));
710 : 0 : fail:
711 [ # # ]: 0 : if (buffer)
712 : 0 : pfree(buffer);
713 [ # # ]: 0 : if (file)
714 : 0 : FreeFile(file);
715 [ # # ]: 0 : if (qfile)
716 : 0 : FreeFile(qfile);
717 : : /* If possible, throw away the bogus file; ignore any error */
718 : 0 : unlink(PGSS_DUMP_FILE);
719 : :
720 : : /*
721 : : * Don't unlink PGSS_TEXT_FILE here; it should always be around while the
722 : : * server is running with pg_stat_statements enabled
723 : : */
724 : : }
725 : :
726 : : /*
727 : : * shmem_shutdown hook: Dump statistics into file.
728 : : *
729 : : * Note: we don't bother with acquiring lock, because there should be no
730 : : * other processes running when this is called.
731 : : */
732 : : static void
733 : 11 : pgss_shmem_shutdown(int code, Datum arg)
734 : : {
735 : : FILE *file;
736 : 11 : char *qbuffer = NULL;
737 : 11 : Size qbuffer_size = 0;
738 : : HASH_SEQ_STATUS hash_seq;
739 : : int64 num_entries;
740 : : pgssEntry *entry;
741 : :
742 : : /* Don't try to dump during a crash. */
743 [ + + ]: 11 : if (code)
744 : 11 : return;
745 : :
746 : : /* Safety check ... shouldn't get here unless shmem is set up. */
747 [ + - - + ]: 9 : if (!pgss || !pgss_hash)
748 : 0 : return;
749 : :
750 : : /* Don't dump if told not to. */
751 [ + + ]: 9 : if (!pgss_save)
752 : 2 : return;
753 : :
754 : 7 : file = AllocateFile(PGSS_DUMP_FILE ".tmp", PG_BINARY_W);
755 [ - + ]: 7 : if (file == NULL)
756 : 0 : goto error;
757 : :
758 [ - + ]: 7 : if (fwrite(&PGSS_FILE_HEADER, sizeof(uint32), 1, file) != 1)
759 : 0 : goto error;
760 [ - + ]: 7 : if (fwrite(&PGSS_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
761 : 0 : goto error;
762 : 7 : num_entries = hash_get_num_entries(pgss_hash);
763 [ - + ]: 7 : if (fwrite(&num_entries, sizeof(int64), 1, file) != 1)
764 : 0 : goto error;
765 : :
766 : 7 : qbuffer = qtext_load_file(&qbuffer_size);
767 [ - + ]: 7 : if (qbuffer == NULL)
768 : 0 : goto error;
769 : :
770 : : /*
771 : : * When serializing to disk, we store query texts immediately after their
772 : : * entry data. Any orphaned query texts are thereby excluded.
773 : : */
774 : 7 : hash_seq_init(&hash_seq, pgss_hash);
775 [ + + ]: 59322 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
776 : : {
777 : 59315 : int len = entry->query_len;
778 : 59315 : char *qstr = qtext_fetch(entry->query_offset, len,
779 : : qbuffer, qbuffer_size);
780 : :
781 [ - + ]: 59315 : if (qstr == NULL)
782 : 0 : continue; /* Ignore any entries with bogus texts */
783 : :
784 [ + - ]: 59315 : if (fwrite(entry, sizeof(pgssEntry), 1, file) != 1 ||
785 [ - + ]: 59315 : fwrite(qstr, 1, len + 1, file) != len + 1)
786 : : {
787 : : /* note: we assume hash_seq_term won't change errno */
788 : 0 : hash_seq_term(&hash_seq);
789 : 0 : goto error;
790 : : }
791 : : }
792 : :
793 : : /* Dump global statistics for pg_stat_statements */
794 [ - + ]: 7 : if (fwrite(&pgss->stats, sizeof(pgssGlobalStats), 1, file) != 1)
795 : 0 : goto error;
796 : :
797 : 7 : pfree(qbuffer);
798 : 7 : qbuffer = NULL;
799 : :
800 [ - + ]: 7 : if (FreeFile(file))
801 : : {
802 : 0 : file = NULL;
803 : 0 : goto error;
804 : : }
805 : :
806 : : /*
807 : : * Rename file into place, so we atomically replace any old one.
808 : : */
809 : 7 : (void) durable_rename(PGSS_DUMP_FILE ".tmp", PGSS_DUMP_FILE, LOG);
810 : :
811 : : /* Unlink query-texts file; it's not needed while shutdown */
812 : 7 : unlink(PGSS_TEXT_FILE);
813 : :
814 : 7 : return;
815 : :
816 : 0 : error:
817 [ # # ]: 0 : ereport(LOG,
818 : : (errcode_for_file_access(),
819 : : errmsg("could not write file \"%s\": %m",
820 : : PGSS_DUMP_FILE ".tmp")));
821 [ # # ]: 0 : if (qbuffer)
822 : 0 : pfree(qbuffer);
823 [ # # ]: 0 : if (file)
824 : 0 : FreeFile(file);
825 : 0 : unlink(PGSS_DUMP_FILE ".tmp");
826 : 0 : unlink(PGSS_TEXT_FILE);
827 : : }
828 : :
829 : : /*
830 : : * Post-parse-analysis hook: mark query with a queryId
831 : : */
832 : : static void
833 : 85368 : pgss_post_parse_analyze(ParseState *pstate, Query *query, const JumbleState *jstate)
834 : : {
835 [ - + ]: 85368 : if (prev_post_parse_analyze_hook)
836 : 0 : prev_post_parse_analyze_hook(pstate, query, jstate);
837 : :
838 : : /* Safety check... */
839 [ + - + - : 85368 : if (!pgss || !pgss_hash || !pgss_enabled(nesting_level))
+ + + + +
+ + + ]
840 : 13208 : return;
841 : :
842 : : /*
843 : : * If it's EXECUTE, clear the queryId so that stats will accumulate for
844 : : * the underlying PREPARE. But don't do this if we're not tracking
845 : : * utility statements, to avoid messing up another extension that might be
846 : : * tracking them.
847 : : */
848 [ + + ]: 72160 : if (query->utilityStmt)
849 : : {
850 [ + + + + ]: 32510 : if (pgss_track_utility && IsA(query->utilityStmt, ExecuteStmt))
851 : : {
852 : 3378 : query->queryId = INT64CONST(0);
853 : 3378 : return;
854 : : }
855 : : }
856 : :
857 : : /*
858 : : * If query jumbling were able to identify any ignorable constants, we
859 : : * immediately create a hash table entry for the query, so that we can
860 : : * record the normalized form of the query string. If there were no such
861 : : * constants, the normalized string would be the same as the query text
862 : : * anyway, so there's no need for an early entry.
863 : : */
864 [ + - + + ]: 68782 : if (jstate && jstate->clocations_count > 0)
865 : 39514 : pgss_store(pstate->p_sourcetext,
866 : : query->queryId,
867 : : query->stmt_location,
868 : : query->stmt_len,
869 : : PGSS_INVALID,
870 : : 0,
871 : : 0,
872 : : NULL,
873 : : NULL,
874 : : NULL,
875 : : jstate,
876 : : 0,
877 : : 0,
878 : : PLAN_STMT_UNKNOWN);
879 : : }
880 : :
881 : : /*
882 : : * Planner hook: forward to regular planner, but measure planning time
883 : : * if needed.
884 : : */
885 : : static PlannedStmt *
886 : 51145 : pgss_planner(Query *parse,
887 : : const char *query_string,
888 : : int cursorOptions,
889 : : ParamListInfo boundParams,
890 : : ExplainState *es)
891 : : {
892 : : PlannedStmt *result;
893 : :
894 : : /*
895 : : * We can't process the query if no query_string is provided, as
896 : : * pgss_store needs it. We also ignore query without queryid, as it would
897 : : * be treated as a utility statement, which may not be the case.
898 : : */
899 [ + + + + : 51145 : if (pgss_enabled(nesting_level)
+ + + + ]
900 [ + + + - ]: 39798 : && pgss_track_planning && query_string
901 [ + - ]: 150 : && parse->queryId != INT64CONST(0))
902 : 150 : {
903 : : instr_time start;
904 : : instr_time duration;
905 : : BufferUsage bufusage_start,
906 : : bufusage;
907 : : WalUsage walusage_start,
908 : : walusage;
909 : :
910 : : /* We need to track buffer usage as the planner can access them. */
911 : 150 : bufusage_start = pgBufferUsage;
912 : :
913 : : /*
914 : : * Similarly the planner could write some WAL records in some cases
915 : : * (e.g. setting a hint bit with those being WAL-logged)
916 : : */
917 : 150 : walusage_start = pgWalUsage;
918 : 150 : INSTR_TIME_SET_CURRENT(start);
919 : :
920 : 150 : nesting_level++;
921 [ + - ]: 150 : PG_TRY();
922 : : {
923 [ - + ]: 150 : if (prev_planner_hook)
924 : 0 : result = prev_planner_hook(parse, query_string, cursorOptions,
925 : : boundParams, es);
926 : : else
927 : 150 : result = standard_planner(parse, query_string, cursorOptions,
928 : : boundParams, es);
929 : : }
930 : 0 : PG_FINALLY();
931 : : {
932 : 150 : nesting_level--;
933 : : }
934 [ - + ]: 150 : PG_END_TRY();
935 : :
936 : 150 : INSTR_TIME_SET_CURRENT(duration);
937 : 150 : INSTR_TIME_SUBTRACT(duration, start);
938 : :
939 : : /* calc differences of buffer counters. */
940 : 150 : memset(&bufusage, 0, sizeof(BufferUsage));
941 : 150 : BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
942 : :
943 : : /* calc differences of WAL counters. */
944 : 150 : memset(&walusage, 0, sizeof(WalUsage));
945 : 150 : WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
946 : :
947 : 300 : pgss_store(query_string,
948 : : parse->queryId,
949 : : parse->stmt_location,
950 : : parse->stmt_len,
951 : : PGSS_PLAN,
952 : 150 : INSTR_TIME_GET_MILLISEC(duration),
953 : : 0,
954 : : &bufusage,
955 : : &walusage,
956 : : NULL,
957 : : NULL,
958 : : 0,
959 : : 0,
960 : : result->planOrigin);
961 : : }
962 : : else
963 : : {
964 : : /*
965 : : * Even though we're not tracking plan time for this statement, we
966 : : * must still increment the nesting level, to ensure that functions
967 : : * evaluated during planning are not seen as top-level calls.
968 : : */
969 : 50995 : nesting_level++;
970 [ + + ]: 50995 : PG_TRY();
971 : : {
972 [ - + ]: 50995 : if (prev_planner_hook)
973 : 0 : result = prev_planner_hook(parse, query_string, cursorOptions,
974 : : boundParams, es);
975 : : else
976 : 50995 : result = standard_planner(parse, query_string, cursorOptions,
977 : : boundParams, es);
978 : : }
979 : 792 : PG_FINALLY();
980 : : {
981 : 50995 : nesting_level--;
982 : : }
983 [ + + ]: 50995 : PG_END_TRY();
984 : : }
985 : :
986 : 50353 : return result;
987 : : }
988 : :
989 : : /*
990 : : * ExecutorStart hook: start up tracking if needed
991 : : */
992 : : static void
993 : 61181 : pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
994 : : {
995 : : /*
996 : : * If query has queryId zero, don't track it. This prevents double
997 : : * counting of optimizable statements that are directly contained in
998 : : * utility statements.
999 : : */
1000 [ + + + + : 61181 : if (pgss_enabled(nesting_level) && queryDesc->plannedstmt->queryId != INT64CONST(0))
+ + + + +
+ ]
1001 : : {
1002 : : /* Request all summary instrumentation, i.e. timing, buffers and WAL */
1003 : 41978 : queryDesc->query_instr_options |= INSTRUMENT_ALL;
1004 : : }
1005 : :
1006 [ - + ]: 61181 : if (prev_ExecutorStart)
1007 : 0 : prev_ExecutorStart(queryDesc, eflags);
1008 : : else
1009 : 61181 : standard_ExecutorStart(queryDesc, eflags);
1010 : 60894 : }
1011 : :
1012 : : /*
1013 : : * ExecutorRun hook: all we need do is track nesting depth
1014 : : */
1015 : : static void
1016 : 59473 : pgss_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
1017 : : {
1018 : 59473 : nesting_level++;
1019 [ + + ]: 59473 : PG_TRY();
1020 : : {
1021 [ - + ]: 59473 : if (prev_ExecutorRun)
1022 : 0 : prev_ExecutorRun(queryDesc, direction, count);
1023 : : else
1024 : 59473 : standard_ExecutorRun(queryDesc, direction, count);
1025 : : }
1026 : 3433 : PG_FINALLY();
1027 : : {
1028 : 59473 : nesting_level--;
1029 : : }
1030 [ + + ]: 59473 : PG_END_TRY();
1031 : 56040 : }
1032 : :
1033 : : /*
1034 : : * ExecutorFinish hook: all we need do is track nesting depth
1035 : : */
1036 : : static void
1037 : 53971 : pgss_ExecutorFinish(QueryDesc *queryDesc)
1038 : : {
1039 : 53971 : nesting_level++;
1040 [ + + ]: 53971 : PG_TRY();
1041 : : {
1042 [ - + ]: 53971 : if (prev_ExecutorFinish)
1043 : 0 : prev_ExecutorFinish(queryDesc);
1044 : : else
1045 : 53971 : standard_ExecutorFinish(queryDesc);
1046 : : }
1047 : 182 : PG_FINALLY();
1048 : : {
1049 : 53971 : nesting_level--;
1050 : : }
1051 [ + + ]: 53971 : PG_END_TRY();
1052 : 53789 : }
1053 : :
1054 : : /*
1055 : : * ExecutorEnd hook: store results if needed
1056 : : */
1057 : : static void
1058 : 56948 : pgss_ExecutorEnd(QueryDesc *queryDesc)
1059 : : {
1060 : 56948 : int64 queryId = queryDesc->plannedstmt->queryId;
1061 : :
1062 [ + + + + ]: 56948 : if (queryId != INT64CONST(0) && queryDesc->query_instr &&
1063 [ + - + + : 40004 : pgss_enabled(nesting_level))
+ - + - ]
1064 : : {
1065 : 40004 : pgss_store(queryDesc->sourceText,
1066 : : queryId,
1067 : 40004 : queryDesc->plannedstmt->stmt_location,
1068 : 40004 : queryDesc->plannedstmt->stmt_len,
1069 : : PGSS_EXEC,
1070 : 40004 : INSTR_TIME_GET_MILLISEC(queryDesc->query_instr->total),
1071 : 40004 : queryDesc->estate->es_total_processed,
1072 : 40004 : &queryDesc->query_instr->bufusage,
1073 : 40004 : &queryDesc->query_instr->walusage,
1074 : 0 : queryDesc->estate->es_jit ? &queryDesc->estate->es_jit->instr : NULL,
1075 : : NULL,
1076 : 40004 : queryDesc->estate->es_parallel_workers_to_launch,
1077 : 40004 : queryDesc->estate->es_parallel_workers_launched,
1078 [ - + ]: 40004 : queryDesc->plannedstmt->planOrigin);
1079 : : }
1080 : :
1081 [ - + ]: 56948 : if (prev_ExecutorEnd)
1082 : 0 : prev_ExecutorEnd(queryDesc);
1083 : : else
1084 : 56948 : standard_ExecutorEnd(queryDesc);
1085 : 56948 : }
1086 : :
1087 : : /*
1088 : : * ProcessUtility hook
1089 : : */
1090 : : static void
1091 : 38168 : pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
1092 : : bool readOnlyTree,
1093 : : ProcessUtilityContext context,
1094 : : ParamListInfo params, QueryEnvironment *queryEnv,
1095 : : DestReceiver *dest, QueryCompletion *qc)
1096 : : {
1097 : 38168 : Node *parsetree = pstmt->utilityStmt;
1098 : 38168 : int64 saved_queryId = pstmt->queryId;
1099 : 38168 : int saved_stmt_location = pstmt->stmt_location;
1100 : 38168 : int saved_stmt_len = pstmt->stmt_len;
1101 : 38168 : PlannedStmtOrigin saved_planOrigin = pstmt->planOrigin;
1102 [ + + + - : 38168 : bool enabled = pgss_track_utility && pgss_enabled(nesting_level);
+ + + - +
+ ]
1103 : :
1104 : : /*
1105 : : * Force utility statements to get queryId zero. We do this even in cases
1106 : : * where the statement contains an optimizable statement for which a
1107 : : * queryId could be derived (such as EXPLAIN or DECLARE CURSOR). For such
1108 : : * cases, runtime control will first go through ProcessUtility and then
1109 : : * the executor, and we don't want the executor hooks to do anything,
1110 : : * since we are already measuring the statement's costs at the utility
1111 : : * level.
1112 : : *
1113 : : * Note that this is only done if pg_stat_statements is enabled and
1114 : : * configured to track utility statements, in the unlikely possibility
1115 : : * that user configured another extension to handle utility statements
1116 : : * only.
1117 : : */
1118 [ + + ]: 38168 : if (enabled)
1119 : 32396 : pstmt->queryId = INT64CONST(0);
1120 : :
1121 : : /*
1122 : : * If it's an EXECUTE statement, we don't track it and don't increment the
1123 : : * nesting level. This allows the cycles to be charged to the underlying
1124 : : * PREPARE instead (by the Executor hooks), which is much more useful.
1125 : : *
1126 : : * We also don't track execution of PREPARE. If we did, we would get one
1127 : : * hash table entry for the PREPARE (with hash calculated from the query
1128 : : * string), and then a different one with the same query string (but hash
1129 : : * calculated from the query tree) would be used to accumulate costs of
1130 : : * ensuing EXECUTEs. This would be confusing. Since PREPARE doesn't
1131 : : * actually run the planner (only parse+rewrite), its costs are generally
1132 : : * pretty negligible and it seems okay to just ignore it.
1133 : : */
1134 [ + + ]: 38168 : if (enabled &&
1135 [ + + ]: 32396 : !IsA(parsetree, ExecuteStmt) &&
1136 [ + + ]: 29024 : !IsA(parsetree, PrepareStmt))
1137 : 26161 : {
1138 : : instr_time start;
1139 : : instr_time duration;
1140 : : uint64 rows;
1141 : : BufferUsage bufusage_start,
1142 : : bufusage;
1143 : : WalUsage walusage_start,
1144 : : walusage;
1145 : :
1146 : 28896 : bufusage_start = pgBufferUsage;
1147 : 28896 : walusage_start = pgWalUsage;
1148 : 28896 : INSTR_TIME_SET_CURRENT(start);
1149 : :
1150 : 28896 : nesting_level++;
1151 [ + + ]: 28896 : PG_TRY();
1152 : : {
1153 [ - + ]: 28896 : if (prev_ProcessUtility)
1154 : 0 : prev_ProcessUtility(pstmt, queryString, readOnlyTree,
1155 : : context, params, queryEnv,
1156 : : dest, qc);
1157 : : else
1158 : 28896 : standard_ProcessUtility(pstmt, queryString, readOnlyTree,
1159 : : context, params, queryEnv,
1160 : : dest, qc);
1161 : : }
1162 : 2735 : PG_FINALLY();
1163 : : {
1164 : 28896 : nesting_level--;
1165 : : }
1166 [ + + ]: 28896 : PG_END_TRY();
1167 : :
1168 : : /*
1169 : : * CAUTION: do not access the *pstmt data structure again below here.
1170 : : * If it was a ROLLBACK or similar, that data structure may have been
1171 : : * freed. We must copy everything we still need into local variables,
1172 : : * which we did above.
1173 : : *
1174 : : * For the same reason, we can't risk restoring pstmt->queryId to its
1175 : : * former value, which'd otherwise be a good idea.
1176 : : */
1177 : 26161 : pstmt = NULL;
1178 : :
1179 : 26161 : INSTR_TIME_SET_CURRENT(duration);
1180 : 26161 : INSTR_TIME_SUBTRACT(duration, start);
1181 : :
1182 : : /*
1183 : : * Track the total number of rows retrieved or affected by the utility
1184 : : * statements of COPY, FETCH, CREATE TABLE AS, CREATE MATERIALIZED
1185 : : * VIEW, REFRESH MATERIALIZED VIEW and SELECT INTO.
1186 : : */
1187 [ + + ]: 26158 : rows = (qc && (qc->commandTag == CMDTAG_COPY ||
1188 [ + + ]: 24340 : qc->commandTag == CMDTAG_FETCH ||
1189 [ + + ]: 24076 : qc->commandTag == CMDTAG_SELECT ||
1190 [ + + ]: 23882 : qc->commandTag == CMDTAG_REFRESH_MATERIALIZED_VIEW)) ?
1191 [ + + ]: 52319 : qc->nprocessed : 0;
1192 : :
1193 : : /* calc differences of buffer counters. */
1194 : 26161 : memset(&bufusage, 0, sizeof(BufferUsage));
1195 : 26161 : BufferUsageAccumDiff(&bufusage, &pgBufferUsage, &bufusage_start);
1196 : :
1197 : : /* calc differences of WAL counters. */
1198 : 26161 : memset(&walusage, 0, sizeof(WalUsage));
1199 : 26161 : WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
1200 : :
1201 : 26161 : pgss_store(queryString,
1202 : : saved_queryId,
1203 : : saved_stmt_location,
1204 : : saved_stmt_len,
1205 : : PGSS_EXEC,
1206 : 26161 : INSTR_TIME_GET_MILLISEC(duration),
1207 : : rows,
1208 : : &bufusage,
1209 : : &walusage,
1210 : : NULL,
1211 : : NULL,
1212 : : 0,
1213 : : 0,
1214 : : saved_planOrigin);
1215 : : }
1216 : : else
1217 : : {
1218 : : /*
1219 : : * Even though we're not tracking execution time for this statement,
1220 : : * we must still increment the nesting level, to ensure that functions
1221 : : * evaluated within it are not seen as top-level calls. But don't do
1222 : : * so for EXECUTE; that way, when control reaches pgss_planner or
1223 : : * pgss_ExecutorStart, we will treat the costs as top-level if
1224 : : * appropriate. Likewise, don't bump for PREPARE, so that parse
1225 : : * analysis will treat the statement as top-level if appropriate.
1226 : : *
1227 : : * To be absolutely certain we don't mess up the nesting level,
1228 : : * evaluate the bump_level condition just once.
1229 : : */
1230 : 9272 : bool bump_level =
1231 [ + + ]: 15171 : !IsA(parsetree, ExecuteStmt) &&
1232 [ + + ]: 5899 : !IsA(parsetree, PrepareStmt);
1233 : :
1234 [ + + ]: 9272 : if (bump_level)
1235 : 5770 : nesting_level++;
1236 [ + + ]: 9272 : PG_TRY();
1237 : : {
1238 [ - + ]: 9272 : if (prev_ProcessUtility)
1239 : 0 : prev_ProcessUtility(pstmt, queryString, readOnlyTree,
1240 : : context, params, queryEnv,
1241 : : dest, qc);
1242 : : else
1243 : 9272 : standard_ProcessUtility(pstmt, queryString, readOnlyTree,
1244 : : context, params, queryEnv,
1245 : : dest, qc);
1246 : : }
1247 : 140 : PG_FINALLY();
1248 : : {
1249 [ + + ]: 9272 : if (bump_level)
1250 : 5770 : nesting_level--;
1251 : : }
1252 [ + + ]: 9272 : PG_END_TRY();
1253 : : }
1254 : 35293 : }
1255 : :
1256 : : /*
1257 : : * Store some statistics for a statement.
1258 : : *
1259 : : * If jstate is not NULL then we're trying to create an entry for which
1260 : : * we have no statistics as yet; we just want to record the normalized
1261 : : * query string. total_time, rows, bufusage and walusage are ignored in this
1262 : : * case.
1263 : : *
1264 : : * If kind is PGSS_PLAN or PGSS_EXEC, its value is used as the array position
1265 : : * for the arrays in the Counters field.
1266 : : */
1267 : : static void
1268 : 105829 : pgss_store(const char *query, int64 queryId,
1269 : : int query_location, int query_len,
1270 : : pgssStoreKind kind,
1271 : : double total_time, uint64 rows,
1272 : : const BufferUsage *bufusage,
1273 : : const WalUsage *walusage,
1274 : : const struct JitInstrumentation *jitusage,
1275 : : const JumbleState *jstate,
1276 : : int parallel_workers_to_launch,
1277 : : int parallel_workers_launched,
1278 : : PlannedStmtOrigin planOrigin)
1279 : : {
1280 : : pgssHashKey key;
1281 : : pgssEntry *entry;
1282 : 105829 : char *norm_query = NULL;
1283 : 105829 : int encoding = GetDatabaseEncoding();
1284 : :
1285 : : Assert(query != NULL);
1286 : :
1287 : : /* Safety check... */
1288 [ + - - + ]: 105829 : if (!pgss || !pgss_hash)
1289 : 0 : return;
1290 : :
1291 : : /*
1292 : : * Nothing to do if compute_query_id isn't enabled and no other module
1293 : : * computed a query identifier.
1294 : : */
1295 [ - + ]: 105829 : if (queryId == INT64CONST(0))
1296 : 0 : return;
1297 : :
1298 : : /*
1299 : : * Confine our attention to the relevant part of the string, if the query
1300 : : * is a portion of a multi-statement source string, and update query
1301 : : * location and length if needed.
1302 : : */
1303 : 105829 : query = CleanQuerytext(query, &query_location, &query_len);
1304 : :
1305 : : /* Set up key for hashtable search */
1306 : :
1307 : : /* clear padding */
1308 : 105829 : memset(&key, 0, sizeof(pgssHashKey));
1309 : :
1310 : 105829 : key.userid = GetUserId();
1311 : 105829 : key.dbid = MyDatabaseId;
1312 : 105829 : key.queryid = queryId;
1313 : 105829 : key.toplevel = (nesting_level == 0);
1314 : :
1315 : : /* Lookup the hash table entry with shared lock. */
1316 : 105829 : LWLockAcquire(&pgss->lock.lock, LW_SHARED);
1317 : :
1318 : 105829 : entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
1319 : :
1320 : : /* Create new entry, if not present */
1321 [ + + ]: 105829 : if (!entry)
1322 : : {
1323 : : Size query_offset;
1324 : : int gc_count;
1325 : : bool stored;
1326 : : bool do_gc;
1327 : :
1328 : : /*
1329 : : * Create a new, normalized query string if caller asked. We don't
1330 : : * need to hold the lock while doing this work. (Note: in any case,
1331 : : * it's possible that someone else creates a duplicate hashtable entry
1332 : : * in the interval where we don't hold the lock below. That case is
1333 : : * handled by entry_alloc.)
1334 : : */
1335 [ + + ]: 31525 : if (jstate)
1336 : : {
1337 : 11707 : LWLockRelease(&pgss->lock.lock);
1338 : 11707 : norm_query = generate_normalized_query(jstate, query,
1339 : : query_location,
1340 : : &query_len);
1341 : 11707 : LWLockAcquire(&pgss->lock.lock, LW_SHARED);
1342 : : }
1343 : :
1344 : : /* Append new query text to file with only shared lock held */
1345 [ + + ]: 31525 : stored = qtext_store(norm_query ? norm_query : query, query_len,
1346 : : &query_offset, &gc_count);
1347 : :
1348 : : /*
1349 : : * Determine whether we need to garbage collect external query texts
1350 : : * while the shared lock is still held. This micro-optimization
1351 : : * avoids taking the time to decide this while holding exclusive lock.
1352 : : */
1353 : 31525 : do_gc = need_gc_qtexts();
1354 : :
1355 : : /* Need exclusive lock to make a new hashtable entry - promote */
1356 : 31525 : LWLockRelease(&pgss->lock.lock);
1357 : 31525 : LWLockAcquire(&pgss->lock.lock, LW_EXCLUSIVE);
1358 : :
1359 : : /*
1360 : : * A garbage collection may have occurred while we weren't holding the
1361 : : * lock. In the unlikely event that this happens, the query text we
1362 : : * stored above will have been garbage collected, so write it again.
1363 : : * This should be infrequent enough that doing it while holding
1364 : : * exclusive lock isn't a performance problem.
1365 : : */
1366 [ + - - + ]: 31525 : if (!stored || pgss->gc_count != gc_count)
1367 [ # # ]: 0 : stored = qtext_store(norm_query ? norm_query : query, query_len,
1368 : : &query_offset, NULL);
1369 : :
1370 : : /* If we failed to write to the text file, give up */
1371 [ - + ]: 31525 : if (!stored)
1372 : 0 : goto done;
1373 : :
1374 : : /* OK to create a new hashtable entry */
1375 : 31525 : entry = entry_alloc(&key, query_offset, query_len, encoding,
1376 : : jstate != NULL);
1377 : :
1378 : : /* If needed, perform garbage collection while exclusive lock held */
1379 [ - + ]: 31525 : if (do_gc)
1380 : 0 : gc_qtexts();
1381 : : }
1382 : :
1383 : : /* Increment the counts, except when jstate is not NULL */
1384 [ + + ]: 105829 : if (!jstate)
1385 : : {
1386 : : Assert(kind == PGSS_PLAN || kind == PGSS_EXEC);
1387 : :
1388 : : /*
1389 : : * Grab the spinlock while updating the counters (see comment about
1390 : : * locking rules at the head of the file)
1391 : : */
1392 : 66315 : SpinLockAcquire(&entry->mutex);
1393 : :
1394 : : /* "Unstick" entry if it was previously sticky */
1395 [ + + ]: 66315 : if (IS_STICKY(entry->counters))
1396 : 30686 : entry->counters.usage = USAGE_INIT;
1397 : :
1398 : 66315 : entry->counters.calls[kind] += 1;
1399 : 66315 : entry->counters.total_time[kind] += total_time;
1400 : :
1401 [ + + ]: 66315 : if (entry->counters.calls[kind] == 1)
1402 : : {
1403 : 30780 : entry->counters.min_time[kind] = total_time;
1404 : 30780 : entry->counters.max_time[kind] = total_time;
1405 : 30780 : entry->counters.mean_time[kind] = total_time;
1406 : : }
1407 : : else
1408 : : {
1409 : : /*
1410 : : * Welford's method for accurately computing variance. See
1411 : : * <http://www.johndcook.com/blog/standard_deviation/>
1412 : : */
1413 : 35535 : double old_mean = entry->counters.mean_time[kind];
1414 : :
1415 : 35535 : entry->counters.mean_time[kind] +=
1416 : 35535 : (total_time - old_mean) / entry->counters.calls[kind];
1417 : 35535 : entry->counters.sum_var_time[kind] +=
1418 : 35535 : (total_time - old_mean) * (total_time - entry->counters.mean_time[kind]);
1419 : :
1420 : : /*
1421 : : * Calculate min and max time. min = 0 and max = 0 means that the
1422 : : * min/max statistics were reset
1423 : : */
1424 [ + + ]: 35535 : if (entry->counters.min_time[kind] == 0
1425 [ + + ]: 6 : && entry->counters.max_time[kind] == 0)
1426 : : {
1427 : 3 : entry->counters.min_time[kind] = total_time;
1428 : 3 : entry->counters.max_time[kind] = total_time;
1429 : : }
1430 : : else
1431 : : {
1432 [ + + ]: 35532 : if (entry->counters.min_time[kind] > total_time)
1433 : 6731 : entry->counters.min_time[kind] = total_time;
1434 [ + + ]: 35532 : if (entry->counters.max_time[kind] < total_time)
1435 : 3665 : entry->counters.max_time[kind] = total_time;
1436 : : }
1437 : : }
1438 : 66315 : entry->counters.rows += rows;
1439 : 66315 : entry->counters.shared_blks_hit += bufusage->shared_blks_hit;
1440 : 66315 : entry->counters.shared_blks_read += bufusage->shared_blks_read;
1441 : 66315 : entry->counters.shared_blks_dirtied += bufusage->shared_blks_dirtied;
1442 : 66315 : entry->counters.shared_blks_written += bufusage->shared_blks_written;
1443 : 66315 : entry->counters.local_blks_hit += bufusage->local_blks_hit;
1444 : 66315 : entry->counters.local_blks_read += bufusage->local_blks_read;
1445 : 66315 : entry->counters.local_blks_dirtied += bufusage->local_blks_dirtied;
1446 : 66315 : entry->counters.local_blks_written += bufusage->local_blks_written;
1447 : 66315 : entry->counters.temp_blks_read += bufusage->temp_blks_read;
1448 : 66315 : entry->counters.temp_blks_written += bufusage->temp_blks_written;
1449 : 66315 : entry->counters.shared_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_read_time);
1450 : 66315 : entry->counters.shared_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->shared_blk_write_time);
1451 : 66315 : entry->counters.local_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->local_blk_read_time);
1452 : 66315 : entry->counters.local_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->local_blk_write_time);
1453 : 66315 : entry->counters.temp_blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_read_time);
1454 : 66315 : entry->counters.temp_blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->temp_blk_write_time);
1455 : 66315 : entry->counters.usage += USAGE_EXEC(total_time);
1456 : 66315 : entry->counters.wal_records += walusage->wal_records;
1457 : 66315 : entry->counters.wal_fpi += walusage->wal_fpi;
1458 : 66315 : entry->counters.wal_bytes += walusage->wal_bytes;
1459 : 66315 : entry->counters.wal_buffers_full += walusage->wal_buffers_full;
1460 [ - + ]: 66315 : if (jitusage)
1461 : : {
1462 : 0 : entry->counters.jit_functions += jitusage->created_functions;
1463 : 0 : entry->counters.jit_generation_time += INSTR_TIME_GET_MILLISEC(jitusage->generation_counter);
1464 : :
1465 [ # # ]: 0 : if (INSTR_TIME_GET_MILLISEC(jitusage->deform_counter))
1466 : 0 : entry->counters.jit_deform_count++;
1467 : 0 : entry->counters.jit_deform_time += INSTR_TIME_GET_MILLISEC(jitusage->deform_counter);
1468 : :
1469 [ # # ]: 0 : if (INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter))
1470 : 0 : entry->counters.jit_inlining_count++;
1471 : 0 : entry->counters.jit_inlining_time += INSTR_TIME_GET_MILLISEC(jitusage->inlining_counter);
1472 : :
1473 [ # # ]: 0 : if (INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter))
1474 : 0 : entry->counters.jit_optimization_count++;
1475 : 0 : entry->counters.jit_optimization_time += INSTR_TIME_GET_MILLISEC(jitusage->optimization_counter);
1476 : :
1477 [ # # ]: 0 : if (INSTR_TIME_GET_MILLISEC(jitusage->emission_counter))
1478 : 0 : entry->counters.jit_emission_count++;
1479 : 0 : entry->counters.jit_emission_time += INSTR_TIME_GET_MILLISEC(jitusage->emission_counter);
1480 : : }
1481 : :
1482 : : /* parallel worker counters */
1483 : 66315 : entry->counters.parallel_workers_to_launch += parallel_workers_to_launch;
1484 : 66315 : entry->counters.parallel_workers_launched += parallel_workers_launched;
1485 : :
1486 : : /* plan cache counters */
1487 [ + + ]: 66315 : if (planOrigin == PLAN_STMT_CACHE_GENERIC)
1488 : 3157 : entry->counters.generic_plan_calls++;
1489 [ + + ]: 63158 : else if (planOrigin == PLAN_STMT_CACHE_CUSTOM)
1490 : 395 : entry->counters.custom_plan_calls++;
1491 : :
1492 : 66315 : SpinLockRelease(&entry->mutex);
1493 : : }
1494 : :
1495 : 39514 : done:
1496 : 105829 : LWLockRelease(&pgss->lock.lock);
1497 : :
1498 : : /* We postpone this clean-up until we're out of the lock */
1499 [ + + ]: 105829 : if (norm_query)
1500 : 11707 : pfree(norm_query);
1501 : : }
1502 : :
1503 : : /*
1504 : : * Reset statement statistics corresponding to userid, dbid, and queryid.
1505 : : */
1506 : : Datum
1507 : 1 : pg_stat_statements_reset_1_7(PG_FUNCTION_ARGS)
1508 : : {
1509 : : Oid userid;
1510 : : Oid dbid;
1511 : : int64 queryid;
1512 : :
1513 : 1 : userid = PG_GETARG_OID(0);
1514 : 1 : dbid = PG_GETARG_OID(1);
1515 : 1 : queryid = PG_GETARG_INT64(2);
1516 : :
1517 : 1 : entry_reset(userid, dbid, queryid, false);
1518 : :
1519 : 1 : PG_RETURN_VOID();
1520 : : }
1521 : :
1522 : : Datum
1523 : 120 : pg_stat_statements_reset_1_11(PG_FUNCTION_ARGS)
1524 : : {
1525 : : Oid userid;
1526 : : Oid dbid;
1527 : : int64 queryid;
1528 : : bool minmax_only;
1529 : :
1530 : 120 : userid = PG_GETARG_OID(0);
1531 : 120 : dbid = PG_GETARG_OID(1);
1532 : 120 : queryid = PG_GETARG_INT64(2);
1533 : 120 : minmax_only = PG_GETARG_BOOL(3);
1534 : :
1535 : 120 : PG_RETURN_TIMESTAMPTZ(entry_reset(userid, dbid, queryid, minmax_only));
1536 : : }
1537 : :
1538 : : /*
1539 : : * Reset statement statistics.
1540 : : */
1541 : : Datum
1542 : 1 : pg_stat_statements_reset(PG_FUNCTION_ARGS)
1543 : : {
1544 : 1 : entry_reset(0, 0, 0, false);
1545 : :
1546 : 1 : PG_RETURN_VOID();
1547 : : }
1548 : :
1549 : : /* Number of output arguments (columns) for various API versions */
1550 : : #define PG_STAT_STATEMENTS_COLS_V1_0 14
1551 : : #define PG_STAT_STATEMENTS_COLS_V1_1 18
1552 : : #define PG_STAT_STATEMENTS_COLS_V1_2 19
1553 : : #define PG_STAT_STATEMENTS_COLS_V1_3 23
1554 : : #define PG_STAT_STATEMENTS_COLS_V1_8 32
1555 : : #define PG_STAT_STATEMENTS_COLS_V1_9 33
1556 : : #define PG_STAT_STATEMENTS_COLS_V1_10 43
1557 : : #define PG_STAT_STATEMENTS_COLS_V1_11 49
1558 : : #define PG_STAT_STATEMENTS_COLS_V1_12 52
1559 : : #define PG_STAT_STATEMENTS_COLS_V1_13 54
1560 : : #define PG_STAT_STATEMENTS_COLS 54 /* maximum of above */
1561 : :
1562 : : /*
1563 : : * Retrieve statement statistics.
1564 : : *
1565 : : * The SQL API of this function has changed multiple times, and will likely
1566 : : * do so again in future. To support the case where a newer version of this
1567 : : * loadable module is being used with an old SQL declaration of the function,
1568 : : * we continue to support the older API versions. For 1.2 and later, the
1569 : : * expected API version is identified by embedding it in the C name of the
1570 : : * function. Unfortunately we weren't bright enough to do that for 1.1.
1571 : : */
1572 : : Datum
1573 : 130 : pg_stat_statements_1_13(PG_FUNCTION_ARGS)
1574 : : {
1575 : 130 : bool showtext = PG_GETARG_BOOL(0);
1576 : :
1577 : 130 : pg_stat_statements_internal(fcinfo, PGSS_V1_13, showtext);
1578 : :
1579 : 130 : return (Datum) 0;
1580 : : }
1581 : :
1582 : : Datum
1583 : 1 : pg_stat_statements_1_12(PG_FUNCTION_ARGS)
1584 : : {
1585 : 1 : bool showtext = PG_GETARG_BOOL(0);
1586 : :
1587 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_12, showtext);
1588 : :
1589 : 1 : return (Datum) 0;
1590 : : }
1591 : :
1592 : : Datum
1593 : 1 : pg_stat_statements_1_11(PG_FUNCTION_ARGS)
1594 : : {
1595 : 1 : bool showtext = PG_GETARG_BOOL(0);
1596 : :
1597 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_11, showtext);
1598 : :
1599 : 1 : return (Datum) 0;
1600 : : }
1601 : :
1602 : : Datum
1603 : 1 : pg_stat_statements_1_10(PG_FUNCTION_ARGS)
1604 : : {
1605 : 1 : bool showtext = PG_GETARG_BOOL(0);
1606 : :
1607 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_10, showtext);
1608 : :
1609 : 1 : return (Datum) 0;
1610 : : }
1611 : :
1612 : : Datum
1613 : 1 : pg_stat_statements_1_9(PG_FUNCTION_ARGS)
1614 : : {
1615 : 1 : bool showtext = PG_GETARG_BOOL(0);
1616 : :
1617 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_9, showtext);
1618 : :
1619 : 1 : return (Datum) 0;
1620 : : }
1621 : :
1622 : : Datum
1623 : 1 : pg_stat_statements_1_8(PG_FUNCTION_ARGS)
1624 : : {
1625 : 1 : bool showtext = PG_GETARG_BOOL(0);
1626 : :
1627 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_8, showtext);
1628 : :
1629 : 1 : return (Datum) 0;
1630 : : }
1631 : :
1632 : : Datum
1633 : 1 : pg_stat_statements_1_3(PG_FUNCTION_ARGS)
1634 : : {
1635 : 1 : bool showtext = PG_GETARG_BOOL(0);
1636 : :
1637 : 1 : pg_stat_statements_internal(fcinfo, PGSS_V1_3, showtext);
1638 : :
1639 : 1 : return (Datum) 0;
1640 : : }
1641 : :
1642 : : Datum
1643 : 0 : pg_stat_statements_1_2(PG_FUNCTION_ARGS)
1644 : : {
1645 : 0 : bool showtext = PG_GETARG_BOOL(0);
1646 : :
1647 : 0 : pg_stat_statements_internal(fcinfo, PGSS_V1_2, showtext);
1648 : :
1649 : 0 : return (Datum) 0;
1650 : : }
1651 : :
1652 : : /*
1653 : : * Legacy entry point for pg_stat_statements() API versions 1.0 and 1.1.
1654 : : * This can be removed someday, perhaps.
1655 : : */
1656 : : Datum
1657 : 0 : pg_stat_statements(PG_FUNCTION_ARGS)
1658 : : {
1659 : : /* If it's really API 1.1, we'll figure that out below */
1660 : 0 : pg_stat_statements_internal(fcinfo, PGSS_V1_0, true);
1661 : :
1662 : 0 : return (Datum) 0;
1663 : : }
1664 : :
1665 : : /* Common code for all versions of pg_stat_statements() */
1666 : : static void
1667 : 136 : pg_stat_statements_internal(FunctionCallInfo fcinfo,
1668 : : pgssVersion api_version,
1669 : : bool showtext)
1670 : : {
1671 : 136 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1672 : 136 : Oid userid = GetUserId();
1673 : 136 : bool is_allowed_role = false;
1674 : 136 : char *qbuffer = NULL;
1675 : 136 : Size qbuffer_size = 0;
1676 : 136 : Size extent = 0;
1677 : 136 : int gc_count = 0;
1678 : : HASH_SEQ_STATUS hash_seq;
1679 : : pgssEntry *entry;
1680 : :
1681 : : /*
1682 : : * Superusers or roles with the privileges of pg_read_all_stats members
1683 : : * are allowed
1684 : : */
1685 : 136 : is_allowed_role = has_privs_of_role(userid, ROLE_PG_READ_ALL_STATS);
1686 : :
1687 : : /* hash table must exist already */
1688 [ + - - + ]: 136 : if (!pgss || !pgss_hash)
1689 [ # # ]: 0 : ereport(ERROR,
1690 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1691 : : errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
1692 : :
1693 : 136 : InitMaterializedSRF(fcinfo, 0);
1694 : :
1695 : : /*
1696 : : * Check we have the expected number of output arguments. Aside from
1697 : : * being a good safety check, we need a kluge here to detect API version
1698 : : * 1.1, which was wedged into the code in an ill-considered way.
1699 : : */
1700 [ - - - + : 136 : switch (rsinfo->setDesc->natts)
+ + + + +
+ - ]
1701 : : {
1702 : 0 : case PG_STAT_STATEMENTS_COLS_V1_0:
1703 [ # # ]: 0 : if (api_version != PGSS_V1_0)
1704 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1705 : 0 : break;
1706 : 0 : case PG_STAT_STATEMENTS_COLS_V1_1:
1707 : : /* pg_stat_statements() should have told us 1.0 */
1708 [ # # ]: 0 : if (api_version != PGSS_V1_0)
1709 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1710 : 0 : api_version = PGSS_V1_1;
1711 : 0 : break;
1712 : 0 : case PG_STAT_STATEMENTS_COLS_V1_2:
1713 [ # # ]: 0 : if (api_version != PGSS_V1_2)
1714 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1715 : 0 : break;
1716 : 1 : case PG_STAT_STATEMENTS_COLS_V1_3:
1717 [ - + ]: 1 : if (api_version != PGSS_V1_3)
1718 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1719 : 1 : break;
1720 : 1 : case PG_STAT_STATEMENTS_COLS_V1_8:
1721 [ - + ]: 1 : if (api_version != PGSS_V1_8)
1722 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1723 : 1 : break;
1724 : 1 : case PG_STAT_STATEMENTS_COLS_V1_9:
1725 [ - + ]: 1 : if (api_version != PGSS_V1_9)
1726 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1727 : 1 : break;
1728 : 1 : case PG_STAT_STATEMENTS_COLS_V1_10:
1729 [ - + ]: 1 : if (api_version != PGSS_V1_10)
1730 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1731 : 1 : break;
1732 : 1 : case PG_STAT_STATEMENTS_COLS_V1_11:
1733 [ - + ]: 1 : if (api_version != PGSS_V1_11)
1734 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1735 : 1 : break;
1736 : 1 : case PG_STAT_STATEMENTS_COLS_V1_12:
1737 [ - + ]: 1 : if (api_version != PGSS_V1_12)
1738 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1739 : 1 : break;
1740 : 130 : case PG_STAT_STATEMENTS_COLS_V1_13:
1741 [ - + ]: 130 : if (api_version != PGSS_V1_13)
1742 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1743 : 130 : break;
1744 : 0 : default:
1745 [ # # ]: 0 : elog(ERROR, "incorrect number of output arguments");
1746 : : }
1747 : :
1748 : : /*
1749 : : * We'd like to load the query text file (if needed) while not holding any
1750 : : * lock on pgss->lock. In the worst case we'll have to do this again
1751 : : * after we have the lock, but it's unlikely enough to make this a win
1752 : : * despite occasional duplicated work. We need to reload if anybody
1753 : : * writes to the file (either a retail qtext_store(), or a garbage
1754 : : * collection) between this point and where we've gotten shared lock. If
1755 : : * a qtext_store is actually in progress when we look, we might as well
1756 : : * skip the speculative load entirely.
1757 : : */
1758 [ + - ]: 136 : if (showtext)
1759 : : {
1760 : : int n_writers;
1761 : :
1762 : : /* Take the mutex so we can examine variables */
1763 : 136 : SpinLockAcquire(&pgss->mutex);
1764 : 136 : extent = pgss->extent;
1765 : 136 : n_writers = pgss->n_writers;
1766 : 136 : gc_count = pgss->gc_count;
1767 : 136 : SpinLockRelease(&pgss->mutex);
1768 : :
1769 : : /* No point in loading file now if there are active writers */
1770 [ + - ]: 136 : if (n_writers == 0)
1771 : 136 : qbuffer = qtext_load_file(&qbuffer_size);
1772 : : }
1773 : :
1774 : : /*
1775 : : * Get shared lock, load or reload the query text file if we must, and
1776 : : * iterate over the hashtable entries.
1777 : : *
1778 : : * With a large hash table, we might be holding the lock rather longer
1779 : : * than one could wish. However, this only blocks creation of new hash
1780 : : * table entries, and the larger the hash table the less likely that is to
1781 : : * be needed. So we can hope this is okay. Perhaps someday we'll decide
1782 : : * we need to partition the hash table to limit the time spent holding any
1783 : : * one lock.
1784 : : */
1785 : 136 : LWLockAcquire(&pgss->lock.lock, LW_SHARED);
1786 : :
1787 [ + - ]: 136 : if (showtext)
1788 : : {
1789 : : /*
1790 : : * Here it is safe to examine extent and gc_count without taking the
1791 : : * mutex. Note that although other processes might change
1792 : : * pgss->extent just after we look at it, the strings they then write
1793 : : * into the file cannot yet be referenced in the hashtable, so we
1794 : : * don't care whether we see them or not.
1795 : : *
1796 : : * If qtext_load_file fails, we just press on; we'll return NULL for
1797 : : * every query text.
1798 : : */
1799 [ + - ]: 136 : if (qbuffer == NULL ||
1800 [ + - ]: 136 : pgss->extent != extent ||
1801 [ - + ]: 136 : pgss->gc_count != gc_count)
1802 : : {
1803 [ # # ]: 0 : if (qbuffer)
1804 : 0 : pfree(qbuffer);
1805 : 0 : qbuffer = qtext_load_file(&qbuffer_size);
1806 : : }
1807 : : }
1808 : :
1809 : 136 : hash_seq_init(&hash_seq, pgss_hash);
1810 [ + + ]: 29872 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
1811 : : {
1812 : : Datum values[PG_STAT_STATEMENTS_COLS];
1813 : : bool nulls[PG_STAT_STATEMENTS_COLS];
1814 : 29736 : int i = 0;
1815 : : Counters tmp;
1816 : : double stddev;
1817 : 29736 : int64 queryid = entry->key.queryid;
1818 : : TimestampTz stats_since;
1819 : : TimestampTz minmax_stats_since;
1820 : :
1821 : 29736 : memset(values, 0, sizeof(values));
1822 : 29736 : memset(nulls, 0, sizeof(nulls));
1823 : :
1824 : 29736 : values[i++] = ObjectIdGetDatum(entry->key.userid);
1825 : 29736 : values[i++] = ObjectIdGetDatum(entry->key.dbid);
1826 [ + + ]: 29736 : if (api_version >= PGSS_V1_9)
1827 : 29724 : values[i++] = BoolGetDatum(entry->key.toplevel);
1828 : :
1829 [ + + + + ]: 29736 : if (is_allowed_role || entry->key.userid == userid)
1830 : : {
1831 [ + - ]: 29732 : if (api_version >= PGSS_V1_2)
1832 : 29732 : values[i++] = Int64GetDatumFast(queryid);
1833 : :
1834 [ + - ]: 29732 : if (showtext)
1835 : : {
1836 : 29732 : char *qstr = qtext_fetch(entry->query_offset,
1837 : : entry->query_len,
1838 : : qbuffer,
1839 : : qbuffer_size);
1840 : :
1841 [ + - ]: 29732 : if (qstr)
1842 : : {
1843 : : char *enc;
1844 : :
1845 : 29732 : enc = pg_any_to_server(qstr,
1846 : : entry->query_len,
1847 : : entry->encoding);
1848 : :
1849 : 29732 : values[i++] = CStringGetTextDatum(enc);
1850 : :
1851 [ - + ]: 29732 : if (enc != qstr)
1852 : 0 : pfree(enc);
1853 : : }
1854 : : else
1855 : : {
1856 : : /* Just return a null if we fail to find the text */
1857 : 0 : nulls[i++] = true;
1858 : : }
1859 : : }
1860 : : else
1861 : : {
1862 : : /* Query text not requested */
1863 : 0 : nulls[i++] = true;
1864 : : }
1865 : : }
1866 : : else
1867 : : {
1868 : : /* Don't show queryid */
1869 [ + - ]: 4 : if (api_version >= PGSS_V1_2)
1870 : 4 : nulls[i++] = true;
1871 : :
1872 : : /*
1873 : : * Don't show query text, but hint as to the reason for not doing
1874 : : * so if it was requested
1875 : : */
1876 [ + - ]: 4 : if (showtext)
1877 : 4 : values[i++] = CStringGetTextDatum("<insufficient privilege>");
1878 : : else
1879 : 0 : nulls[i++] = true;
1880 : : }
1881 : :
1882 : : /* copy counters to a local variable to keep locking time short */
1883 : 29736 : SpinLockAcquire(&entry->mutex);
1884 : 29736 : tmp = entry->counters;
1885 : 29736 : SpinLockRelease(&entry->mutex);
1886 : :
1887 : : /*
1888 : : * The spinlock is not required when reading these two as they are
1889 : : * always updated when holding pgss->lock exclusively.
1890 : : */
1891 : 29736 : stats_since = entry->stats_since;
1892 : 29736 : minmax_stats_since = entry->minmax_stats_since;
1893 : :
1894 : : /* Skip entry if unexecuted (ie, it's a pending "sticky" entry) */
1895 [ + + ]: 29736 : if (IS_STICKY(tmp))
1896 : 46 : continue;
1897 : :
1898 : : /* Note that we rely on PGSS_PLAN being 0 and PGSS_EXEC being 1. */
1899 [ + + ]: 89070 : for (int kind = 0; kind < PGSS_NUMKIND; kind++)
1900 : : {
1901 [ + + + + ]: 59380 : if (kind == PGSS_EXEC || api_version >= PGSS_V1_8)
1902 : : {
1903 : 59376 : values[i++] = Int64GetDatumFast(tmp.calls[kind]);
1904 : 59376 : values[i++] = Float8GetDatumFast(tmp.total_time[kind]);
1905 : : }
1906 : :
1907 [ + + - + : 59380 : if ((kind == PGSS_EXEC && api_version >= PGSS_V1_3) ||
+ + ]
1908 : : api_version >= PGSS_V1_8)
1909 : : {
1910 : 59376 : values[i++] = Float8GetDatumFast(tmp.min_time[kind]);
1911 : 59376 : values[i++] = Float8GetDatumFast(tmp.max_time[kind]);
1912 : 59376 : values[i++] = Float8GetDatumFast(tmp.mean_time[kind]);
1913 : :
1914 : : /*
1915 : : * Note we are calculating the population variance here, not
1916 : : * the sample variance, as we have data for the whole
1917 : : * population, so Bessel's correction is not used, and we
1918 : : * don't divide by tmp.calls - 1.
1919 : : */
1920 [ + + ]: 59376 : if (tmp.calls[kind] > 1)
1921 : 5509 : stddev = sqrt(tmp.sum_var_time[kind] / tmp.calls[kind]);
1922 : : else
1923 : 53867 : stddev = 0.0;
1924 : 59376 : values[i++] = Float8GetDatumFast(stddev);
1925 : : }
1926 : : }
1927 : 29690 : values[i++] = Int64GetDatumFast(tmp.rows);
1928 : 29690 : values[i++] = Int64GetDatumFast(tmp.shared_blks_hit);
1929 : 29690 : values[i++] = Int64GetDatumFast(tmp.shared_blks_read);
1930 [ + - ]: 29690 : if (api_version >= PGSS_V1_1)
1931 : 29690 : values[i++] = Int64GetDatumFast(tmp.shared_blks_dirtied);
1932 : 29690 : values[i++] = Int64GetDatumFast(tmp.shared_blks_written);
1933 : 29690 : values[i++] = Int64GetDatumFast(tmp.local_blks_hit);
1934 : 29690 : values[i++] = Int64GetDatumFast(tmp.local_blks_read);
1935 [ + - ]: 29690 : if (api_version >= PGSS_V1_1)
1936 : 29690 : values[i++] = Int64GetDatumFast(tmp.local_blks_dirtied);
1937 : 29690 : values[i++] = Int64GetDatumFast(tmp.local_blks_written);
1938 : 29690 : values[i++] = Int64GetDatumFast(tmp.temp_blks_read);
1939 : 29690 : values[i++] = Int64GetDatumFast(tmp.temp_blks_written);
1940 [ + - ]: 29690 : if (api_version >= PGSS_V1_1)
1941 : : {
1942 : 29690 : values[i++] = Float8GetDatumFast(tmp.shared_blk_read_time);
1943 : 29690 : values[i++] = Float8GetDatumFast(tmp.shared_blk_write_time);
1944 : : }
1945 [ + + ]: 29690 : if (api_version >= PGSS_V1_11)
1946 : : {
1947 : 29662 : values[i++] = Float8GetDatumFast(tmp.local_blk_read_time);
1948 : 29662 : values[i++] = Float8GetDatumFast(tmp.local_blk_write_time);
1949 : : }
1950 [ + + ]: 29690 : if (api_version >= PGSS_V1_10)
1951 : : {
1952 : 29671 : values[i++] = Float8GetDatumFast(tmp.temp_blk_read_time);
1953 : 29671 : values[i++] = Float8GetDatumFast(tmp.temp_blk_write_time);
1954 : : }
1955 [ + + ]: 29690 : if (api_version >= PGSS_V1_8)
1956 : : {
1957 : : char buf[256];
1958 : : Datum wal_bytes;
1959 : :
1960 : 29686 : values[i++] = Int64GetDatumFast(tmp.wal_records);
1961 : 29686 : values[i++] = Int64GetDatumFast(tmp.wal_fpi);
1962 : :
1963 : 29686 : snprintf(buf, sizeof buf, UINT64_FORMAT, tmp.wal_bytes);
1964 : :
1965 : : /* Convert to numeric. */
1966 : 29686 : wal_bytes = DirectFunctionCall3(numeric_in,
1967 : : CStringGetDatum(buf),
1968 : : ObjectIdGetDatum(0),
1969 : : Int32GetDatum(-1));
1970 : 29686 : values[i++] = wal_bytes;
1971 : : }
1972 [ + + ]: 29690 : if (api_version >= PGSS_V1_12)
1973 : : {
1974 : 29652 : values[i++] = Int64GetDatumFast(tmp.wal_buffers_full);
1975 : : }
1976 [ + + ]: 29690 : if (api_version >= PGSS_V1_10)
1977 : : {
1978 : 29671 : values[i++] = Int64GetDatumFast(tmp.jit_functions);
1979 : 29671 : values[i++] = Float8GetDatumFast(tmp.jit_generation_time);
1980 : 29671 : values[i++] = Int64GetDatumFast(tmp.jit_inlining_count);
1981 : 29671 : values[i++] = Float8GetDatumFast(tmp.jit_inlining_time);
1982 : 29671 : values[i++] = Int64GetDatumFast(tmp.jit_optimization_count);
1983 : 29671 : values[i++] = Float8GetDatumFast(tmp.jit_optimization_time);
1984 : 29671 : values[i++] = Int64GetDatumFast(tmp.jit_emission_count);
1985 : 29671 : values[i++] = Float8GetDatumFast(tmp.jit_emission_time);
1986 : : }
1987 [ + + ]: 29690 : if (api_version >= PGSS_V1_11)
1988 : : {
1989 : 29662 : values[i++] = Int64GetDatumFast(tmp.jit_deform_count);
1990 : 29662 : values[i++] = Float8GetDatumFast(tmp.jit_deform_time);
1991 : : }
1992 [ + + ]: 29690 : if (api_version >= PGSS_V1_12)
1993 : : {
1994 : 29652 : values[i++] = Int64GetDatumFast(tmp.parallel_workers_to_launch);
1995 : 29652 : values[i++] = Int64GetDatumFast(tmp.parallel_workers_launched);
1996 : : }
1997 [ + + ]: 29690 : if (api_version >= PGSS_V1_13)
1998 : : {
1999 : 29647 : values[i++] = Int64GetDatumFast(tmp.generic_plan_calls);
2000 : 29647 : values[i++] = Int64GetDatumFast(tmp.custom_plan_calls);
2001 : : }
2002 [ + + ]: 29690 : if (api_version >= PGSS_V1_11)
2003 : : {
2004 : 29662 : values[i++] = TimestampTzGetDatum(stats_since);
2005 : 29662 : values[i++] = TimestampTzGetDatum(minmax_stats_since);
2006 : : }
2007 : :
2008 : : Assert(i == (api_version == PGSS_V1_0 ? PG_STAT_STATEMENTS_COLS_V1_0 :
2009 : : api_version == PGSS_V1_1 ? PG_STAT_STATEMENTS_COLS_V1_1 :
2010 : : api_version == PGSS_V1_2 ? PG_STAT_STATEMENTS_COLS_V1_2 :
2011 : : api_version == PGSS_V1_3 ? PG_STAT_STATEMENTS_COLS_V1_3 :
2012 : : api_version == PGSS_V1_8 ? PG_STAT_STATEMENTS_COLS_V1_8 :
2013 : : api_version == PGSS_V1_9 ? PG_STAT_STATEMENTS_COLS_V1_9 :
2014 : : api_version == PGSS_V1_10 ? PG_STAT_STATEMENTS_COLS_V1_10 :
2015 : : api_version == PGSS_V1_11 ? PG_STAT_STATEMENTS_COLS_V1_11 :
2016 : : api_version == PGSS_V1_12 ? PG_STAT_STATEMENTS_COLS_V1_12 :
2017 : : api_version == PGSS_V1_13 ? PG_STAT_STATEMENTS_COLS_V1_13 :
2018 : : -1 /* fail if you forget to update this assert */ ));
2019 : :
2020 : 29690 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2021 : : }
2022 : :
2023 : 136 : LWLockRelease(&pgss->lock.lock);
2024 : :
2025 [ + - ]: 136 : if (qbuffer)
2026 : 136 : pfree(qbuffer);
2027 : 136 : }
2028 : :
2029 : : /* Number of output arguments (columns) for pg_stat_statements_info */
2030 : : #define PG_STAT_STATEMENTS_INFO_COLS 2
2031 : :
2032 : : /*
2033 : : * Return statistics of pg_stat_statements.
2034 : : */
2035 : : Datum
2036 : 3 : pg_stat_statements_info(PG_FUNCTION_ARGS)
2037 : : {
2038 : : pgssGlobalStats stats;
2039 : : TupleDesc tupdesc;
2040 : 3 : Datum values[PG_STAT_STATEMENTS_INFO_COLS] = {0};
2041 : 3 : bool nulls[PG_STAT_STATEMENTS_INFO_COLS] = {0};
2042 : :
2043 [ + - - + ]: 3 : if (!pgss || !pgss_hash)
2044 [ # # ]: 0 : ereport(ERROR,
2045 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2046 : : errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
2047 : :
2048 : : /* Build a tuple descriptor for our result type */
2049 [ - + ]: 3 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2050 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
2051 : :
2052 : : /* Read global statistics for pg_stat_statements */
2053 : 3 : SpinLockAcquire(&pgss->mutex);
2054 : 3 : stats = pgss->stats;
2055 : 3 : SpinLockRelease(&pgss->mutex);
2056 : :
2057 : 3 : values[0] = Int64GetDatum(stats.dealloc);
2058 : 3 : values[1] = TimestampTzGetDatum(stats.stats_reset);
2059 : :
2060 : 3 : PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
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 : 60239 : 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 [ - + ]: 60239 : while (hash_get_num_entries(pgss_hash) >= (int64) pgss_max)
2089 : 0 : entry_dealloc();
2090 : :
2091 : : /* Find or create an entry with desired hash code */
2092 : 60239 : entry = (pgssEntry *) hash_search(pgss_hash, key, HASH_ENTER, &found);
2093 : :
2094 [ + - ]: 60239 : if (!found)
2095 : : {
2096 : : /* New entry, initialize it */
2097 : :
2098 : : /* reset the statistics */
2099 : 60239 : memset(&entry->counters, 0, sizeof(Counters));
2100 : : /* set the appropriate initial usage count */
2101 [ + + ]: 60239 : entry->counters.usage = sticky ? pgss->cur_median_usage : USAGE_INIT;
2102 : : /* re-initialize the mutex each time ... we assume no one using it */
2103 : 60239 : SpinLockInit(&entry->mutex);
2104 : : /* ... and don't forget the query text metadata */
2105 : : Assert(query_len >= 0);
2106 : 60239 : entry->query_offset = query_offset;
2107 : 60239 : entry->query_len = query_len;
2108 : 60239 : entry->encoding = encoding;
2109 : 60239 : entry->stats_since = GetCurrentTimestamp();
2110 : 60239 : entry->minmax_stats_since = entry->stats_since;
2111 : : }
2112 : :
2113 : 60239 : return entry;
2114 : : }
2115 : :
2116 : : /*
2117 : : * qsort comparator for sorting into increasing usage order
2118 : : */
2119 : : static int
2120 : 0 : entry_cmp(const void *lhs, const void *rhs)
2121 : : {
2122 : 0 : double l_usage = (*(pgssEntry *const *) lhs)->counters.usage;
2123 : 0 : double r_usage = (*(pgssEntry *const *) rhs)->counters.usage;
2124 : :
2125 [ # # ]: 0 : if (l_usage < r_usage)
2126 : 0 : return -1;
2127 [ # # ]: 0 : else if (l_usage > r_usage)
2128 : 0 : return +1;
2129 : : else
2130 : 0 : 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 : 0 : 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 : 0 : entries = palloc(hash_get_num_entries(pgss_hash) * sizeof(pgssEntry *));
2162 : :
2163 : 0 : i = 0;
2164 : 0 : tottextlen = 0;
2165 : 0 : nvalidtexts = 0;
2166 : :
2167 : 0 : hash_seq_init(&hash_seq, pgss_hash);
2168 [ # # ]: 0 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2169 : : {
2170 : 0 : entries[i++] = entry;
2171 : : /* "Sticky" entries get a different usage decay rate. */
2172 [ # # ]: 0 : if (IS_STICKY(entry->counters))
2173 : 0 : entry->counters.usage *= STICKY_DECREASE_FACTOR;
2174 : : else
2175 : 0 : entry->counters.usage *= USAGE_DECREASE_FACTOR;
2176 : : /* In the mean length computation, ignore dropped texts. */
2177 [ # # ]: 0 : if (entry->query_len >= 0)
2178 : : {
2179 : 0 : tottextlen += entry->query_len + 1;
2180 : 0 : nvalidtexts++;
2181 : : }
2182 : : }
2183 : :
2184 : : /* Sort into increasing order by usage */
2185 : 0 : qsort(entries, i, sizeof(pgssEntry *), entry_cmp);
2186 : :
2187 : : /* Record the (approximate) median usage */
2188 [ # # ]: 0 : if (i > 0)
2189 : 0 : pgss->cur_median_usage = entries[i / 2]->counters.usage;
2190 : : /* Record the mean query length */
2191 [ # # ]: 0 : if (nvalidtexts > 0)
2192 : 0 : pgss->mean_query_len = tottextlen / nvalidtexts;
2193 : : else
2194 : 0 : pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2195 : :
2196 : : /* Now zap an appropriate fraction of lowest-usage entries */
2197 [ # # ]: 0 : nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
2198 : 0 : nvictims = Min(nvictims, i);
2199 : :
2200 [ # # ]: 0 : for (i = 0; i < nvictims; i++)
2201 : : {
2202 : 0 : hash_search(pgss_hash, &entries[i]->key, HASH_REMOVE, NULL);
2203 : : }
2204 : :
2205 : 0 : pfree(entries);
2206 : :
2207 : : /* Increment the number of times entries are deallocated */
2208 : 0 : SpinLockAcquire(&pgss->mutex);
2209 : 0 : pgss->stats.dealloc += 1;
2210 : 0 : SpinLockRelease(&pgss->mutex);
2211 : 0 : }
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 : 31525 : 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 : 31525 : SpinLockAcquire(&pgss->mutex);
2241 : 31525 : off = pgss->extent;
2242 : 31525 : pgss->extent += query_len + 1;
2243 : 31525 : pgss->n_writers++;
2244 [ + - ]: 31525 : if (gc_count)
2245 : 31525 : *gc_count = pgss->gc_count;
2246 : 31525 : SpinLockRelease(&pgss->mutex);
2247 : :
2248 : 31525 : *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 [ - + ]: 31525 : if (unlikely(query_len >= MaxAllocHugeSize - off))
2256 : : {
2257 : 0 : errno = EFBIG; /* not quite right, but it'll do */
2258 : 0 : fd = -1;
2259 : 0 : goto error;
2260 : : }
2261 : :
2262 : : /* Now write the data into the successfully-reserved part of the file */
2263 : 31525 : fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDWR | O_CREAT | PG_BINARY);
2264 [ - + ]: 31525 : if (fd < 0)
2265 : 0 : goto error;
2266 : :
2267 [ - + ]: 31525 : if (pg_pwrite(fd, query, query_len, off) != query_len)
2268 : 0 : goto error;
2269 [ - + ]: 31525 : if (pg_pwrite(fd, "\0", 1, off + query_len) != 1)
2270 : 0 : goto error;
2271 : :
2272 : 31525 : CloseTransientFile(fd);
2273 : :
2274 : : /* Mark our write complete */
2275 : 31525 : SpinLockAcquire(&pgss->mutex);
2276 : 31525 : pgss->n_writers--;
2277 : 31525 : SpinLockRelease(&pgss->mutex);
2278 : :
2279 : 31525 : return true;
2280 : :
2281 : 0 : error:
2282 [ # # ]: 0 : ereport(LOG,
2283 : : (errcode_for_file_access(),
2284 : : errmsg("could not write file \"%s\": %m",
2285 : : PGSS_TEXT_FILE)));
2286 : :
2287 [ # # ]: 0 : if (fd >= 0)
2288 : 0 : CloseTransientFile(fd);
2289 : :
2290 : : /* Mark our write complete */
2291 : 0 : SpinLockAcquire(&pgss->mutex);
2292 : 0 : pgss->n_writers--;
2293 : 0 : SpinLockRelease(&pgss->mutex);
2294 : :
2295 : 0 : 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 : 143 : qtext_load_file(Size *buffer_size)
2311 : : {
2312 : : char *buf;
2313 : : int fd;
2314 : : struct stat stat;
2315 : : Size nread;
2316 : :
2317 : 143 : fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDONLY | PG_BINARY);
2318 [ - + ]: 143 : if (fd < 0)
2319 : : {
2320 [ # # ]: 0 : if (errno != ENOENT)
2321 [ # # ]: 0 : ereport(LOG,
2322 : : (errcode_for_file_access(),
2323 : : errmsg("could not read file \"%s\": %m",
2324 : : PGSS_TEXT_FILE)));
2325 : 0 : return NULL;
2326 : : }
2327 : :
2328 : : /* Get file length */
2329 [ - + ]: 143 : if (fstat(fd, &stat))
2330 : : {
2331 [ # # ]: 0 : ereport(LOG,
2332 : : (errcode_for_file_access(),
2333 : : errmsg("could not stat file \"%s\": %m",
2334 : : PGSS_TEXT_FILE)));
2335 : 0 : CloseTransientFile(fd);
2336 : 0 : return NULL;
2337 : : }
2338 : :
2339 : : /* Allocate buffer; beware that off_t might be wider than size_t */
2340 [ + - ]: 143 : if (stat.st_size <= MaxAllocHugeSize)
2341 : 143 : buf = (char *) palloc_extended(stat.st_size, MCXT_ALLOC_HUGE | MCXT_ALLOC_NO_OOM);
2342 : : else
2343 : 0 : buf = NULL;
2344 [ - + ]: 143 : if (buf == NULL)
2345 : : {
2346 [ # # ]: 0 : 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 : 0 : CloseTransientFile(fd);
2352 : 0 : 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 : 143 : nread = 0;
2361 [ + + ]: 285 : while (nread < stat.st_size)
2362 : : {
2363 : 142 : 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 : 142 : errno = 0;
2373 [ - + ]: 142 : if (read(fd, buf + nread, toread) != toread)
2374 : : {
2375 [ # # ]: 0 : if (errno)
2376 [ # # ]: 0 : ereport(LOG,
2377 : : (errcode_for_file_access(),
2378 : : errmsg("could not read file \"%s\": %m",
2379 : : PGSS_TEXT_FILE)));
2380 : 0 : pfree(buf);
2381 : 0 : CloseTransientFile(fd);
2382 : 0 : return NULL;
2383 : : }
2384 : 142 : nread += toread;
2385 : : }
2386 : :
2387 [ - + ]: 143 : if (CloseTransientFile(fd) != 0)
2388 [ # # ]: 0 : ereport(LOG,
2389 : : (errcode_for_file_access(),
2390 : : errmsg("could not close file \"%s\": %m", PGSS_TEXT_FILE)));
2391 : :
2392 : 143 : *buffer_size = nread;
2393 : 143 : 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 : 89047 : qtext_fetch(Size query_offset, int query_len,
2404 : : char *buffer, Size buffer_size)
2405 : : {
2406 : : /* File read failed? */
2407 [ - + ]: 89047 : if (buffer == NULL)
2408 : 0 : return NULL;
2409 : : /* Bogus offset/length? */
2410 [ + - ]: 89047 : if (query_len < 0 ||
2411 [ - + ]: 89047 : query_offset + query_len >= buffer_size)
2412 : 0 : return NULL;
2413 : : /* As a further sanity check, make sure there's a trailing null */
2414 [ - + ]: 89047 : if (buffer[query_offset + query_len] != '\0')
2415 : 0 : return NULL;
2416 : : /* Looks OK */
2417 : 89047 : 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 : 31525 : need_gc_qtexts(void)
2427 : : {
2428 : : Size extent;
2429 : :
2430 : : /* Read shared extent pointer */
2431 : 31525 : SpinLockAcquire(&pgss->mutex);
2432 : 31525 : extent = pgss->extent;
2433 : 31525 : 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 [ + - ]: 31525 : if ((uint64) extent < (uint64) 512 * pgss_max)
2443 : 31525 : 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 [ # # ]: 0 : if ((uint64) extent < (uint64) pgss->mean_query_len * pgss_max * 2)
2453 : 0 : return false;
2454 : :
2455 : 0 : 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 : 0 : gc_qtexts(void)
2476 : : {
2477 : : char *qbuffer;
2478 : : Size qbuffer_size;
2479 : 0 : 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 [ # # ]: 0 : if (!need_gc_qtexts())
2491 : 0 : 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 : 0 : qbuffer = qtext_load_file(&qbuffer_size);
2501 [ # # ]: 0 : if (qbuffer == NULL)
2502 : 0 : 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 : 0 : qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2511 [ # # ]: 0 : if (qfile == NULL)
2512 : : {
2513 [ # # ]: 0 : ereport(LOG,
2514 : : (errcode_for_file_access(),
2515 : : errmsg("could not write file \"%s\": %m",
2516 : : PGSS_TEXT_FILE)));
2517 : 0 : goto gc_fail;
2518 : : }
2519 : :
2520 : 0 : extent = 0;
2521 : 0 : nentries = 0;
2522 : :
2523 : 0 : hash_seq_init(&hash_seq, pgss_hash);
2524 [ # # ]: 0 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2525 : : {
2526 : 0 : int query_len = entry->query_len;
2527 : 0 : char *qry = qtext_fetch(entry->query_offset,
2528 : : query_len,
2529 : : qbuffer,
2530 : : qbuffer_size);
2531 : :
2532 [ # # ]: 0 : if (qry == NULL)
2533 : : {
2534 : : /* Trouble ... drop the text */
2535 : 0 : entry->query_offset = 0;
2536 : 0 : entry->query_len = -1;
2537 : : /* entry will not be counted in mean query length computation */
2538 : 0 : continue;
2539 : : }
2540 : :
2541 [ # # ]: 0 : if (fwrite(qry, 1, query_len + 1, qfile) != query_len + 1)
2542 : : {
2543 [ # # ]: 0 : ereport(LOG,
2544 : : (errcode_for_file_access(),
2545 : : errmsg("could not write file \"%s\": %m",
2546 : : PGSS_TEXT_FILE)));
2547 : 0 : hash_seq_term(&hash_seq);
2548 : 0 : goto gc_fail;
2549 : : }
2550 : :
2551 : 0 : entry->query_offset = extent;
2552 : 0 : extent += query_len + 1;
2553 : 0 : 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 [ # # ]: 0 : if (ftruncate(fileno(qfile), extent) != 0)
2561 [ # # ]: 0 : ereport(LOG,
2562 : : (errcode_for_file_access(),
2563 : : errmsg("could not truncate file \"%s\": %m",
2564 : : PGSS_TEXT_FILE)));
2565 : :
2566 [ # # ]: 0 : if (FreeFile(qfile))
2567 : : {
2568 [ # # ]: 0 : ereport(LOG,
2569 : : (errcode_for_file_access(),
2570 : : errmsg("could not write file \"%s\": %m",
2571 : : PGSS_TEXT_FILE)));
2572 : 0 : qfile = NULL;
2573 : 0 : goto gc_fail;
2574 : : }
2575 : :
2576 [ # # ]: 0 : 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 : 0 : 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 [ # # ]: 0 : if (nentries > 0)
2587 : 0 : pgss->mean_query_len = extent / nentries;
2588 : : else
2589 : 0 : pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2590 : :
2591 : 0 : 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 : 0 : record_gc_qtexts();
2601 : :
2602 : 0 : return;
2603 : :
2604 : 0 : gc_fail:
2605 : : /* clean up resources */
2606 [ # # ]: 0 : if (qfile)
2607 : 0 : FreeFile(qfile);
2608 [ # # ]: 0 : if (qbuffer)
2609 : 0 : 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 : 0 : hash_seq_init(&hash_seq, pgss_hash);
2616 [ # # ]: 0 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2617 : : {
2618 : 0 : entry->query_offset = 0;
2619 : 0 : entry->query_len = -1;
2620 : : }
2621 : :
2622 : : /*
2623 : : * Destroy the query text file and create a new, empty one
2624 : : */
2625 : 0 : (void) unlink(PGSS_TEXT_FILE);
2626 : 0 : qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2627 [ # # ]: 0 : if (qfile == NULL)
2628 [ # # ]: 0 : ereport(LOG,
2629 : : (errcode_for_file_access(),
2630 : : errmsg("could not recreate file \"%s\": %m",
2631 : : PGSS_TEXT_FILE)));
2632 : : else
2633 : 0 : FreeFile(qfile);
2634 : :
2635 : : /* Reset the shared extent pointer */
2636 : 0 : pgss->extent = 0;
2637 : :
2638 : : /* Reset mean_query_len to match the new state */
2639 : 0 : 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 : 0 : 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 : 122 : 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 : : int64 num_entries;
2684 : 122 : int64 num_remove = 0;
2685 : : pgssHashKey key;
2686 : : TimestampTz stats_reset;
2687 : :
2688 [ + - - + ]: 122 : if (!pgss || !pgss_hash)
2689 [ # # ]: 0 : ereport(ERROR,
2690 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2691 : : errmsg("pg_stat_statements must be loaded via \"shared_preload_libraries\"")));
2692 : :
2693 : 122 : LWLockAcquire(&pgss->lock.lock, LW_EXCLUSIVE);
2694 : 122 : num_entries = hash_get_num_entries(pgss_hash);
2695 : :
2696 : 122 : stats_reset = GetCurrentTimestamp();
2697 : :
2698 [ + + + + : 122 : if (userid != 0 && dbid != 0 && queryid != INT64CONST(0))
+ - ]
2699 : : {
2700 : : /* If all the parameters are available, use the fast path. */
2701 : 1 : memset(&key, 0, sizeof(pgssHashKey));
2702 : 1 : key.userid = userid;
2703 : 1 : key.dbid = dbid;
2704 : 1 : key.queryid = queryid;
2705 : :
2706 : : /*
2707 : : * Reset the entry if it exists, starting with the non-top-level
2708 : : * entry.
2709 : : */
2710 : 1 : key.toplevel = false;
2711 : 1 : entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
2712 : :
2713 [ - + - - : 1 : SINGLE_ENTRY_RESET(entry);
- - ]
2714 : :
2715 : : /* Also reset the top-level entry if it exists. */
2716 : 1 : key.toplevel = true;
2717 : 1 : entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
2718 : :
2719 [ + - - + : 1 : SINGLE_ENTRY_RESET(entry);
- - ]
2720 : : }
2721 [ + + + - : 121 : else if (userid != 0 || dbid != 0 || queryid != INT64CONST(0))
+ + ]
2722 : : {
2723 : : /* Reset entries corresponding to valid parameters. */
2724 : 4 : hash_seq_init(&hash_seq, pgss_hash);
2725 [ + + ]: 51 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2726 : : {
2727 [ + + + + : 47 : if ((!userid || entry->key.userid == userid) &&
- + ]
2728 [ - - + + ]: 36 : (!dbid || entry->key.dbid == dbid) &&
2729 [ + + ]: 34 : (!queryid || entry->key.queryid == queryid))
2730 : : {
2731 [ + - + + : 7 : SINGLE_ENTRY_RESET(entry);
+ + ]
2732 : : }
2733 : : }
2734 : : }
2735 : : else
2736 : : {
2737 : : /* Reset all entries. */
2738 : 117 : hash_seq_init(&hash_seq, pgss_hash);
2739 [ + + ]: 1158 : while ((entry = hash_seq_search(&hash_seq)) != NULL)
2740 : : {
2741 [ + - + + : 946 : SINGLE_ENTRY_RESET(entry);
+ + ]
2742 : : }
2743 : : }
2744 : :
2745 : : /* All entries are removed? */
2746 [ + + ]: 122 : if (num_entries != num_remove)
2747 : 6 : goto release_lock;
2748 : :
2749 : : /*
2750 : : * Reset global statistics for pg_stat_statements since all entries are
2751 : : * removed.
2752 : : */
2753 : 116 : SpinLockAcquire(&pgss->mutex);
2754 : 116 : pgss->stats.dealloc = 0;
2755 : 116 : pgss->stats.stats_reset = stats_reset;
2756 : 116 : 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 : 116 : qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2763 [ - + ]: 116 : if (qfile == NULL)
2764 : : {
2765 [ # # ]: 0 : ereport(LOG,
2766 : : (errcode_for_file_access(),
2767 : : errmsg("could not create file \"%s\": %m",
2768 : : PGSS_TEXT_FILE)));
2769 : 0 : goto done;
2770 : : }
2771 : :
2772 : : /* If ftruncate fails, log it, but it's not a fatal problem */
2773 [ - + ]: 116 : if (ftruncate(fileno(qfile), 0) != 0)
2774 [ # # ]: 0 : ereport(LOG,
2775 : : (errcode_for_file_access(),
2776 : : errmsg("could not truncate file \"%s\": %m",
2777 : : PGSS_TEXT_FILE)));
2778 : :
2779 : 116 : FreeFile(qfile);
2780 : :
2781 : 116 : done:
2782 : 116 : pgss->extent = 0;
2783 : : /* This counts as a query text garbage collection for our purposes */
2784 : 116 : record_gc_qtexts();
2785 : :
2786 : 122 : release_lock:
2787 : 122 : LWLockRelease(&pgss->lock.lock);
2788 : :
2789 : 122 : 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 : 11707 : generate_normalized_query(const JumbleState *jstate, const char *query,
2813 : : int query_loc, int *query_len_p)
2814 : : {
2815 : : StringInfoData norm_query;
2816 : 11707 : int query_len = *query_len_p;
2817 : : int len_to_wrt, /* Length (in bytes) to write */
2818 : 11707 : quer_loc = 0, /* Source query byte location */
2819 : 11707 : last_off = 0, /* Offset from start for previous tok */
2820 : 11707 : last_tok_len = 0; /* Length (in bytes) of that tok */
2821 : 11707 : int num_constants_replaced = 0;
2822 : 11707 : LocationLen *locs = NULL;
2823 : :
2824 : : /*
2825 : : * Our output buffer is an expansible StringInfo, but avoid enlarging it
2826 : : * in most cases by reserving extra space for each constant location.
2827 : : */
2828 : : Assert(jstate->clocations_count > 0);
2829 : 11707 : initStringInfoExt(&norm_query, query_len + jstate->clocations_count * 10);
2830 : :
2831 : : /*
2832 : : * Determine constants' lengths (core system only gives us locations), and
2833 : : * return a sorted copy of jstate's LocationLen data with lengths filled
2834 : : * in.
2835 : : */
2836 : 11707 : locs = ComputeConstantLengths(jstate, query, query_loc);
2837 : :
2838 [ + + ]: 47067 : for (int i = 0; i < jstate->clocations_count; i++)
2839 : : {
2840 : : int off, /* Offset from start for cur tok */
2841 : : tok_len; /* Length (in bytes) of that tok */
2842 : :
2843 : : /*
2844 : : * If we have an external param at this location, but no lists are
2845 : : * being squashed across the query, then we skip here; this will make
2846 : : * us print the characters found in the original query that represent
2847 : : * the parameter in the next iteration (or after the loop is done),
2848 : : * which is a bit odd but seems to work okay in most cases.
2849 : : */
2850 [ + + + + ]: 35360 : if (locs[i].extern_param && !jstate->has_squashed_lists)
2851 : 169 : continue;
2852 : :
2853 : 35191 : off = locs[i].location;
2854 : :
2855 : : /* Adjust recorded location if we're dealing with partial string */
2856 : 35191 : off -= query_loc;
2857 : :
2858 : 35191 : tok_len = locs[i].length;
2859 : :
2860 [ + + ]: 35191 : if (tok_len < 0)
2861 : 716 : continue; /* ignore any duplicates */
2862 : :
2863 : : /* Copy next chunk (what precedes the next constant) */
2864 : 34475 : len_to_wrt = off - last_off;
2865 : 34475 : len_to_wrt -= last_tok_len;
2866 : : Assert(len_to_wrt >= 0);
2867 : 34475 : appendBinaryStringInfo(&norm_query, query + quer_loc, len_to_wrt);
2868 : :
2869 : : /*
2870 : : * And insert a param symbol in place of the constant token; and, if
2871 : : * we have a squashable list, insert a placeholder comment starting
2872 : : * from the list's second value.
2873 : : */
2874 : 34475 : appendStringInfo(&norm_query, "$%d%s",
2875 : 34475 : num_constants_replaced + 1 + jstate->highest_extern_param_id,
2876 [ + + ]: 34475 : locs[i].squashed ? " /*, ... */" : "");
2877 : 34475 : num_constants_replaced++;
2878 : :
2879 : : /* move forward */
2880 : 34475 : quer_loc = off + tok_len;
2881 : 34475 : last_off = off;
2882 : 34475 : last_tok_len = tok_len;
2883 : : }
2884 : :
2885 : : /* Clean up, if needed */
2886 [ + - ]: 11707 : if (locs)
2887 : 11707 : pfree(locs);
2888 : :
2889 : : /*
2890 : : * We've copied up until the last ignorable constant. Copy over the
2891 : : * remaining bytes of the original query string.
2892 : : */
2893 : 11707 : len_to_wrt = query_len - quer_loc;
2894 : :
2895 : : Assert(len_to_wrt >= 0);
2896 : 11707 : appendBinaryStringInfo(&norm_query, query + quer_loc, len_to_wrt);
2897 : :
2898 : 11707 : *query_len_p = norm_query.len;
2899 : 11707 : return norm_query.data;
2900 : : }
|