1 /*-------------------------------------------------------------------------
4 * Track statement execution times across a whole database cluster.
6 * Execution costs are totalled for each distinct source query, and kept in
7 * a shared hashtable. (We track only as many distinct queries as will fit
8 * in the designated amount of shared memory.)
10 * As of Postgres 9.2, this module normalizes query entries. Normalization
11 * is a process whereby similar queries, typically differing only in their
12 * constants (though the exact rules are somewhat more subtle than that) are
13 * recognized as equivalent, and are tracked as a single entry. This is
14 * particularly useful for non-prepared queries.
16 * Normalization is implemented by fingerprinting queries, selectively
17 * serializing those fields of each query tree's nodes that are judged to be
18 * essential to the query. This is referred to as a query jumble. This is
19 * distinct from a regular serialization in that various extraneous
20 * information is ignored as irrelevant or not essential to the query, such
21 * as the collations of Vars and, most notably, the values of constants.
23 * This jumble is acquired at the end of parse analysis of each query, and
24 * a 32-bit hash of it is stored into the query's Query.queryId field.
25 * The server then copies this value around, making it available in plan
26 * tree(s) generated from the query. The executor can then use this value
27 * to blame query costs on the proper queryId.
29 * To facilitate presenting entries to users, we create "representative" query
30 * strings in which constants are replaced with '?' characters, to make it
31 * clearer what a normalized entry can represent. To save on shared memory,
32 * and to avoid having to truncate oversized query strings, we store these
33 * strings in a temporary external query-texts file. Offsets into this
34 * file are kept in shared memory.
36 * Note about locking issues: to create or delete an entry in the shared
37 * hashtable, one must hold pgss->lock exclusively. Modifying any field
38 * in an entry except the counters requires the same. To look up an entry,
39 * one must hold the lock shared. To read or update the counters within
40 * an entry, one must hold the lock shared or exclusive (so the entry doesn't
41 * disappear!) and also take the entry's mutex spinlock.
42 * The shared state variable pgss->extent (the next free spot in the external
43 * query-text file) should be accessed only while holding either the
44 * pgss->mutex spinlock, or exclusive lock on pgss->lock. We use the mutex to
45 * allow reserving file space while holding only shared lock on pgss->lock.
46 * Rewriting the entire external query-text file, eg for garbage collection,
47 * requires holding pgss->lock exclusively; this allows individual entries
48 * in the file to be read or written while holding only shared lock.
51 * Copyright (c) 2008-2014, PostgreSQL Global Development Group
54 * contrib/pg_stat_statements/pg_stat_statements.c
56 *-------------------------------------------------------------------------
66 #include "access/hash.h"
68 #include "executor/instrument.h"
70 #include "mb/pg_wchar.h"
71 #include "miscadmin.h"
72 #include "parser/analyze.h"
73 #include "parser/parsetree.h"
75 #include "parser/scanner.h"
78 #include "storage/fd.h"
79 #include "storage/ipc.h"
80 #include "storage/spin.h"
81 #include "tcop/utility.h"
82 #include "utils/builtins.h"
83 #include "utils/memutils.h"
88 /* Location of permanent stats file (valid when database is shut down) */
89 #define PGSS_DUMP_FILE PGSTAT_STAT_PERMANENT_DIRECTORY "/pg_stat_statements.stat"
92 * Location of external query text file. We don't keep it in the core
93 * system's stats_temp_directory. The core system can safely use that GUC
94 * setting, because the statistics collector temp file paths are set only once
95 * as part of changing the GUC, but pg_stat_statements has no way of avoiding
96 * race conditions. Besides, we only expect modest, infrequent I/O for query
97 * strings, so placing the file on a faster filesystem is not compelling.
99 #define PGSS_TEXT_FILE PG_STAT_TMP_DIR "/pgss_query_texts.stat"
101 /* Magic number identifying the stats file format */
102 static const uint32 PGSS_FILE_HEADER = 0x20140125;
104 /* PostgreSQL major version number, changes in which invalidate all entries */
105 static const uint32 PGSS_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
107 /* XXX: Should USAGE_EXEC reflect execution time and/or buffer usage? */
108 #define USAGE_EXEC(duration) (1.0)
109 #define USAGE_INIT (1.0) /* including initial planning */
110 #define ASSUMED_MEDIAN_INIT (10.0) /* initial assumed median usage */
111 #define ASSUMED_LENGTH_INIT 1024 /* initial assumed mean query length */
112 #define USAGE_DECREASE_FACTOR (0.99) /* decreased every entry_dealloc */
113 #define STICKY_DECREASE_FACTOR (0.50) /* factor for sticky entries */
114 #define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
116 #define JUMBLE_SIZE 1024 /* query serialization buffer size */
119 * Extension version number, for supporting older extension versions' objects
121 typedef enum pgssVersion
129 * Hashtable key that defines the identity of a hashtable entry. We separate
130 * queries by user and by database even if they are otherwise identical.
132 typedef struct pgssHashKey
134 Oid userid; /* user OID */
135 Oid dbid; /* database OID */
136 uint32 queryid; /* query identifier */
140 * The actual stats counters kept within pgssEntry.
142 typedef struct Counters
144 int64 calls; /* # of times executed */
145 double total_time; /* total execution time, in msec */
146 int64 rows; /* total # of retrieved or affected rows */
147 int64 shared_blks_hit; /* # of shared buffer hits */
148 int64 shared_blks_read; /* # of shared disk blocks read */
149 int64 shared_blks_dirtied; /* # of shared disk blocks dirtied */
150 int64 shared_blks_written; /* # of shared disk blocks written */
151 int64 local_blks_hit; /* # of local buffer hits */
152 int64 local_blks_read; /* # of local disk blocks read */
153 int64 local_blks_dirtied; /* # of local disk blocks dirtied */
154 int64 local_blks_written; /* # of local disk blocks written */
155 int64 temp_blks_read; /* # of temp blocks read */
156 int64 temp_blks_written; /* # of temp blocks written */
157 double blk_read_time; /* time spent reading, in msec */
158 double blk_write_time; /* time spent writing, in msec */
159 double usage; /* usage factor */
163 * Statistics per statement
165 * Note: in event of a failure in garbage collection of the query text file,
166 * we reset query_offset to zero and query_len to -1. This will be seen as
167 * an invalid state by qtext_fetch().
169 typedef struct pgssEntry
171 pgssHashKey key; /* hash key of entry - MUST BE FIRST */
172 Counters counters; /* the statistics for this query */
173 Size query_offset; /* query text offset in external file */
174 int query_len; /* # of valid bytes in query string */
175 int encoding; /* query text encoding */
176 slock_t mutex; /* protects the counters only */
180 * Global shared state
182 typedef struct pgssSharedState
184 LWLock *lock; /* protects hashtable search/modification */
185 double cur_median_usage; /* current median usage in hashtable */
186 Size mean_query_len; /* current mean entry text length */
187 slock_t mutex; /* protects following fields only: */
188 Size extent; /* current extent of query file */
189 int n_writers; /* number of active writers to query file */
190 int gc_count; /* query file garbage collection cycle count */
194 * Struct for tracking locations/lengths of constants during normalization
196 typedef struct pgssLocationLen
198 int location; /* start offset in query text */
199 int length; /* length in bytes, or -1 to ignore */
203 * Working state for computing a query jumble and producing a normalized
206 typedef struct pgssJumbleState
208 /* Jumble of current query tree */
209 unsigned char *jumble;
211 /* Number of bytes used in jumble[] */
214 /* Array of locations of constants that should be removed */
215 pgssLocationLen *clocations;
217 /* Allocated length of clocations array */
218 int clocations_buf_size;
220 /* Current number of valid entries in clocations array */
221 int clocations_count;
224 /*---- Local variables ----*/
226 /* Current nesting depth of ExecutorRun+ProcessUtility calls */
227 static int nested_level = 0;
229 /* Saved hook values in case of unload */
230 static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
231 static post_parse_analyze_hook_type prev_post_parse_analyze_hook = NULL;
232 static ExecutorStart_hook_type prev_ExecutorStart = NULL;
233 static ExecutorRun_hook_type prev_ExecutorRun = NULL;
234 static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
235 static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
236 static ProcessUtility_hook_type prev_ProcessUtility = NULL;
238 /* Links to shared memory state */
239 static pgssSharedState *pgss = NULL;
240 static HTAB *pgss_hash = NULL;
242 /*---- GUC variables ----*/
246 PGSS_TRACK_NONE, /* track no statements */
247 PGSS_TRACK_TOP, /* only top level statements */
248 PGSS_TRACK_ALL /* all statements, including nested ones */
251 static const struct config_enum_entry track_options[] =
253 {"none", PGSS_TRACK_NONE, false},
254 {"top", PGSS_TRACK_TOP, false},
255 {"all", PGSS_TRACK_ALL, false},
259 static int pgss_max; /* max # statements to track */
260 static int pgss_track; /* tracking level */
261 static bool pgss_track_utility; /* whether to track utility commands */
262 static bool pgss_save; /* whether to save stats across shutdown */
265 #define pgss_enabled() \
266 (pgss_track == PGSS_TRACK_ALL || \
267 (pgss_track == PGSS_TRACK_TOP && nested_level == 0))
269 #define record_gc_qtexts() \
271 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss; \
272 SpinLockAcquire(&s->mutex); \
274 SpinLockRelease(&s->mutex); \
277 /*---- Function declarations ----*/
282 PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
283 PG_FUNCTION_INFO_V1(pg_stat_statements_1_2);
284 PG_FUNCTION_INFO_V1(pg_stat_statements);
286 static void pgss_shmem_startup(void);
287 static void pgss_shmem_shutdown(int code, Datum arg);
288 static void pgss_post_parse_analyze(ParseState *pstate, Query *query);
289 static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags);
290 static void pgss_ExecutorRun(QueryDesc *queryDesc,
291 ScanDirection direction,
293 static void pgss_ExecutorFinish(QueryDesc *queryDesc);
294 static void pgss_ExecutorEnd(QueryDesc *queryDesc);
295 static void pgss_ProcessUtility(Node *parsetree, const char *queryString,
296 ProcessUtilityContext context, ParamListInfo params,
297 DestReceiver *dest, char *completionTag);
298 static uint32 pgss_hash_fn(const void *key, Size keysize);
299 static int pgss_match_fn(const void *key1, const void *key2, Size keysize);
300 static uint32 pgss_hash_string(const char *str);
301 static void pgss_store(const char *query, uint32 queryId,
302 double total_time, uint64 rows,
303 const BufferUsage *bufusage,
304 pgssJumbleState *jstate);
305 static void pg_stat_statements_internal(FunctionCallInfo fcinfo,
306 pgssVersion api_version,
308 static Size pgss_memsize(void);
309 static pgssEntry *entry_alloc(pgssHashKey *key, Size query_offset, int query_len,
310 int encoding, bool sticky);
311 static void entry_dealloc(void);
312 static bool qtext_store(const char *query, int query_len,
313 Size *query_offset, int *gc_count);
314 static char *qtext_load_file(Size *buffer_size);
315 static char *qtext_fetch(Size query_offset, int query_len,
316 char *buffer, Size buffer_size);
317 static bool need_gc_qtexts(void);
318 static void gc_qtexts(void);
319 static void entry_reset(void);
321 static void AppendJumble(pgssJumbleState *jstate,
322 const unsigned char *item, Size size);
323 static void JumbleQuery(pgssJumbleState *jstate, Query *query);
324 static void JumbleRangeTable(pgssJumbleState *jstate, List *rtable);
325 static void JumbleExpr(pgssJumbleState *jstate, Node *node);
326 static void RecordConstLocation(pgssJumbleState *jstate, int location);
328 static char *generate_normalized_query(pgssJumbleState *jstate, const char *query,
329 int *query_len_p, int encoding);
331 static void fill_in_constant_lengths(pgssJumbleState *jstate, const char *query);
332 static int comp_location(const void *a, const void *b);
337 * Module load callback
343 * In order to create our shared memory area, we have to be loaded via
344 * shared_preload_libraries. If not, fall out without hooking into any of
345 * the main system. (We don't throw error here because it seems useful to
346 * allow the pg_stat_statements functions to be created even when the
347 * module isn't active. The functions must protect themselves against
348 * being called then, however.)
350 if (!process_shared_preload_libraries_in_progress)
354 * Define (or redefine) custom GUC variables.
356 DefineCustomIntVariable("pg_stat_statements.max",
357 "Sets the maximum number of statements tracked by pg_stat_statements.",
369 DefineCustomEnumVariable("pg_stat_statements.track",
370 "Selects which statements are tracked by pg_stat_statements.",
381 DefineCustomBoolVariable("pg_stat_statements.track_utility",
382 "Selects whether utility commands are tracked by pg_stat_statements.",
392 DefineCustomBoolVariable("pg_stat_statements.save",
393 "Save pg_stat_statements statistics across server shutdowns.",
403 EmitWarningsOnPlaceholders("pg_stat_statements");
406 * Request additional shared resources. (These are no-ops if we're not in
407 * the postmaster process.) We'll allocate or attach to the shared
408 * resources in pgss_shmem_startup().
410 RequestAddinShmemSpace(pgss_memsize());
411 RequestAddinLWLocks(1);
416 prev_shmem_startup_hook = shmem_startup_hook;
417 shmem_startup_hook = pgss_shmem_startup;
418 prev_post_parse_analyze_hook = post_parse_analyze_hook;
419 post_parse_analyze_hook = pgss_post_parse_analyze;
420 prev_ExecutorStart = ExecutorStart_hook;
421 ExecutorStart_hook = pgss_ExecutorStart;
422 prev_ExecutorRun = ExecutorRun_hook;
423 ExecutorRun_hook = pgss_ExecutorRun;
424 prev_ExecutorFinish = ExecutorFinish_hook;
425 ExecutorFinish_hook = pgss_ExecutorFinish;
426 prev_ExecutorEnd = ExecutorEnd_hook;
427 ExecutorEnd_hook = pgss_ExecutorEnd;
428 prev_ProcessUtility = ProcessUtility_hook;
429 ProcessUtility_hook = pgss_ProcessUtility;
433 * Module unload callback
438 /* Uninstall hooks. */
439 shmem_startup_hook = prev_shmem_startup_hook;
440 post_parse_analyze_hook = prev_post_parse_analyze_hook;
441 ExecutorStart_hook = prev_ExecutorStart;
442 ExecutorRun_hook = prev_ExecutorRun;
443 ExecutorFinish_hook = prev_ExecutorFinish;
444 ExecutorEnd_hook = prev_ExecutorEnd;
445 ProcessUtility_hook = prev_ProcessUtility;
449 * shmem_startup hook: allocate or attach to shared memory,
450 * then load any pre-existing statistics from file.
451 * Also create and load the query-texts file, which is expected to exist
452 * (even if empty) while the module is enabled.
455 pgss_shmem_startup(void)
468 if (prev_shmem_startup_hook)
469 prev_shmem_startup_hook();
471 /* reset in case this is a restart within the postmaster */
476 * Create or attach to the shared memory state, including hash table
478 LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
480 pgss = ShmemInitStruct("pg_stat_statements",
481 sizeof(pgssSharedState),
486 /* First time through ... */
487 pgss->lock = LWLockAssign();
488 pgss->cur_median_usage = ASSUMED_MEDIAN_INIT;
489 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
490 SpinLockInit(&pgss->mutex);
496 memset(&info, 0, sizeof(info));
497 info.keysize = sizeof(pgssHashKey);
498 info.entrysize = sizeof(pgssEntry);
499 info.hash = pgss_hash_fn;
500 info.match = pgss_match_fn;
501 pgss_hash = ShmemInitHash("pg_stat_statements hash",
504 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
506 LWLockRelease(AddinShmemInitLock);
509 * If we're in the postmaster (or a standalone backend...), set up a shmem
510 * exit hook to dump the statistics to disk.
512 if (!IsUnderPostmaster)
513 on_shmem_exit(pgss_shmem_shutdown, (Datum) 0);
516 * Done if some other process already completed our initialization.
522 * Note: we don't bother with locks here, because there should be no other
523 * processes running when this code is reached.
526 /* Unlink query text file possibly left over from crash */
527 unlink(PGSS_TEXT_FILE);
529 /* Allocate new query text temp file */
530 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
535 * If we were told not to load old statistics, we're done. (Note we do
536 * not try to unlink any old dump file in this case. This seems a bit
537 * questionable but it's the historical behavior.)
546 * Attempt to load old statistics from the dump file.
548 file = AllocateFile(PGSS_DUMP_FILE, PG_BINARY_R);
553 /* No existing persisted stats file, so we're done */
559 buffer = (char *) palloc(buffer_size);
561 if (fread(&header, sizeof(uint32), 1, file) != 1 ||
562 fread(&pgver, sizeof(uint32), 1, file) != 1 ||
563 fread(&num, sizeof(int32), 1, file) != 1)
566 if (header != PGSS_FILE_HEADER ||
567 pgver != PGSS_PG_MAJOR_VERSION)
570 for (i = 0; i < num; i++)
576 if (fread(&temp, sizeof(pgssEntry), 1, file) != 1)
579 /* Encoding is the only field we can easily sanity-check */
580 if (!PG_VALID_BE_ENCODING(temp.encoding))
583 /* Resize buffer as needed */
584 if (temp.query_len >= buffer_size)
586 buffer_size = Max(buffer_size * 2, temp.query_len + 1);
587 buffer = repalloc(buffer, buffer_size);
590 if (fread(buffer, 1, temp.query_len + 1, file) != temp.query_len + 1)
593 /* Should have a trailing null, but let's make sure */
594 buffer[temp.query_len] = '\0';
596 /* Skip loading "sticky" entries */
597 if (temp.counters.calls == 0)
600 /* Store the query text */
601 query_offset = pgss->extent;
602 if (fwrite(buffer, 1, temp.query_len + 1, qfile) != temp.query_len + 1)
604 pgss->extent += temp.query_len + 1;
606 /* make the hashtable entry (discards old entries if too many) */
607 entry = entry_alloc(&temp.key, query_offset, temp.query_len,
611 /* copy in the actual stats */
612 entry->counters = temp.counters;
620 * Remove the persisted stats file so it's not included in
621 * backups/replication slaves, etc. A new file will be written on next
624 * Note: it's okay if the PGSS_TEXT_FILE is included in a basebackup,
625 * because we remove that file on startup; it acts inversely to
626 * PGSS_DUMP_FILE, in that it is only supposed to be around when the
627 * server is running, whereas PGSS_DUMP_FILE is only supposed to be around
628 * when the server is not running. Leaving the file creates no danger of
629 * a newly restored database having a spurious record of execution costs,
630 * which is what we're really concerned about here.
632 unlink(PGSS_DUMP_FILE);
638 (errcode_for_file_access(),
639 errmsg("could not read pg_stat_statement file \"%s\": %m",
644 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
645 errmsg("ignoring invalid data in pg_stat_statement file \"%s\"",
650 (errcode_for_file_access(),
651 errmsg("could not write pg_stat_statement file \"%s\": %m",
660 /* If possible, throw away the bogus file; ignore any error */
661 unlink(PGSS_DUMP_FILE);
664 * Don't unlink PGSS_TEXT_FILE here; it should always be around while the
665 * server is running with pg_stat_statements enabled
670 * shmem_shutdown hook: Dump statistics into file.
672 * Note: we don't bother with acquiring lock, because there should be no
673 * other processes running when this is called.
676 pgss_shmem_shutdown(int code, Datum arg)
679 char *qbuffer = NULL;
680 Size qbuffer_size = 0;
681 HASH_SEQ_STATUS hash_seq;
685 /* Don't try to dump during a crash. */
689 /* Safety check ... shouldn't get here unless shmem is set up. */
690 if (!pgss || !pgss_hash)
693 /* Don't dump if told not to. */
697 file = AllocateFile(PGSS_DUMP_FILE ".tmp", PG_BINARY_W);
701 if (fwrite(&PGSS_FILE_HEADER, sizeof(uint32), 1, file) != 1)
703 if (fwrite(&PGSS_PG_MAJOR_VERSION, sizeof(uint32), 1, file) != 1)
705 num_entries = hash_get_num_entries(pgss_hash);
706 if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
709 qbuffer = qtext_load_file(&qbuffer_size);
714 * When serializing to disk, we store query texts immediately after their
715 * entry data. Any orphaned query texts are thereby excluded.
717 hash_seq_init(&hash_seq, pgss_hash);
718 while ((entry = hash_seq_search(&hash_seq)) != NULL)
720 int len = entry->query_len;
721 char *qstr = qtext_fetch(entry->query_offset, len,
722 qbuffer, qbuffer_size);
725 continue; /* Ignore any entries with bogus texts */
727 if (fwrite(entry, sizeof(pgssEntry), 1, file) != 1 ||
728 fwrite(qstr, 1, len + 1, file) != len + 1)
730 /* note: we assume hash_seq_term won't change errno */
731 hash_seq_term(&hash_seq);
746 * Rename file into place, so we atomically replace any old one.
748 if (rename(PGSS_DUMP_FILE ".tmp", PGSS_DUMP_FILE) != 0)
750 (errcode_for_file_access(),
751 errmsg("could not rename pg_stat_statement file \"%s\": %m",
752 PGSS_DUMP_FILE ".tmp")));
754 /* Unlink query-texts file; it's not needed while shutdown */
755 unlink(PGSS_TEXT_FILE);
761 (errcode_for_file_access(),
762 errmsg("could not write pg_stat_statement file \"%s\": %m",
763 PGSS_DUMP_FILE ".tmp")));
768 unlink(PGSS_DUMP_FILE ".tmp");
769 unlink(PGSS_TEXT_FILE);
773 * Post-parse-analysis hook: mark query with a queryId
776 pgss_post_parse_analyze(ParseState *pstate, Query *query)
778 pgssJumbleState jstate;
780 if (prev_post_parse_analyze_hook)
781 prev_post_parse_analyze_hook(pstate, query);
783 /* Assert we didn't do this already */
784 Assert(query->queryId == 0);
786 /* Safety check... */
787 if (!pgss || !pgss_hash)
791 * Utility statements get queryId zero. We do this even in cases where
792 * the statement contains an optimizable statement for which a queryId
793 * could be derived (such as EXPLAIN or DECLARE CURSOR). For such cases,
794 * runtime control will first go through ProcessUtility and then the
795 * executor, and we don't want the executor hooks to do anything, since we
796 * are already measuring the statement's costs at the utility level.
798 if (query->utilityStmt)
804 /* Set up workspace for query jumbling */
805 jstate.jumble = (unsigned char *) palloc(JUMBLE_SIZE);
806 jstate.jumble_len = 0;
807 jstate.clocations_buf_size = 32;
808 jstate.clocations = (pgssLocationLen *)
809 palloc(jstate.clocations_buf_size * sizeof(pgssLocationLen));
810 jstate.clocations_count = 0;
812 /* Compute query ID and mark the Query node with it */
813 JumbleQuery(&jstate, query);
814 query->queryId = hash_any(jstate.jumble, jstate.jumble_len);
817 * If we are unlucky enough to get a hash of zero, use 1 instead, to
818 * prevent confusion with the utility-statement case.
820 if (query->queryId == 0)
824 * If we were able to identify any ignorable constants, we immediately
825 * create a hash table entry for the query, so that we can record the
826 * normalized form of the query string. If there were no such constants,
827 * the normalized string would be the same as the query text anyway, so
828 * there's no need for an early entry.
830 if (jstate.clocations_count > 0)
831 pgss_store(pstate->p_sourcetext,
840 * ExecutorStart hook: start up tracking if needed
843 pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
845 if (prev_ExecutorStart)
846 prev_ExecutorStart(queryDesc, eflags);
848 standard_ExecutorStart(queryDesc, eflags);
851 * If query has queryId zero, don't track it. This prevents double
852 * counting of optimizable statements that are directly contained in
853 * utility statements.
855 if (pgss_enabled() && queryDesc->plannedstmt->queryId != 0)
858 * Set up to track total elapsed time in ExecutorRun. Make sure the
859 * space is allocated in the per-query context so it will go away at
862 if (queryDesc->totaltime == NULL)
864 MemoryContext oldcxt;
866 oldcxt = MemoryContextSwitchTo(queryDesc->estate->es_query_cxt);
867 queryDesc->totaltime = InstrAlloc(1, INSTRUMENT_ALL);
868 MemoryContextSwitchTo(oldcxt);
874 * ExecutorRun hook: all we need do is track nesting depth
877 pgss_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count)
882 if (prev_ExecutorRun)
883 prev_ExecutorRun(queryDesc, direction, count);
885 standard_ExecutorRun(queryDesc, direction, count);
897 * ExecutorFinish hook: all we need do is track nesting depth
900 pgss_ExecutorFinish(QueryDesc *queryDesc)
905 if (prev_ExecutorFinish)
906 prev_ExecutorFinish(queryDesc);
908 standard_ExecutorFinish(queryDesc);
920 * ExecutorEnd hook: store results if needed
923 pgss_ExecutorEnd(QueryDesc *queryDesc)
925 uint32 queryId = queryDesc->plannedstmt->queryId;
927 if (queryId != 0 && queryDesc->totaltime && pgss_enabled())
930 * Make sure stats accumulation is done. (Note: it's okay if several
931 * levels of hook all do this.)
933 InstrEndLoop(queryDesc->totaltime);
935 pgss_store(queryDesc->sourceText,
937 queryDesc->totaltime->total * 1000.0, /* convert to msec */
938 queryDesc->estate->es_processed,
939 &queryDesc->totaltime->bufusage,
943 if (prev_ExecutorEnd)
944 prev_ExecutorEnd(queryDesc);
946 standard_ExecutorEnd(queryDesc);
950 * ProcessUtility hook
953 pgss_ProcessUtility(Node *parsetree, const char *queryString,
954 ProcessUtilityContext context, ParamListInfo params,
955 DestReceiver *dest, char *completionTag)
958 * If it's an EXECUTE statement, we don't track it and don't increment the
959 * nesting level. This allows the cycles to be charged to the underlying
960 * PREPARE instead (by the Executor hooks), which is much more useful.
962 * We also don't track execution of PREPARE. If we did, we would get one
963 * hash table entry for the PREPARE (with hash calculated from the query
964 * string), and then a different one with the same query string (but hash
965 * calculated from the query tree) would be used to accumulate costs of
966 * ensuing EXECUTEs. This would be confusing, and inconsistent with other
967 * cases where planning time is not included at all.
969 if (pgss_track_utility && pgss_enabled() &&
970 !IsA(parsetree, ExecuteStmt) &&
971 !IsA(parsetree, PrepareStmt))
976 BufferUsage bufusage_start,
980 bufusage_start = pgBufferUsage;
981 INSTR_TIME_SET_CURRENT(start);
986 if (prev_ProcessUtility)
987 prev_ProcessUtility(parsetree, queryString,
989 dest, completionTag);
991 standard_ProcessUtility(parsetree, queryString,
993 dest, completionTag);
1003 INSTR_TIME_SET_CURRENT(duration);
1004 INSTR_TIME_SUBTRACT(duration, start);
1006 /* parse command tag to retrieve the number of affected rows. */
1007 if (completionTag &&
1008 strncmp(completionTag, "COPY ", 5) == 0)
1010 #ifdef HAVE_STRTOULL
1011 rows = strtoull(completionTag + 5, NULL, 10);
1013 rows = strtoul(completionTag + 5, NULL, 10);
1019 /* calc differences of buffer counters. */
1020 bufusage.shared_blks_hit =
1021 pgBufferUsage.shared_blks_hit - bufusage_start.shared_blks_hit;
1022 bufusage.shared_blks_read =
1023 pgBufferUsage.shared_blks_read - bufusage_start.shared_blks_read;
1024 bufusage.shared_blks_dirtied =
1025 pgBufferUsage.shared_blks_dirtied - bufusage_start.shared_blks_dirtied;
1026 bufusage.shared_blks_written =
1027 pgBufferUsage.shared_blks_written - bufusage_start.shared_blks_written;
1028 bufusage.local_blks_hit =
1029 pgBufferUsage.local_blks_hit - bufusage_start.local_blks_hit;
1030 bufusage.local_blks_read =
1031 pgBufferUsage.local_blks_read - bufusage_start.local_blks_read;
1032 bufusage.local_blks_dirtied =
1033 pgBufferUsage.local_blks_dirtied - bufusage_start.local_blks_dirtied;
1034 bufusage.local_blks_written =
1035 pgBufferUsage.local_blks_written - bufusage_start.local_blks_written;
1036 bufusage.temp_blks_read =
1037 pgBufferUsage.temp_blks_read - bufusage_start.temp_blks_read;
1038 bufusage.temp_blks_written =
1039 pgBufferUsage.temp_blks_written - bufusage_start.temp_blks_written;
1040 bufusage.blk_read_time = pgBufferUsage.blk_read_time;
1041 INSTR_TIME_SUBTRACT(bufusage.blk_read_time, bufusage_start.blk_read_time);
1042 bufusage.blk_write_time = pgBufferUsage.blk_write_time;
1043 INSTR_TIME_SUBTRACT(bufusage.blk_write_time, bufusage_start.blk_write_time);
1045 /* For utility statements, we just hash the query string directly */
1046 queryId = pgss_hash_string(queryString);
1048 pgss_store(queryString,
1050 INSTR_TIME_GET_MILLISEC(duration),
1057 if (prev_ProcessUtility)
1058 prev_ProcessUtility(parsetree, queryString,
1060 dest, completionTag);
1062 standard_ProcessUtility(parsetree, queryString,
1064 dest, completionTag);
1069 * Calculate hash value for a key
1072 pgss_hash_fn(const void *key, Size keysize)
1074 const pgssHashKey *k = (const pgssHashKey *) key;
1076 return hash_uint32((uint32) k->userid) ^
1077 hash_uint32((uint32) k->dbid) ^
1078 hash_uint32((uint32) k->queryid);
1082 * Compare two keys - zero means match
1085 pgss_match_fn(const void *key1, const void *key2, Size keysize)
1087 const pgssHashKey *k1 = (const pgssHashKey *) key1;
1088 const pgssHashKey *k2 = (const pgssHashKey *) key2;
1090 if (k1->userid == k2->userid &&
1091 k1->dbid == k2->dbid &&
1092 k1->queryid == k2->queryid)
1099 * Given an arbitrarily long query string, produce a hash for the purposes of
1100 * identifying the query, without normalizing constants. Used when hashing
1101 * utility statements.
1104 pgss_hash_string(const char *str)
1106 return hash_any((const unsigned char *) str, strlen(str));
1110 * Store some statistics for a statement.
1112 * If jstate is not NULL then we're trying to create an entry for which
1113 * we have no statistics as yet; we just want to record the normalized
1114 * query string. total_time, rows, bufusage are ignored in this case.
1117 pgss_store(const char *query, uint32 queryId,
1118 double total_time, uint64 rows,
1119 const BufferUsage *bufusage,
1120 pgssJumbleState *jstate)
1124 char *norm_query = NULL;
1125 int encoding = GetDatabaseEncoding();
1128 Assert(query != NULL);
1130 /* Safety check... */
1131 if (!pgss || !pgss_hash)
1134 query_len = strlen(query);
1136 /* Set up key for hashtable search */
1137 key.userid = GetUserId();
1138 key.dbid = MyDatabaseId;
1139 key.queryid = queryId;
1141 /* Lookup the hash table entry with shared lock. */
1142 LWLockAcquire(pgss->lock, LW_SHARED);
1144 entry = (pgssEntry *) hash_search(pgss_hash, &key, HASH_FIND, NULL);
1146 /* Create new entry, if not present */
1155 * Create a new, normalized query string if caller asked. We don't
1156 * need to hold the lock while doing this work. (Note: in any case,
1157 * it's possible that someone else creates a duplicate hashtable entry
1158 * in the interval where we don't hold the lock below. That case is
1159 * handled by entry_alloc.)
1163 LWLockRelease(pgss->lock);
1164 norm_query = generate_normalized_query(jstate, query,
1167 LWLockAcquire(pgss->lock, LW_SHARED);
1170 /* Append new query text to file with only shared lock held */
1171 stored = qtext_store(norm_query ? norm_query : query, query_len,
1172 &query_offset, &gc_count);
1175 * Determine whether we need to garbage collect external query texts
1176 * while the shared lock is still held. This micro-optimization
1177 * avoids taking the time to decide this while holding exclusive lock.
1179 do_gc = need_gc_qtexts();
1181 /* Need exclusive lock to make a new hashtable entry - promote */
1182 LWLockRelease(pgss->lock);
1183 LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
1186 * A garbage collection may have occurred while we weren't holding the
1187 * lock. In the unlikely event that this happens, the query text we
1188 * stored above will have been garbage collected, so write it again.
1189 * This should be infrequent enough that doing it while holding
1190 * exclusive lock isn't a performance problem.
1192 if (!stored || pgss->gc_count != gc_count)
1193 stored = qtext_store(norm_query ? norm_query : query, query_len,
1194 &query_offset, NULL);
1196 /* If we failed to write to the text file, give up */
1200 /* OK to create a new hashtable entry */
1201 entry = entry_alloc(&key, query_offset, query_len, encoding,
1204 /* If needed, perform garbage collection while exclusive lock held */
1209 /* Increment the counts, except when jstate is not NULL */
1213 * Grab the spinlock while updating the counters (see comment about
1214 * locking rules at the head of the file)
1216 volatile pgssEntry *e = (volatile pgssEntry *) entry;
1218 SpinLockAcquire(&e->mutex);
1220 /* "Unstick" entry if it was previously sticky */
1221 if (e->counters.calls == 0)
1222 e->counters.usage = USAGE_INIT;
1224 e->counters.calls += 1;
1225 e->counters.total_time += total_time;
1226 e->counters.rows += rows;
1227 e->counters.shared_blks_hit += bufusage->shared_blks_hit;
1228 e->counters.shared_blks_read += bufusage->shared_blks_read;
1229 e->counters.shared_blks_dirtied += bufusage->shared_blks_dirtied;
1230 e->counters.shared_blks_written += bufusage->shared_blks_written;
1231 e->counters.local_blks_hit += bufusage->local_blks_hit;
1232 e->counters.local_blks_read += bufusage->local_blks_read;
1233 e->counters.local_blks_dirtied += bufusage->local_blks_dirtied;
1234 e->counters.local_blks_written += bufusage->local_blks_written;
1235 e->counters.temp_blks_read += bufusage->temp_blks_read;
1236 e->counters.temp_blks_written += bufusage->temp_blks_written;
1237 e->counters.blk_read_time += INSTR_TIME_GET_MILLISEC(bufusage->blk_read_time);
1238 e->counters.blk_write_time += INSTR_TIME_GET_MILLISEC(bufusage->blk_write_time);
1239 e->counters.usage += USAGE_EXEC(total_time);
1241 SpinLockRelease(&e->mutex);
1245 LWLockRelease(pgss->lock);
1247 /* We postpone this clean-up until we're out of the lock */
1253 * Reset all statement statistics.
1256 pg_stat_statements_reset(PG_FUNCTION_ARGS)
1258 if (!pgss || !pgss_hash)
1260 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1261 errmsg("pg_stat_statements must be loaded via shared_preload_libraries")));
1266 /* Number of output arguments (columns) for various API versions */
1267 #define PG_STAT_STATEMENTS_COLS_V1_0 14
1268 #define PG_STAT_STATEMENTS_COLS_V1_1 18
1269 #define PG_STAT_STATEMENTS_COLS_V1_2 19
1270 #define PG_STAT_STATEMENTS_COLS 19 /* maximum of above */
1273 * Retrieve statement statistics.
1275 * The SQL API of this function has changed multiple times, and will likely
1276 * do so again in future. To support the case where a newer version of this
1277 * loadable module is being used with an old SQL declaration of the function,
1278 * we continue to support the older API versions. For 1.2 and later, the
1279 * expected API version is identified by embedding it in the C name of the
1280 * function. Unfortunately we weren't bright enough to do that for 1.1.
1283 pg_stat_statements_1_2(PG_FUNCTION_ARGS)
1285 bool showtext = PG_GETARG_BOOL(0);
1287 pg_stat_statements_internal(fcinfo, PGSS_V1_2, showtext);
1293 * Legacy entry point for pg_stat_statements() API versions 1.0 and 1.1.
1294 * This can be removed someday, perhaps.
1297 pg_stat_statements(PG_FUNCTION_ARGS)
1299 /* If it's really API 1.1, we'll figure that out below */
1300 pg_stat_statements_internal(fcinfo, PGSS_V1_0, true);
1305 /* Common code for all versions of pg_stat_statements() */
1307 pg_stat_statements_internal(FunctionCallInfo fcinfo,
1308 pgssVersion api_version,
1311 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1313 Tuplestorestate *tupstore;
1314 MemoryContext per_query_ctx;
1315 MemoryContext oldcontext;
1316 Oid userid = GetUserId();
1317 bool is_superuser = superuser();
1318 char *qbuffer = NULL;
1319 Size qbuffer_size = 0;
1322 HASH_SEQ_STATUS hash_seq;
1325 /* hash table must exist already */
1326 if (!pgss || !pgss_hash)
1328 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1329 errmsg("pg_stat_statements must be loaded via shared_preload_libraries")));
1331 /* check to see if caller supports us returning a tuplestore */
1332 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1334 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1335 errmsg("set-valued function called in context that cannot accept a set")));
1336 if (!(rsinfo->allowedModes & SFRM_Materialize))
1338 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1339 errmsg("materialize mode required, but it is not " \
1340 "allowed in this context")));
1342 /* Switch into long-lived context to construct returned data structures */
1343 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1344 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1346 /* Build a tuple descriptor for our result type */
1347 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1348 elog(ERROR, "return type must be a row type");
1351 * Check we have the expected number of output arguments. Aside from
1352 * being a good safety check, we need a kluge here to detect API version
1353 * 1.1, which was wedged into the code in an ill-considered way.
1355 switch (tupdesc->natts)
1357 case PG_STAT_STATEMENTS_COLS_V1_0:
1358 if (api_version != PGSS_V1_0)
1359 elog(ERROR, "incorrect number of output arguments");
1361 case PG_STAT_STATEMENTS_COLS_V1_1:
1362 /* pg_stat_statements() should have told us 1.0 */
1363 if (api_version != PGSS_V1_0)
1364 elog(ERROR, "incorrect number of output arguments");
1365 api_version = PGSS_V1_1;
1367 case PG_STAT_STATEMENTS_COLS_V1_2:
1368 if (api_version != PGSS_V1_2)
1369 elog(ERROR, "incorrect number of output arguments");
1372 elog(ERROR, "incorrect number of output arguments");
1375 tupstore = tuplestore_begin_heap(true, false, work_mem);
1376 rsinfo->returnMode = SFRM_Materialize;
1377 rsinfo->setResult = tupstore;
1378 rsinfo->setDesc = tupdesc;
1380 MemoryContextSwitchTo(oldcontext);
1383 * We'd like to load the query text file (if needed) while not holding any
1384 * lock on pgss->lock. In the worst case we'll have to do this again
1385 * after we have the lock, but it's unlikely enough to make this a win
1386 * despite occasional duplicated work. We need to reload if anybody
1387 * writes to the file (either a retail qtext_store(), or a garbage
1388 * collection) between this point and where we've gotten shared lock. If
1389 * a qtext_store is actually in progress when we look, we might as well
1390 * skip the speculative load entirely.
1396 /* Take the mutex so we can examine variables */
1398 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss;
1400 SpinLockAcquire(&s->mutex);
1402 n_writers = s->n_writers;
1403 gc_count = s->gc_count;
1404 SpinLockRelease(&s->mutex);
1407 /* No point in loading file now if there are active writers */
1409 qbuffer = qtext_load_file(&qbuffer_size);
1413 * Get shared lock, load or reload the query text file if we must, and
1414 * iterate over the hashtable entries.
1416 * With a large hash table, we might be holding the lock rather longer
1417 * than one could wish. However, this only blocks creation of new hash
1418 * table entries, and the larger the hash table the less likely that is to
1419 * be needed. So we can hope this is okay. Perhaps someday we'll decide
1420 * we need to partition the hash table to limit the time spent holding any
1423 LWLockAcquire(pgss->lock, LW_SHARED);
1428 * Here it is safe to examine extent and gc_count without taking the
1429 * mutex. Note that although other processes might change
1430 * pgss->extent just after we look at it, the strings they then write
1431 * into the file cannot yet be referenced in the hashtable, so we
1432 * don't care whether we see them or not.
1434 * If qtext_load_file fails, we just press on; we'll return NULL for
1437 if (qbuffer == NULL ||
1438 pgss->extent != extent ||
1439 pgss->gc_count != gc_count)
1443 qbuffer = qtext_load_file(&qbuffer_size);
1447 hash_seq_init(&hash_seq, pgss_hash);
1448 while ((entry = hash_seq_search(&hash_seq)) != NULL)
1450 Datum values[PG_STAT_STATEMENTS_COLS];
1451 bool nulls[PG_STAT_STATEMENTS_COLS];
1454 int64 queryid = entry->key.queryid;
1456 memset(values, 0, sizeof(values));
1457 memset(nulls, 0, sizeof(nulls));
1459 values[i++] = ObjectIdGetDatum(entry->key.userid);
1460 values[i++] = ObjectIdGetDatum(entry->key.dbid);
1462 if (is_superuser || entry->key.userid == userid)
1464 if (api_version >= PGSS_V1_2)
1465 values[i++] = Int64GetDatumFast(queryid);
1469 char *qstr = qtext_fetch(entry->query_offset,
1478 enc = pg_any_to_server(qstr,
1482 values[i++] = CStringGetTextDatum(enc);
1489 /* Just return a null if we fail to find the text */
1495 /* Query text not requested */
1501 /* Don't show queryid */
1502 if (api_version >= PGSS_V1_2)
1506 * Don't show query text, but hint as to the reason for not doing
1507 * so if it was requested
1510 values[i++] = CStringGetTextDatum("<insufficient privilege>");
1515 /* copy counters to a local variable to keep locking time short */
1517 volatile pgssEntry *e = (volatile pgssEntry *) entry;
1519 SpinLockAcquire(&e->mutex);
1521 SpinLockRelease(&e->mutex);
1524 /* Skip entry if unexecuted (ie, it's a pending "sticky" entry) */
1528 values[i++] = Int64GetDatumFast(tmp.calls);
1529 values[i++] = Float8GetDatumFast(tmp.total_time);
1530 values[i++] = Int64GetDatumFast(tmp.rows);
1531 values[i++] = Int64GetDatumFast(tmp.shared_blks_hit);
1532 values[i++] = Int64GetDatumFast(tmp.shared_blks_read);
1533 if (api_version >= PGSS_V1_1)
1534 values[i++] = Int64GetDatumFast(tmp.shared_blks_dirtied);
1535 values[i++] = Int64GetDatumFast(tmp.shared_blks_written);
1536 values[i++] = Int64GetDatumFast(tmp.local_blks_hit);
1537 values[i++] = Int64GetDatumFast(tmp.local_blks_read);
1538 if (api_version >= PGSS_V1_1)
1539 values[i++] = Int64GetDatumFast(tmp.local_blks_dirtied);
1540 values[i++] = Int64GetDatumFast(tmp.local_blks_written);
1541 values[i++] = Int64GetDatumFast(tmp.temp_blks_read);
1542 values[i++] = Int64GetDatumFast(tmp.temp_blks_written);
1543 if (api_version >= PGSS_V1_1)
1545 values[i++] = Float8GetDatumFast(tmp.blk_read_time);
1546 values[i++] = Float8GetDatumFast(tmp.blk_write_time);
1549 Assert(i == (api_version == PGSS_V1_0 ? PG_STAT_STATEMENTS_COLS_V1_0 :
1550 api_version == PGSS_V1_1 ? PG_STAT_STATEMENTS_COLS_V1_1 :
1551 api_version == PGSS_V1_2 ? PG_STAT_STATEMENTS_COLS_V1_2 :
1552 -1 /* fail if you forget to update this assert */ ));
1554 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1557 /* clean up and return the tuplestore */
1558 LWLockRelease(pgss->lock);
1563 tuplestore_donestoring(tupstore);
1567 * Estimate shared memory space needed.
1574 size = MAXALIGN(sizeof(pgssSharedState));
1575 size = add_size(size, hash_estimate_size(pgss_max, sizeof(pgssEntry)));
1581 * Allocate a new hashtable entry.
1582 * caller must hold an exclusive lock on pgss->lock
1584 * "query" need not be null-terminated; we rely on query_len instead
1586 * If "sticky" is true, make the new entry artificially sticky so that it will
1587 * probably still be there when the query finishes execution. We do this by
1588 * giving it a median usage value rather than the normal value. (Strictly
1589 * speaking, query strings are normalized on a best effort basis, though it
1590 * would be difficult to demonstrate this even under artificial conditions.)
1592 * Note: despite needing exclusive lock, it's not an error for the target
1593 * entry to already exist. This is because pgss_store releases and
1594 * reacquires lock after failing to find a match; so someone else could
1595 * have made the entry while we waited to get exclusive lock.
1598 entry_alloc(pgssHashKey *key, Size query_offset, int query_len, int encoding,
1604 /* Make space if needed */
1605 while (hash_get_num_entries(pgss_hash) >= pgss_max)
1608 /* Find or create an entry with desired hash code */
1609 entry = (pgssEntry *) hash_search(pgss_hash, key, HASH_ENTER, &found);
1613 /* New entry, initialize it */
1615 /* reset the statistics */
1616 memset(&entry->counters, 0, sizeof(Counters));
1617 /* set the appropriate initial usage count */
1618 entry->counters.usage = sticky ? pgss->cur_median_usage : USAGE_INIT;
1619 /* re-initialize the mutex each time ... we assume no one using it */
1620 SpinLockInit(&entry->mutex);
1621 /* ... and don't forget the query text metadata */
1622 Assert(query_len >= 0);
1623 entry->query_offset = query_offset;
1624 entry->query_len = query_len;
1625 entry->encoding = encoding;
1632 * qsort comparator for sorting into increasing usage order
1635 entry_cmp(const void *lhs, const void *rhs)
1637 double l_usage = (*(pgssEntry *const *) lhs)->counters.usage;
1638 double r_usage = (*(pgssEntry *const *) rhs)->counters.usage;
1640 if (l_usage < r_usage)
1642 else if (l_usage > r_usage)
1649 * Deallocate least used entries.
1650 * Caller must hold an exclusive lock on pgss->lock.
1655 HASH_SEQ_STATUS hash_seq;
1656 pgssEntry **entries;
1663 * Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them.
1664 * While we're scanning the table, apply the decay factor to the usage
1668 entries = palloc(hash_get_num_entries(pgss_hash) * sizeof(pgssEntry *));
1671 hash_seq_init(&hash_seq, pgss_hash);
1672 while ((entry = hash_seq_search(&hash_seq)) != NULL)
1674 entries[i++] = entry;
1675 /* "Sticky" entries get a different usage decay rate. */
1676 if (entry->counters.calls == 0)
1677 entry->counters.usage *= STICKY_DECREASE_FACTOR;
1679 entry->counters.usage *= USAGE_DECREASE_FACTOR;
1680 /* Accumulate total size, too. */
1681 totlen += entry->query_len + 1;
1684 qsort(entries, i, sizeof(pgssEntry *), entry_cmp);
1688 /* Record the (approximate) median usage */
1689 pgss->cur_median_usage = entries[i / 2]->counters.usage;
1690 /* Record the mean query length */
1691 pgss->mean_query_len = totlen / i;
1694 nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
1695 nvictims = Min(nvictims, i);
1697 for (i = 0; i < nvictims; i++)
1699 hash_search(pgss_hash, &entries[i]->key, HASH_REMOVE, NULL);
1706 * Given a null-terminated string, allocate a new entry in the external query
1707 * text file and store the string there.
1709 * Although we could compute the string length via strlen(), callers already
1710 * have it handy, so we require them to pass it too.
1712 * If successful, returns true, and stores the new entry's offset in the file
1713 * into *query_offset. Also, if gc_count isn't NULL, *gc_count is set to the
1714 * number of garbage collections that have occurred so far.
1716 * On failure, returns false.
1718 * At least a shared lock on pgss->lock must be held by the caller, so as
1719 * to prevent a concurrent garbage collection. Share-lock-holding callers
1720 * should pass a gc_count pointer to obtain the number of garbage collections,
1721 * so that they can recheck the count after obtaining exclusive lock to
1722 * detect whether a garbage collection occurred (and removed this entry).
1725 qtext_store(const char *query, int query_len,
1726 Size *query_offset, int *gc_count)
1732 * We use a spinlock to protect extent/n_writers/gc_count, so that
1733 * multiple processes may execute this function concurrently.
1736 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss;
1738 SpinLockAcquire(&s->mutex);
1740 s->extent += query_len + 1;
1743 *gc_count = s->gc_count;
1744 SpinLockRelease(&s->mutex);
1747 *query_offset = off;
1749 /* Now write the data into the successfully-reserved part of the file */
1750 fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDWR | O_CREAT | PG_BINARY,
1755 if (lseek(fd, off, SEEK_SET) != off)
1758 if (write(fd, query, query_len + 1) != query_len + 1)
1761 CloseTransientFile(fd);
1763 /* Mark our write complete */
1765 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss;
1767 SpinLockAcquire(&s->mutex);
1769 SpinLockRelease(&s->mutex);
1776 (errcode_for_file_access(),
1777 errmsg("could not write pg_stat_statement file \"%s\": %m",
1781 CloseTransientFile(fd);
1783 /* Mark our write complete */
1785 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss;
1787 SpinLockAcquire(&s->mutex);
1789 SpinLockRelease(&s->mutex);
1796 * Read the external query text file into a malloc'd buffer.
1798 * Returns NULL (without throwing an error) if unable to read, eg
1799 * file not there or insufficient memory.
1801 * On success, the buffer size is also returned into *buffer_size.
1803 * This can be called without any lock on pgss->lock, but in that case
1804 * the caller is responsible for verifying that the result is sane.
1807 qtext_load_file(Size *buffer_size)
1813 fd = OpenTransientFile(PGSS_TEXT_FILE, O_RDONLY | PG_BINARY, 0);
1816 if (errno != ENOENT)
1818 (errcode_for_file_access(),
1819 errmsg("could not read pg_stat_statement file \"%s\": %m",
1824 /* Get file length */
1825 if (fstat(fd, &stat))
1828 (errcode_for_file_access(),
1829 errmsg("could not stat pg_stat_statement file \"%s\": %m",
1831 CloseTransientFile(fd);
1835 /* Allocate buffer; beware that off_t might be wider than size_t */
1836 if (stat.st_size <= MaxAllocSize)
1837 buf = (char *) malloc(stat.st_size);
1843 (errcode(ERRCODE_OUT_OF_MEMORY),
1844 errmsg("out of memory")));
1845 CloseTransientFile(fd);
1850 * OK, slurp in the file. If we get a short read and errno doesn't get
1851 * set, the reason is probably that garbage collection truncated the file
1852 * since we did the fstat(), so we don't log a complaint --- but we don't
1853 * return the data, either, since it's most likely corrupt due to
1854 * concurrent writes from garbage collection.
1857 if (read(fd, buf, stat.st_size) != stat.st_size)
1861 (errcode_for_file_access(),
1862 errmsg("could not read pg_stat_statement file \"%s\": %m",
1865 CloseTransientFile(fd);
1869 CloseTransientFile(fd);
1871 *buffer_size = stat.st_size;
1876 * Locate a query text in the file image previously read by qtext_load_file().
1878 * We validate the given offset/length, and return NULL if bogus. Otherwise,
1879 * the result points to a null-terminated string within the buffer.
1882 qtext_fetch(Size query_offset, int query_len,
1883 char *buffer, Size buffer_size)
1885 /* File read failed? */
1888 /* Bogus offset/length? */
1889 if (query_len < 0 ||
1890 query_offset + query_len >= buffer_size)
1892 /* As a further sanity check, make sure there's a trailing null */
1893 if (buffer[query_offset + query_len] != '\0')
1896 return buffer + query_offset;
1900 * Do we need to garbage-collect the external query text file?
1902 * Caller should hold at least a shared lock on pgss->lock.
1905 need_gc_qtexts(void)
1909 /* Read shared extent pointer */
1911 volatile pgssSharedState *s = (volatile pgssSharedState *) pgss;
1913 SpinLockAcquire(&s->mutex);
1915 SpinLockRelease(&s->mutex);
1918 /* Don't proceed if file does not exceed 512 bytes per possible entry */
1919 if (extent < 512 * pgss_max)
1923 * Don't proceed if file is less than about 50% bloat. Nothing can or
1924 * should be done in the event of unusually large query texts accounting
1925 * for file's large size. We go to the trouble of maintaining the mean
1926 * query length in order to prevent garbage collection from thrashing
1929 if (extent < pgss->mean_query_len * pgss_max * 2)
1936 * Garbage-collect orphaned query texts in external file.
1938 * This won't be called often in the typical case, since it's likely that
1939 * there won't be too much churn, and besides, a similar compaction process
1940 * occurs when serializing to disk at shutdown or as part of resetting.
1941 * Despite this, it seems prudent to plan for the edge case where the file
1942 * becomes unreasonably large, with no other method of compaction likely to
1943 * occur in the foreseeable future.
1945 * The caller must hold an exclusive lock on pgss->lock.
1953 HASH_SEQ_STATUS hash_seq;
1959 * When called from pgss_store, some other session might have proceeded
1960 * with garbage collection in the no-lock-held interim of lock strength
1961 * escalation. Check once more that this is actually necessary.
1963 if (!need_gc_qtexts())
1967 * Load the old texts file. If we fail (out of memory, for instance) just
1968 * skip the garbage collection.
1970 qbuffer = qtext_load_file(&qbuffer_size);
1971 if (qbuffer == NULL)
1975 * We overwrite the query texts file in place, so as to reduce the risk of
1976 * an out-of-disk-space failure. Since the file is guaranteed not to get
1977 * larger, this should always work on traditional filesystems; though we
1978 * could still lose on copy-on-write filesystems.
1980 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
1984 (errcode_for_file_access(),
1985 errmsg("could not write pg_stat_statement file \"%s\": %m",
1993 hash_seq_init(&hash_seq, pgss_hash);
1994 while ((entry = hash_seq_search(&hash_seq)) != NULL)
1996 int query_len = entry->query_len;
1997 char *qry = qtext_fetch(entry->query_offset,
2004 /* Trouble ... drop the text */
2005 entry->query_offset = 0;
2006 entry->query_len = -1;
2010 if (fwrite(qry, 1, query_len + 1, qfile) != query_len + 1)
2013 (errcode_for_file_access(),
2014 errmsg("could not write pg_stat_statement file \"%s\": %m",
2016 hash_seq_term(&hash_seq);
2020 entry->query_offset = extent;
2021 extent += query_len + 1;
2026 * Truncate away any now-unused space. If this fails for some odd reason,
2027 * we log it, but there's no need to fail.
2029 if (ftruncate(fileno(qfile), extent) != 0)
2031 (errcode_for_file_access(),
2032 errmsg("could not truncate pg_stat_statement file \"%s\": %m",
2035 if (FreeFile(qfile))
2038 (errcode_for_file_access(),
2039 errmsg("could not write pg_stat_statement file \"%s\": %m",
2045 elog(DEBUG1, "pgss gc of queries file shrunk size from %zu to %zu",
2046 pgss->extent, extent);
2048 /* Reset the shared extent pointer */
2049 pgss->extent = extent;
2052 * Also update the mean query length, to be sure that need_gc_qtexts()
2053 * won't still think we have a problem.
2056 pgss->mean_query_len = extent / nentries;
2058 pgss->mean_query_len = ASSUMED_LENGTH_INIT;
2063 * OK, count a garbage collection cycle. (Note: even though we have
2064 * exclusive lock on pgss->lock, we must take pgss->mutex for this, since
2065 * other processes may examine gc_count while holding only the mutex.
2066 * Also, we have to advance the count *after* we've rewritten the file,
2067 * else other processes might not realize they read a stale file.)
2074 /* clean up resources */
2081 * Since the contents of the external file are now uncertain, mark all
2082 * hashtable entries as having invalid texts.
2084 hash_seq_init(&hash_seq, pgss_hash);
2085 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2087 entry->query_offset = 0;
2088 entry->query_len = -1;
2091 /* Seems like a good idea to bump the GC count even though we failed */
2096 * Release all entries.
2101 HASH_SEQ_STATUS hash_seq;
2105 LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
2107 hash_seq_init(&hash_seq, pgss_hash);
2108 while ((entry = hash_seq_search(&hash_seq)) != NULL)
2110 hash_search(pgss_hash, &entry->key, HASH_REMOVE, NULL);
2114 * Write new empty query file, perhaps even creating a new one to recover
2115 * if the file was missing.
2117 qfile = AllocateFile(PGSS_TEXT_FILE, PG_BINARY_W);
2121 (errcode_for_file_access(),
2122 errmsg("could not create pg_stat_statement file \"%s\": %m",
2127 /* If ftruncate fails, log it, but it's not a fatal problem */
2128 if (ftruncate(fileno(qfile), 0) != 0)
2130 (errcode_for_file_access(),
2131 errmsg("could not truncate pg_stat_statement file \"%s\": %m",
2138 /* This counts as a query text garbage collection for our purposes */
2141 LWLockRelease(pgss->lock);
2146 * AppendJumble: Append a value that is substantive in a given query to
2147 * the current jumble.
2150 AppendJumble(pgssJumbleState *jstate, const unsigned char *item, Size size)
2152 unsigned char *jumble = jstate->jumble;
2153 Size jumble_len = jstate->jumble_len;
2156 * Whenever the jumble buffer is full, we hash the current contents and
2157 * reset the buffer to contain just that hash value, thus relying on the
2158 * hash to summarize everything so far.
2164 if (jumble_len >= JUMBLE_SIZE)
2166 uint32 start_hash = hash_any(jumble, JUMBLE_SIZE);
2168 memcpy(jumble, &start_hash, sizeof(start_hash));
2169 jumble_len = sizeof(start_hash);
2171 part_size = Min(size, JUMBLE_SIZE - jumble_len);
2172 memcpy(jumble + jumble_len, item, part_size);
2173 jumble_len += part_size;
2177 jstate->jumble_len = jumble_len;
2181 * Wrappers around AppendJumble to encapsulate details of serialization
2182 * of individual local variable elements.
2184 #define APP_JUMB(item) \
2185 AppendJumble(jstate, (const unsigned char *) &(item), sizeof(item))
2186 #define APP_JUMB_STRING(str) \
2187 AppendJumble(jstate, (const unsigned char *) (str), strlen(str) + 1)
2190 * JumbleQuery: Selectively serialize the query tree, appending significant
2191 * data to the "query jumble" while ignoring nonsignificant data.
2193 * Rule of thumb for what to include is that we should ignore anything not
2194 * semantically significant (such as alias names) as well as anything that can
2195 * be deduced from child nodes (else we'd just be double-hashing that piece
2199 JumbleQuery(pgssJumbleState *jstate, Query *query)
2201 Assert(IsA(query, Query));
2202 Assert(query->utilityStmt == NULL);
2204 APP_JUMB(query->commandType);
2205 /* resultRelation is usually predictable from commandType */
2206 JumbleExpr(jstate, (Node *) query->cteList);
2207 JumbleRangeTable(jstate, query->rtable);
2208 JumbleExpr(jstate, (Node *) query->jointree);
2209 JumbleExpr(jstate, (Node *) query->targetList);
2210 JumbleExpr(jstate, (Node *) query->returningList);
2211 JumbleExpr(jstate, (Node *) query->groupClause);
2212 JumbleExpr(jstate, query->havingQual);
2213 JumbleExpr(jstate, (Node *) query->windowClause);
2214 JumbleExpr(jstate, (Node *) query->distinctClause);
2215 JumbleExpr(jstate, (Node *) query->sortClause);
2216 JumbleExpr(jstate, query->limitOffset);
2217 JumbleExpr(jstate, query->limitCount);
2218 /* we ignore rowMarks */
2219 JumbleExpr(jstate, query->setOperations);
2223 * Jumble a range table
2226 JumbleRangeTable(pgssJumbleState *jstate, List *rtable)
2232 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2234 Assert(IsA(rte, RangeTblEntry));
2235 APP_JUMB(rte->rtekind);
2236 switch (rte->rtekind)
2239 APP_JUMB(rte->relid);
2242 JumbleQuery(jstate, rte->subquery);
2245 APP_JUMB(rte->jointype);
2248 JumbleExpr(jstate, (Node *) rte->functions);
2251 JumbleExpr(jstate, (Node *) rte->values_lists);
2256 * Depending on the CTE name here isn't ideal, but it's the
2257 * only info we have to identify the referenced WITH item.
2259 APP_JUMB_STRING(rte->ctename);
2260 APP_JUMB(rte->ctelevelsup);
2263 elog(ERROR, "unrecognized RTE kind: %d", (int) rte->rtekind);
2270 * Jumble an expression tree
2272 * In general this function should handle all the same node types that
2273 * expression_tree_walker() does, and therefore it's coded to be as parallel
2274 * to that function as possible. However, since we are only invoked on
2275 * queries immediately post-parse-analysis, we need not handle node types
2276 * that only appear in planning.
2278 * Note: the reason we don't simply use expression_tree_walker() is that the
2279 * point of that function is to support tree walkers that don't care about
2280 * most tree node types, but here we care about all types. We should complain
2281 * about any unrecognized node type.
2284 JumbleExpr(pgssJumbleState *jstate, Node *node)
2291 /* Guard against stack overflow due to overly complex expressions */
2292 check_stack_depth();
2295 * We always emit the node's NodeTag, then any additional fields that are
2296 * considered significant, and then we recurse to any child nodes.
2298 APP_JUMB(node->type);
2300 switch (nodeTag(node))
2304 Var *var = (Var *) node;
2306 APP_JUMB(var->varno);
2307 APP_JUMB(var->varattno);
2308 APP_JUMB(var->varlevelsup);
2313 Const *c = (Const *) node;
2315 /* We jumble only the constant's type, not its value */
2316 APP_JUMB(c->consttype);
2317 /* Also, record its parse location for query normalization */
2318 RecordConstLocation(jstate, c->location);
2323 Param *p = (Param *) node;
2325 APP_JUMB(p->paramkind);
2326 APP_JUMB(p->paramid);
2327 APP_JUMB(p->paramtype);
2332 Aggref *expr = (Aggref *) node;
2334 APP_JUMB(expr->aggfnoid);
2335 JumbleExpr(jstate, (Node *) expr->aggdirectargs);
2336 JumbleExpr(jstate, (Node *) expr->args);
2337 JumbleExpr(jstate, (Node *) expr->aggorder);
2338 JumbleExpr(jstate, (Node *) expr->aggdistinct);
2339 JumbleExpr(jstate, (Node *) expr->aggfilter);
2344 WindowFunc *expr = (WindowFunc *) node;
2346 APP_JUMB(expr->winfnoid);
2347 APP_JUMB(expr->winref);
2348 JumbleExpr(jstate, (Node *) expr->args);
2349 JumbleExpr(jstate, (Node *) expr->aggfilter);
2354 ArrayRef *aref = (ArrayRef *) node;
2356 JumbleExpr(jstate, (Node *) aref->refupperindexpr);
2357 JumbleExpr(jstate, (Node *) aref->reflowerindexpr);
2358 JumbleExpr(jstate, (Node *) aref->refexpr);
2359 JumbleExpr(jstate, (Node *) aref->refassgnexpr);
2364 FuncExpr *expr = (FuncExpr *) node;
2366 APP_JUMB(expr->funcid);
2367 JumbleExpr(jstate, (Node *) expr->args);
2370 case T_NamedArgExpr:
2372 NamedArgExpr *nae = (NamedArgExpr *) node;
2374 APP_JUMB(nae->argnumber);
2375 JumbleExpr(jstate, (Node *) nae->arg);
2379 case T_DistinctExpr: /* struct-equivalent to OpExpr */
2380 case T_NullIfExpr: /* struct-equivalent to OpExpr */
2382 OpExpr *expr = (OpExpr *) node;
2384 APP_JUMB(expr->opno);
2385 JumbleExpr(jstate, (Node *) expr->args);
2388 case T_ScalarArrayOpExpr:
2390 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2392 APP_JUMB(expr->opno);
2393 APP_JUMB(expr->useOr);
2394 JumbleExpr(jstate, (Node *) expr->args);
2399 BoolExpr *expr = (BoolExpr *) node;
2401 APP_JUMB(expr->boolop);
2402 JumbleExpr(jstate, (Node *) expr->args);
2407 SubLink *sublink = (SubLink *) node;
2409 APP_JUMB(sublink->subLinkType);
2410 JumbleExpr(jstate, (Node *) sublink->testexpr);
2411 JumbleQuery(jstate, (Query *) sublink->subselect);
2416 FieldSelect *fs = (FieldSelect *) node;
2418 APP_JUMB(fs->fieldnum);
2419 JumbleExpr(jstate, (Node *) fs->arg);
2424 FieldStore *fstore = (FieldStore *) node;
2426 JumbleExpr(jstate, (Node *) fstore->arg);
2427 JumbleExpr(jstate, (Node *) fstore->newvals);
2432 RelabelType *rt = (RelabelType *) node;
2434 APP_JUMB(rt->resulttype);
2435 JumbleExpr(jstate, (Node *) rt->arg);
2440 CoerceViaIO *cio = (CoerceViaIO *) node;
2442 APP_JUMB(cio->resulttype);
2443 JumbleExpr(jstate, (Node *) cio->arg);
2446 case T_ArrayCoerceExpr:
2448 ArrayCoerceExpr *acexpr = (ArrayCoerceExpr *) node;
2450 APP_JUMB(acexpr->resulttype);
2451 JumbleExpr(jstate, (Node *) acexpr->arg);
2454 case T_ConvertRowtypeExpr:
2456 ConvertRowtypeExpr *crexpr = (ConvertRowtypeExpr *) node;
2458 APP_JUMB(crexpr->resulttype);
2459 JumbleExpr(jstate, (Node *) crexpr->arg);
2464 CollateExpr *ce = (CollateExpr *) node;
2466 APP_JUMB(ce->collOid);
2467 JumbleExpr(jstate, (Node *) ce->arg);
2472 CaseExpr *caseexpr = (CaseExpr *) node;
2474 JumbleExpr(jstate, (Node *) caseexpr->arg);
2475 foreach(temp, caseexpr->args)
2477 CaseWhen *when = (CaseWhen *) lfirst(temp);
2479 Assert(IsA(when, CaseWhen));
2480 JumbleExpr(jstate, (Node *) when->expr);
2481 JumbleExpr(jstate, (Node *) when->result);
2483 JumbleExpr(jstate, (Node *) caseexpr->defresult);
2486 case T_CaseTestExpr:
2488 CaseTestExpr *ct = (CaseTestExpr *) node;
2490 APP_JUMB(ct->typeId);
2494 JumbleExpr(jstate, (Node *) ((ArrayExpr *) node)->elements);
2497 JumbleExpr(jstate, (Node *) ((RowExpr *) node)->args);
2499 case T_RowCompareExpr:
2501 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2503 APP_JUMB(rcexpr->rctype);
2504 JumbleExpr(jstate, (Node *) rcexpr->largs);
2505 JumbleExpr(jstate, (Node *) rcexpr->rargs);
2508 case T_CoalesceExpr:
2509 JumbleExpr(jstate, (Node *) ((CoalesceExpr *) node)->args);
2513 MinMaxExpr *mmexpr = (MinMaxExpr *) node;
2515 APP_JUMB(mmexpr->op);
2516 JumbleExpr(jstate, (Node *) mmexpr->args);
2521 XmlExpr *xexpr = (XmlExpr *) node;
2523 APP_JUMB(xexpr->op);
2524 JumbleExpr(jstate, (Node *) xexpr->named_args);
2525 JumbleExpr(jstate, (Node *) xexpr->args);
2530 NullTest *nt = (NullTest *) node;
2532 APP_JUMB(nt->nulltesttype);
2533 JumbleExpr(jstate, (Node *) nt->arg);
2538 BooleanTest *bt = (BooleanTest *) node;
2540 APP_JUMB(bt->booltesttype);
2541 JumbleExpr(jstate, (Node *) bt->arg);
2544 case T_CoerceToDomain:
2546 CoerceToDomain *cd = (CoerceToDomain *) node;
2548 APP_JUMB(cd->resulttype);
2549 JumbleExpr(jstate, (Node *) cd->arg);
2552 case T_CoerceToDomainValue:
2554 CoerceToDomainValue *cdv = (CoerceToDomainValue *) node;
2556 APP_JUMB(cdv->typeId);
2559 case T_SetToDefault:
2561 SetToDefault *sd = (SetToDefault *) node;
2563 APP_JUMB(sd->typeId);
2566 case T_CurrentOfExpr:
2568 CurrentOfExpr *ce = (CurrentOfExpr *) node;
2570 APP_JUMB(ce->cvarno);
2571 if (ce->cursor_name)
2572 APP_JUMB_STRING(ce->cursor_name);
2573 APP_JUMB(ce->cursor_param);
2578 TargetEntry *tle = (TargetEntry *) node;
2580 APP_JUMB(tle->resno);
2581 APP_JUMB(tle->ressortgroupref);
2582 JumbleExpr(jstate, (Node *) tle->expr);
2587 RangeTblRef *rtr = (RangeTblRef *) node;
2589 APP_JUMB(rtr->rtindex);
2594 JoinExpr *join = (JoinExpr *) node;
2596 APP_JUMB(join->jointype);
2597 APP_JUMB(join->isNatural);
2598 APP_JUMB(join->rtindex);
2599 JumbleExpr(jstate, join->larg);
2600 JumbleExpr(jstate, join->rarg);
2601 JumbleExpr(jstate, join->quals);
2606 FromExpr *from = (FromExpr *) node;
2608 JumbleExpr(jstate, (Node *) from->fromlist);
2609 JumbleExpr(jstate, from->quals);
2613 foreach(temp, (List *) node)
2615 JumbleExpr(jstate, (Node *) lfirst(temp));
2618 case T_SortGroupClause:
2620 SortGroupClause *sgc = (SortGroupClause *) node;
2622 APP_JUMB(sgc->tleSortGroupRef);
2623 APP_JUMB(sgc->eqop);
2624 APP_JUMB(sgc->sortop);
2625 APP_JUMB(sgc->nulls_first);
2628 case T_WindowClause:
2630 WindowClause *wc = (WindowClause *) node;
2632 APP_JUMB(wc->winref);
2633 APP_JUMB(wc->frameOptions);
2634 JumbleExpr(jstate, (Node *) wc->partitionClause);
2635 JumbleExpr(jstate, (Node *) wc->orderClause);
2636 JumbleExpr(jstate, wc->startOffset);
2637 JumbleExpr(jstate, wc->endOffset);
2640 case T_CommonTableExpr:
2642 CommonTableExpr *cte = (CommonTableExpr *) node;
2644 /* we store the string name because RTE_CTE RTEs need it */
2645 APP_JUMB_STRING(cte->ctename);
2646 JumbleQuery(jstate, (Query *) cte->ctequery);
2649 case T_SetOperationStmt:
2651 SetOperationStmt *setop = (SetOperationStmt *) node;
2653 APP_JUMB(setop->op);
2654 APP_JUMB(setop->all);
2655 JumbleExpr(jstate, setop->larg);
2656 JumbleExpr(jstate, setop->rarg);
2659 case T_RangeTblFunction:
2661 RangeTblFunction *rtfunc = (RangeTblFunction *) node;
2663 JumbleExpr(jstate, rtfunc->funcexpr);
2667 /* Only a warning, since we can stumble along anyway */
2668 elog(WARNING, "unrecognized node type: %d",
2669 (int) nodeTag(node));
2675 * Record location of constant within query string of query tree
2676 * that is currently being walked.
2679 RecordConstLocation(pgssJumbleState *jstate, int location)
2681 /* -1 indicates unknown or undefined location */
2684 /* enlarge array if needed */
2685 if (jstate->clocations_count >= jstate->clocations_buf_size)
2687 jstate->clocations_buf_size *= 2;
2688 jstate->clocations = (pgssLocationLen *)
2689 repalloc(jstate->clocations,
2690 jstate->clocations_buf_size *
2691 sizeof(pgssLocationLen));
2693 jstate->clocations[jstate->clocations_count].location = location;
2694 /* initialize lengths to -1 to simplify fill_in_constant_lengths */
2695 jstate->clocations[jstate->clocations_count].length = -1;
2696 jstate->clocations_count++;
2701 * Generate a normalized version of the query string that will be used to
2702 * represent all similar queries.
2704 * Note that the normalized representation may well vary depending on
2705 * just which "equivalent" query is used to create the hashtable entry.
2706 * We assume this is OK.
2708 * *query_len_p contains the input string length, and is updated with
2709 * the result string length (which cannot be longer) on exit.
2711 * Returns a palloc'd string.
2714 generate_normalized_query(pgssJumbleState *jstate, const char *query,
2715 int *query_len_p, int encoding)
2718 int query_len = *query_len_p;
2720 len_to_wrt, /* Length (in bytes) to write */
2721 quer_loc = 0, /* Source query byte location */
2722 n_quer_loc = 0, /* Normalized query byte location */
2723 last_off = 0, /* Offset from start for previous tok */
2724 last_tok_len = 0; /* Length (in bytes) of that tok */
2727 * Get constants' lengths (core system only gives us locations). Note
2728 * this also ensures the items are sorted by location.
2730 fill_in_constant_lengths(jstate, query);
2732 /* Allocate result buffer */
2733 norm_query = palloc(query_len + 1);
2735 for (i = 0; i < jstate->clocations_count; i++)
2737 int off, /* Offset from start for cur tok */
2738 tok_len; /* Length (in bytes) of that tok */
2740 off = jstate->clocations[i].location;
2741 tok_len = jstate->clocations[i].length;
2744 continue; /* ignore any duplicates */
2746 /* Copy next chunk (what precedes the next constant) */
2747 len_to_wrt = off - last_off;
2748 len_to_wrt -= last_tok_len;
2750 Assert(len_to_wrt >= 0);
2751 memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
2752 n_quer_loc += len_to_wrt;
2754 /* And insert a '?' in place of the constant token */
2755 norm_query[n_quer_loc++] = '?';
2757 quer_loc = off + tok_len;
2759 last_tok_len = tok_len;
2763 * We've copied up until the last ignorable constant. Copy over the
2764 * remaining bytes of the original query string.
2766 len_to_wrt = query_len - quer_loc;
2768 Assert(len_to_wrt >= 0);
2769 memcpy(norm_query + n_quer_loc, query + quer_loc, len_to_wrt);
2770 n_quer_loc += len_to_wrt;
2772 Assert(n_quer_loc <= query_len);
2773 norm_query[n_quer_loc] = '\0';
2775 *query_len_p = n_quer_loc;
2780 * Given a valid SQL string and an array of constant-location records,
2781 * fill in the textual lengths of those constants.
2783 * The constants may use any allowed constant syntax, such as float literals,
2784 * bit-strings, single-quoted strings and dollar-quoted strings. This is
2785 * accomplished by using the public API for the core scanner.
2787 * It is the caller's job to ensure that the string is a valid SQL statement
2788 * with constants at the indicated locations. Since in practice the string
2789 * has already been parsed, and the locations that the caller provides will
2790 * have originated from within the authoritative parser, this should not be
2793 * Duplicate constant pointers are possible, and will have their lengths
2794 * marked as '-1', so that they are later ignored. (Actually, we assume the
2795 * lengths were initialized as -1 to start with, and don't change them here.)
2797 * N.B. There is an assumption that a '-' character at a Const location begins
2798 * a negative numeric constant. This precludes there ever being another
2799 * reason for a constant to start with a '-'.
2802 fill_in_constant_lengths(pgssJumbleState *jstate, const char *query)
2804 pgssLocationLen *locs;
2805 core_yyscan_t yyscanner;
2806 core_yy_extra_type yyextra;
2807 core_YYSTYPE yylval;
2813 * Sort the records by location so that we can process them in order while
2814 * scanning the query text.
2816 if (jstate->clocations_count > 1)
2817 qsort(jstate->clocations, jstate->clocations_count,
2818 sizeof(pgssLocationLen), comp_location);
2819 locs = jstate->clocations;
2821 /* initialize the flex scanner --- should match raw_parser() */
2822 yyscanner = scanner_init(query,
2827 /* Search for each constant, in sequence */
2828 for (i = 0; i < jstate->clocations_count; i++)
2830 int loc = locs[i].location;
2835 if (loc <= last_loc)
2836 continue; /* Duplicate constant, ignore */
2838 /* Lex tokens until we find the desired constant */
2841 tok = core_yylex(&yylval, &yylloc, yyscanner);
2843 /* We should not hit end-of-string, but if we do, behave sanely */
2845 break; /* out of inner for-loop */
2848 * We should find the token position exactly, but if we somehow
2849 * run past it, work with that.
2853 if (query[loc] == '-')
2856 * It's a negative value - this is the one and only case
2857 * where we replace more than a single token.
2859 * Do not compensate for the core system's special-case
2860 * adjustment of location to that of the leading '-'
2861 * operator in the event of a negative constant. It is
2862 * also useful for our purposes to start from the minus
2863 * symbol. In this way, queries like "select * from foo
2864 * where bar = 1" and "select * from foo where bar = -2"
2865 * will have identical normalized query strings.
2867 tok = core_yylex(&yylval, &yylloc, yyscanner);
2869 break; /* out of inner for-loop */
2873 * We now rely on the assumption that flex has placed a zero
2874 * byte after the text of the current token in scanbuf.
2876 locs[i].length = strlen(yyextra.scanbuf + loc);
2877 break; /* out of inner for-loop */
2881 /* If we hit end-of-string, give up, leaving remaining lengths -1 */
2888 scanner_finish(yyscanner);
2892 * comp_location: comparator for qsorting pgssLocationLen structs by location
2895 comp_location(const void *a, const void *b)
2897 int l = ((const pgssLocationLen *) a)->location;
2898 int r = ((const pgssLocationLen *) b)->location;