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