diff -cprN HEAD/contrib/Makefile pg_stat_statements/contrib/Makefile
*** HEAD/contrib/Makefile	Sat Nov 22 11:15:56 2008
--- pg_stat_statements/contrib/Makefile	Fri Dec 12 18:26:03 2008
*************** WANTED_DIRS = \
*** 31,36 ****
--- 31,37 ----
  		pgbench		\
  		pgcrypto	\
  		pgrowlocks	\
+ 		pg_stat_statements	\
  		pgstattuple	\
  		seg		\
  		spi		\
diff -cprN HEAD/contrib/pg_stat_statements/Makefile pg_stat_statements/contrib/pg_stat_statements/Makefile
*** HEAD/contrib/pg_stat_statements/Makefile	Thu Jan  1 09:00:00 1970
--- pg_stat_statements/contrib/pg_stat_statements/Makefile	Mon Jun 23 11:05:19 2008
***************
*** 0 ****
--- 1,15 ----
+ MODULE_big = pg_stat_statements
+ DATA_built = pg_stat_statements.sql
+ DATA = uninstall_pg_stat_statements.sql
+ OBJS = pg_stat_statements.o
+ 
+ ifdef USE_PGXS
+ PG_CONFIG = pg_config
+ PGXS := $(shell $(PG_CONFIG) --pgxs)
+ include $(PGXS)
+ else
+ subdir = contrib/pg_stat_statements
+ top_builddir = ../..
+ include $(top_builddir)/src/Makefile.global
+ include $(top_srcdir)/contrib/contrib-global.mk
+ endif
diff -cprN HEAD/contrib/pg_stat_statements/pg_stat_statements.c pg_stat_statements/contrib/pg_stat_statements/pg_stat_statements.c
*** HEAD/contrib/pg_stat_statements/pg_stat_statements.c	Thu Jan  1 09:00:00 1970
--- pg_stat_statements/contrib/pg_stat_statements/pg_stat_statements.c	Fri Dec 12 10:52:02 2008
***************
*** 0 ****
--- 1,810 ----
+ /*-------------------------------------------------------------------------
+  *
+  * pg_stat_statements.c
+  *
+  *-------------------------------------------------------------------------
+  */
+ #include "postgres.h"
+ 
+ #include <unistd.h>
+ 
+ #ifdef HAVE_SYS_RESOURCE_H
+ #include <sys/time.h>
+ #include <sys/resource.h>
+ #endif
+ #ifndef HAVE_GETRUSAGE
+ #include "rusagestub.h"
+ #endif
+ 
+ #include "access/hash.h"
+ #include "executor/instrument.h"
+ #include "funcapi.h"
+ #include "mb/pg_wchar.h"
+ #include "miscadmin.h"
+ #include "pgstat.h"
+ #include "storage/ipc.h"
+ #include "storage/spin.h"
+ #include "utils/builtins.h"
+ #include "utils/guc.h"
+ 
+ PG_MODULE_MAGIC;
+ 
+ #define GUCNAME(name)		("statistics." name)
+ 
+ #define MAX_STATEMENTS_DEFAULT	1000
+ #define CHUNK_SIZE				MAXALIGN(pgstat_track_activity_query_size)
+ 
+ const uint32 PGSS_FILE_HEADER = 0x20081202;
+ 
+ /* XXX: Should USAGE_EXEC reflect execution time and/or buffer usage? */
+ #define USAGE_EXEC(duration)	(1.0)
+ #define USAGE_INIT				(1.0)	/* including initial planning */
+ #define USAGE_DECREASE_FACTOR	(0.99)	/* decreased every entry_dealloc */
+ #define USAGE_DEALLOC_PERCENT	5		/* free this % of entries at once */
+ 
+ #define timeval_diff_in_usec(end, beg) \
+ 	( (int64) ((end).tv_sec - (beg).tv_sec) * 1000000 \
+ 	+ ((end).tv_usec - (beg).tv_usec))
+ 
+ #define track_statements_enabled() \
+ 	(track_statements == PGSS_TRACK_ALL || \
+ 	(track_statements == PGSS_TRACK_TOP && nested_level == 0))
+ 
+ /*
+  * Chunk buffer for query text.
+  */
+ typedef union Chunk Chunk;
+ union Chunk
+ {
+ 	char	query[1];	/* query text. true size is [CHUNK_SIZE] */
+ 	Chunk  *next;		/* next free chunk */
+ };
+ 
+ typedef struct Counters
+ {
+ 	int64		calls;		/* # of executed */
+ 	double		total_time;	/* total execution time in sec */
+ 	double		cpu_user;	/* user cpu time in sec */
+ 	double		cpu_sys;	/* sys cpu time in sec */
+ 	int64		gets;		/* # of buffer gets during execution */
+ 	int64		reads;		/* # of buffer reads during execution */
+ 	int64		lreads;		/* # of buffile reads during execution */
+ 	int64		rows;		/* # of retrieved or affected rows */
+ } Counters;
+ 
+ /*
+  * Statistics per statement
+  */
+ typedef struct Entry
+ {
+ 	uint32		tag;		/* hash value of query */
+ 	Oid			userid;		/* user oid */
+ 	Oid			dbid;		/* database oid */
+ 	Counters	counters;	/* counters */
+ 	double		usage;		/* usage factor */
+ 	Chunk	   *chunk;		/* query text */
+ 	slock_t		mutex;		/* protect above fields */
+ } Entry;
+ 
+ /*
+  * Global shared state
+  */
+ typedef struct pgStatStmt
+ {
+ 	LWLockId	lock;				/* protect fields and hash */
+ 	int			num_statements;		/* # of entries in hash */
+ 	int			chunk_size;			/* max query length in bytes */
+ 	Chunk	   *free_chunks;		/* single linked list of free chunks */
+ 	Chunk		chunks[1];			/* chunk buffers */
+ } pgStatStmt;
+ 
+ /*---- Local variables ----*/
+ 
+ static int						nested_level = 0;
+ static startup_hook_type		prev_startup_hook = NULL;
+ static shutdown_hook_type		prev_shutdown_hook = NULL;
+ static ExecutorStart_hook_type	prev_ExecutorStart = NULL;
+ static ExecutorRun_hook_type	prev_ExecutorRun = NULL;
+ static ExecutorEnd_hook_type	prev_ExecutorEnd = NULL;
+ static pgStatStmt			   *pgss;
+ static HTAB					   *pgss_hash;
+ static bool						reset_requested = false;
+ 
+ /*---- Function declarations ----*/
+ 
+ void	_PG_init(void);
+ void	_PG_fini(void);
+ Datum	pg_stat_statements_reset(PG_FUNCTION_ARGS);
+ Datum	pg_stat_statements(PG_FUNCTION_ARGS);
+ 
+ PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
+ PG_FUNCTION_INFO_V1(pg_stat_statements);
+ 
+ static uint32 pgss_tag(Oid userid, Oid dbid, const char *query);
+ static void pgss_ExecutorStart(QueryDesc *queryDesc, int eflags);
+ static void pgss_ExecutorRun(QueryDesc *queryDesc,
+ 							 ScanDirection direction,
+ 							 long count);
+ static void pgss_ExecutorEnd(QueryDesc *queryDesc);
+ static void pgss_executed(const char *query,
+ 						  const Instrumentation *instr, uint32 rows);
+ 
+ static Size	pgss_memsize(void);
+ static void pgss_init(void);
+ static volatile Entry *entry_alloc(uint32 tag, Oid userid, Oid dbid,
+ 							const char *query);
+ static void entry_dealloc(void);
+ static void entry_reset(void);
+ static Chunk *chunk_alloc(void);
+ static void chunk_free(Chunk *chunk);
+ static void chunk_reset(void);
+ 
+ static const char *assign_saved_file(const char *newval, bool doit, GucSource source);
+ 
+ /*---- GUC variables ----*/
+ 
+ typedef enum
+ {
+ 	PGSS_TRACK_NONE,	/* log no statements */
+ 	PGSS_TRACK_TOP,		/* only top level statements */
+ 	PGSS_TRACK_ALL,		/* all statements, including nested ones */
+ } PGSSTrackLevel;
+ 
+ static const struct config_enum_entry track_options[] = {
+ 	{"none", PGSS_TRACK_NONE, false},
+ 	{"top", PGSS_TRACK_TOP, false},
+ 	{"all", PGSS_TRACK_ALL, false},
+ 	{NULL, 0, false}
+ };
+ 
+ static int		max_statements;
+ static int		track_statements;
+ static char	   *saved_file;
+ 
+ /*
+  * pgss_shutdown - Dump statistics into file.
+  */
+ static void
+ pgss_shutdown(void)
+ {
+ 	FILE			   *file;
+ 	HASH_SEQ_STATUS		hash_seq;
+ 	Entry			   *entry;
+ 	int					save_errno;
+ 
+ 	if (prev_shutdown_hook)
+ 		prev_shutdown_hook();
+ 
+ 	if (saved_file == NULL || saved_file[0] == '\0')
+ 		return;
+ 
+ 	if (!pgss)
+ 		pgss_init();
+ 
+ 	file = fopen(saved_file, PG_BINARY_W);
+ 	if (file == NULL ||
+ 		fwrite(&PGSS_FILE_HEADER, sizeof(uint32), 1, file) != 1 ||
+ 		fwrite(&pgss->num_statements, sizeof(int32), 1, file) != 1)
+ 		goto error;
+ 
+ 	hash_seq_init(&hash_seq, pgss_hash);
+ 	while ((entry = hash_seq_search(&hash_seq)) != NULL)
+ 	{
+ 		int32	len = (int32) strlen(entry->chunk->query);
+ 
+ 		if (fwrite(entry, offsetof(Entry, chunk), 1, file) != 1 ||
+ 			fwrite(&len, sizeof(int32), 1, file) != 1 ||
+ 			fwrite(entry->chunk->query, 1, len, file) != len)
+ 			goto error;
+ 	}
+ 
+ 	fclose(file);
+ 	return;
+ 
+ error:
+ 	save_errno = errno;
+ 
+ 	if (file)
+ 		fclose(file);
+ 	unlink(saved_file);
+ 
+ 	errno = save_errno;
+ 	ereport(LOG,
+ 		(errcode_for_file_access(),
+ 		 errmsg("could not write pg_stat_statement file \"%s\": %m",
+ 				saved_file)));
+ }
+ 
+ /*
+  * pgss_startup - Load statistics from file.
+  */
+ static void
+ pgss_startup(void)
+ {
+ 	FILE	   *file;
+ 	uint32		header;
+ 	int32		num;
+ 	int32		i;
+ 	char	   *buffer = NULL;
+ 	int			save_errno;
+ 
+ 	if (prev_startup_hook)
+ 		prev_startup_hook();
+ 
+ 	if (saved_file == NULL || saved_file[0] == '\0')
+ 		return;
+ 
+ 	file = fopen(saved_file, PG_BINARY_R);
+ 	if (file == NULL)
+ 	{
+ 		if (errno == ENOENT)
+ 			return;	/* ignore not found error */
+ 		goto error;
+ 	}
+ 
+ 	if (!pgss)
+ 		pgss_init();
+ 
+ 	buffer = palloc(CHUNK_SIZE);
+ 
+ 	if (fread(&header, sizeof(uint32), 1, file) != 1 ||
+ 		header != PGSS_FILE_HEADER ||
+ 		fread(&num, sizeof(int32), 1, file) != 1)
+ 		goto error;
+ 
+ 	for (i = 0; i < num; i++)
+ 	{
+ 		Entry		temp;
+ 		Entry	   *entry;
+ 		int32		templen;
+ 		int32		len;
+ 
+ 		if (fread(&temp, offsetof(Entry, chunk), 1, file) != 1 ||
+ 			fread(&templen, sizeof(int32), 1, file) != 1)
+ 			goto error;
+ 
+ 		/*
+ 		 * We might not have enough buffer to read query text
+ 		 * when pgstat_track_activity_query_size is set smaller.
+ 		 */
+ 		if (templen < CHUNK_SIZE)
+ 			len = templen;
+ 		else
+ 			len = CHUNK_SIZE - 1;
+ 
+ 		if (fread(buffer, 1, len, file) != len)
+ 			goto error;
+ 		buffer[len] = '\0';
+ 		entry = (Entry *) entry_alloc(
+ 			temp.tag, temp.userid, temp.dbid, buffer);
+ 		memcpy(entry, &temp, offsetof(Entry, chunk));
+ 
+ 		/* Discard the tail of query text. */
+ 		if (templen > len)
+ 			fseek(file, templen - len, SEEK_CUR);
+ 	}
+ 
+ 	pfree(buffer);
+ 	fclose(file);
+ 	return;
+ 
+ error:
+ 	save_errno = errno;
+ 
+ 	if (file)
+ 		fclose(file);
+ 	unlink(saved_file);
+ 	if (buffer)
+ 		pfree(buffer);
+ 
+ 	errno = save_errno;
+ 	ereport(LOG,
+ 		(errcode_for_file_access(),
+ 		 errmsg("could not read pg_stat_statement file \"%s\": %m",
+ 				saved_file)));
+ }
+ 
+ void
+ _PG_init(void)
+ {
+ 	/* Define custom guc variables. */
+ 	DefineCustomIntVariable(
+ 		GUCNAME("max_statements"),
+ 		"Sets the maximum number of statements tracked by pg_stat_statements.",
+ 		NULL,
+ 		&max_statements,
+ 		MAX_STATEMENTS_DEFAULT,
+ 		100,
+ 		INT_MAX,
+ 		PGC_POSTMASTER,
+ 		0,
+ 		NULL,
+ 		NULL);
+ 
+ 	DefineCustomEnumVariable(
+ 		GUCNAME("track_statements"),
+ 		"Collects information about executed statements.",
+ 		NULL,
+ 		&track_statements,
+ 		PGSS_TRACK_NONE,
+ 		track_options,
+ 		PGC_SUSET,
+ 		0,
+ 		NULL,
+ 		NULL);
+ 
+ 	DefineCustomStringVariable(
+ 		GUCNAME("saved_file"),
+ 		"Writes statistic files to the specified path on shutdown.",
+ 		NULL,
+ 		&saved_file,
+ 		"global/pg_stat_statements.dump",
+ 		PGC_USERSET,
+ 		GUC_SUPERUSER_ONLY,
+ 		assign_saved_file,
+ 		NULL);
+ 
+ 	/* Request additonal shared resources. */
+ 	RequestAddinShmemSpace(pgss_memsize());
+ 	RequestAddinLWLocks(1);
+ 
+ 	/* Install hooks. */
+ 	prev_startup_hook = startup_hook;
+ 	startup_hook = pgss_startup;
+ 	prev_shutdown_hook = shutdown_hook;
+ 	shutdown_hook = pgss_shutdown;
+ 	prev_ExecutorStart = ExecutorStart_hook;
+ 	ExecutorStart_hook = pgss_ExecutorStart;
+ 	prev_ExecutorRun = ExecutorRun_hook;
+ 	ExecutorRun_hook = pgss_ExecutorRun;
+ 	prev_ExecutorEnd = ExecutorEnd_hook;
+ 	ExecutorEnd_hook = pgss_ExecutorEnd;
+ }
+ 
+ void
+ _PG_fini(void)
+ {
+ 	/* Uninstall hooks. */
+ 	ExecutorStart_hook = prev_ExecutorStart;
+ 	ExecutorRun_hook = prev_ExecutorRun;
+ 	ExecutorEnd_hook = prev_ExecutorEnd;
+ 	shutdown_hook = prev_shutdown_hook;
+ 	startup_hook = prev_startup_hook;
+ }
+ 
+ static uint32
+ pgss_tag(Oid userid, Oid dbid, const char *query)
+ {
+ 	return oid_hash(&userid, sizeof(Oid)) ^
+ 		   oid_hash(&dbid, sizeof(Oid)) ^
+ 		   DatumGetUInt32(hash_any((const unsigned char *) query,
+ 								   (int) strlen(query)));
+ }
+ 
+ static void
+ pgss_executed(const char *query, const Instrumentation *instr, uint32 rows)
+ {
+ 	volatile Entry *entry;
+ 	Oid				userid;
+ 	Oid				dbid;
+ 	uint32			tag;
+ 	long			gets;
+ 	long			reads;
+ 	double			usage;
+ 
+ 	Assert(query != NULL);
+ 
+ 	if (!track_statements)
+ 		return;
+ 	if (!pgss)
+ 		pgss_init();
+ 
+ 	userid = GetUserId();
+ 	dbid = MyDatabaseId;
+ 	tag = pgss_tag(userid, dbid, query);
+ 	gets = instr->buffer.shared_gets + instr->buffer.local_gets;
+ 	reads = gets - instr->buffer.shared_hits - instr->buffer.local_hits;
+ 	usage = USAGE_EXEC(duration);
+ 
+ 	LWLockAcquire(pgss->lock, LW_SHARED);
+ 
+ 	entry = hash_search(pgss_hash, &tag, HASH_FIND, NULL);
+ 	if (!entry)
+ 	{
+ 		/* Re-acquire exclusive lock to add a new entry. */
+ 		LWLockRelease(pgss->lock);
+ 		LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
+ 		entry = entry_alloc(tag, userid, dbid, query);
+ 	}
+ 
+ 	SpinLockAcquire(&entry->mutex);
+ 	entry->counters.calls += 1;
+ 	entry->counters.total_time += instr->total;
+ 	entry->counters.cpu_user += instr->utime;
+ 	entry->counters.cpu_sys += instr->stime;
+ 	entry->counters.gets += gets;
+ 	entry->counters.reads += reads;
+ 	entry->counters.lreads += instr->buffer.buffile_reads;
+ 	entry->counters.rows += rows;
+ 	entry->usage += usage;
+ 	SpinLockRelease(&entry->mutex);
+ 
+ 	LWLockRelease(pgss->lock);
+ }
+ 
+ void
+ pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
+ {
+ 	if (track_statements_enabled() && queryDesc->totaltime == NULL)
+ 		queryDesc->totaltime = InstrAlloc(1);
+ 
+ 	if (prev_ExecutorStart)
+ 		prev_ExecutorStart(queryDesc, eflags);
+ 	else
+ 		standard_ExecutorStart(queryDesc, eflags);
+ }
+ 
+ void
+ pgss_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count)
+ {
+ 	nested_level++;
+ 	PG_TRY();
+ 	{
+ 		if (prev_ExecutorRun)
+ 			prev_ExecutorRun(queryDesc, direction, count);
+ 		else
+ 			standard_ExecutorRun(queryDesc, direction, count);
+ 		nested_level--;
+ 	}
+ 	PG_CATCH();
+ 	{
+ 		nested_level--;
+ 		PG_RE_THROW();
+ 	}
+ 	PG_END_TRY();
+ }
+ 
+ 
+ void
+ pgss_ExecutorEnd(QueryDesc *queryDesc)
+ {
+ 	if (queryDesc->totaltime && track_statements_enabled())
+ 	{
+ 		/*
+ 		 * Make sure stats accumulation is done.  (Note: it's okay if
+ 		 * several levels of hook all do this.)
+ 		 */
+ 		InstrEndLoop(queryDesc->totaltime);
+ 
+ 		pgss_executed(queryDesc->sourceText,
+ 			queryDesc->totaltime,
+ 			queryDesc->estate->es_processed);
+ 	}
+ 
+ 	if (prev_ExecutorEnd)
+ 		prev_ExecutorEnd(queryDesc);
+ 	else
+ 		standard_ExecutorEnd(queryDesc);
+ 
+ 	/* Reset statistics if requested. */
+ 	if (reset_requested && nested_level == 0)
+ 	{
+ 		entry_reset();
+ 		reset_requested = false;
+ 	}
+ }
+ 
+ Datum
+ pg_stat_statements_reset(PG_FUNCTION_ARGS)
+ {
+ 	if (!pgss)
+ 		pgss_init();
+ 	reset_requested = true;
+ 	PG_RETURN_BOOL(true);
+ }
+ 
+ #define pg_stat_statements_cols		11
+ 
+ Datum
+ pg_stat_statements(PG_FUNCTION_ARGS)
+ {
+ 	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
+ 	TupleDesc			tupdesc;
+ 	Tuplestorestate    *tupstore;
+ 	MemoryContext		per_query_ctx;
+ 	MemoryContext		oldcontext;
+ 	Oid					userid = GetUserId();
+ 	bool				is_superuser = superuser();
+ 	HASH_SEQ_STATUS		hash_seq;
+ 	Entry			   *entry;
+ 
+ 	if (!pgss)
+ 		pgss_init();
+ 
+ 	/* check to see if caller supports us returning a tuplestore */
+ 	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ 				 errmsg("set-valued function called in context that cannot accept a set")));
+ 	if (!(rsinfo->allowedModes & SFRM_Materialize))
+ 		ereport(ERROR,
+ 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ 				 errmsg("materialize mode required, but it is not " \
+ 						"allowed in this context")));
+ 
+ 	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
+ 	oldcontext = MemoryContextSwitchTo(per_query_ctx);
+ 
+ 	tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
+ 	tupstore = tuplestore_begin_heap(true, false, work_mem);
+ 	rsinfo->returnMode = SFRM_Materialize;
+ 	rsinfo->setResult = tupstore;
+ 	rsinfo->setDesc = tupdesc;
+ 
+ 	LWLockAcquire(pgss->lock, LW_SHARED);
+ 
+ 	hash_seq_init(&hash_seq, pgss_hash);
+ 	while ((entry = hash_seq_search(&hash_seq)) != NULL)
+ 	{
+ 		Datum	values[pg_stat_statements_cols];
+ 		bool	nulls[pg_stat_statements_cols] = { 0 };
+ 		int		i = 0;
+ 
+ 		/* generate junk in short-term context */
+ 		MemoryContextSwitchTo(oldcontext);
+ 
+ 		values[i++] = ObjectIdGetDatum(entry->userid);
+ 		values[i++] = ObjectIdGetDatum(entry->dbid);
+ 
+ 		if (is_superuser || entry->userid == userid)
+ 			values[i++] = CStringGetTextDatum(entry->chunk->query);
+ 		else
+ 			values[i++] = CStringGetTextDatum("<insufficient privilege>");
+ 
+ 		SpinLockAcquire(&entry->mutex);
+ 		values[i++] = Int64GetDatumFast(entry->counters.calls);
+ 		values[i++] = Float8GetDatumFast(entry->counters.total_time);
+ 		values[i++] = Float8GetDatumFast(entry->counters.cpu_user);
+ 		values[i++] = Float8GetDatumFast(entry->counters.cpu_sys);
+ 		values[i++] = Int64GetDatumFast(entry->counters.gets);
+ 		values[i++] = Int64GetDatumFast(entry->counters.reads);
+ 		values[i++] = Int64GetDatumFast(entry->counters.lreads);
+ 		values[i++] = Int64GetDatumFast(entry->counters.rows);
+ 		SpinLockRelease(&entry->mutex);
+ 		Assert(i == pg_stat_statements_cols);
+ 
+ 		/* switch to appropriate context while storing the tuple */
+ 		MemoryContextSwitchTo(per_query_ctx);
+ 		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
+ 	}
+ 
+ 	LWLockRelease(pgss->lock);
+ 
+ 	/* clean up and return the tuplestore */
+ 	tuplestore_donestoring(tupstore);
+ 
+ 	MemoryContextSwitchTo(oldcontext);
+ 
+ 	return (Datum) 0;
+ }
+ 
+ static Size
+ pgss_memsize(void)
+ {
+ 	Size	size;
+ 
+ 	size = offsetof(pgStatStmt, chunks);
+ 	size = add_size(size, mul_size(max_statements, CHUNK_SIZE));
+ 	size = add_size(size, hash_estimate_size(max_statements, sizeof(Entry)));
+ 
+ 	return size;
+ }
+ 
+ static void
+ pgss_init(void)
+ {
+     bool		found;
+ 	Size		size;
+ 	HASHCTL		info = { 0 };
+ 
+ 	Assert(pgss == NULL);
+ 
+ 	size = pgss_memsize();
+ 
+ 	LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
+ 
+ 	pgss = ShmemInitStruct("pg_stat_statements", size, &found);
+ 	if (!pgss)
+ 		elog(ERROR, "out of shared memory");
+ 
+ 	if (!found)
+     {
+ 		pgss->lock = LWLockAssign();
+ 		pgss->num_statements = 0;
+ 		pgss->chunk_size = CHUNK_SIZE;
+ 		chunk_reset();
+ 	}
+ 
+ 	info.keysize = sizeof(uint32);
+ 	info.entrysize = sizeof(Entry);
+ 	info.hash = oid_hash;
+ 	pgss_hash = ShmemInitHash("pg_stat_statements hash",
+ 							  max_statements, max_statements,
+ 							  &info,
+ 							  HASH_ELEM | HASH_FUNCTION);
+ 	if (!pgss_hash)
+ 		elog(ERROR, "out of shared memory");
+ 
+ 	LWLockRelease(AddinShmemInitLock);
+ }
+ 
+ /*
+  * caller must be hold an exclusive lock on pgStateStmt->lock
+  */
+ static volatile Entry *
+ entry_alloc(uint32 tag, Oid userid, Oid dbid, const char *query)
+ {
+ 	bool	found;
+ 	Entry  *entry;
+ 
+ 	Assert(query != NULL);
+ 
+ 	while (pgss->num_statements >= max_statements)
+ 		entry_dealloc();
+ 
+ 	entry = hash_search(pgss_hash, &tag, HASH_ENTER, &found);
+ 
+ 	if (!found)
+ 	{
+ 		Size	len;
+ 
+ 		pgss->num_statements++;
+ 
+ 		entry->userid = userid;
+ 		entry->dbid = dbid;
+ 		memset(&entry->counters, 0, sizeof(Counters));
+ 		entry->usage = USAGE_INIT;
+ 
+ 		entry->chunk = chunk_alloc();
+ 		len = strlen(query);
+ 		len = pg_mbcliplen(query, len, pgss->chunk_size - 1);
+ 		memcpy(entry->chunk->query, query, len);
+ 		entry->chunk->query[len] = '\0';
+ 
+ 		SpinLockInit(&entry->mutex);
+ 	}
+ 
+ 	return entry;
+ }
+ 
+ /*
+  * Free least recently used entries.
+  * Caller must be hold an exclusive lock on pgStateStmt->lock.
+  */
+ static int
+ entry_cmp(const void *lhs, const void *rhs)
+ {
+ 	double	l_usage = (*(const Entry **)lhs)->usage;
+ 	double	r_usage = (*(const Entry **)rhs)->usage;
+ 
+ 	if (l_usage < r_usage)
+ 		return -1;
+ 	else if (l_usage > r_usage)
+ 		return +1;
+ 	else
+ 		return 0;
+ }
+ 
+ /*
+  * Deallocate least used entries.
+  */
+ static void
+ entry_dealloc(void)
+ {
+ 	HASH_SEQ_STATUS		hash_seq;
+ 	Entry			  **entries;
+ 	Entry			   *entry;
+ 	int					nvictims;
+ 	int					i;
+ 
+ 	/* Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them. */
+ 
+ 	entries = palloc(pgss->num_statements * sizeof(Entry *));
+ 
+ 	i = 0;
+ 	hash_seq_init(&hash_seq, pgss_hash);
+ 	while ((entry = hash_seq_search(&hash_seq)) != NULL)
+ 	{
+ 		entries[i++] = entry;
+ 		entry->usage *= USAGE_DECREASE_FACTOR;
+ 	}
+ 
+ 	qsort(entries, i, sizeof(Entry *), entry_cmp);
+ 	nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
+ 
+ 	for (i = 0; i < nvictims; i++)
+ 	{
+ 		chunk_free(entries[i]->chunk);
+ 		(void) SpinLockFree(&entries[i]->mutex);
+ 		hash_search(pgss_hash, &entries[i]->tag, HASH_REMOVE, NULL);
+ 		pgss->num_statements--;
+ 	}
+ 
+ 	pfree(entries);
+ }
+ 
+ static void
+ entry_reset(void)
+ {
+ 	HASH_SEQ_STATUS		hash_seq;
+ 	Entry			   *entry;
+ 
+ 	LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
+ 
+ 	hash_seq_init(&hash_seq, pgss_hash);
+ 	while ((entry = hash_seq_search(&hash_seq)) != NULL)
+ 	{
+ 		(void) SpinLockFree(&entry->mutex);
+ 		hash_search(pgss_hash, &entry->tag, HASH_REMOVE, NULL);
+ 	}
+ 
+ 	pgss->num_statements = 0;
+ 	chunk_reset();
+ 
+ 	LWLockRelease(pgss->lock);
+ }
+ 
+ static Chunk *
+ chunk_alloc(void)
+ {
+ 	Chunk *chunk;
+ 
+ 	Assert(pgss->free_chunks != NULL);
+ 
+ 	chunk = pgss->free_chunks;
+ 	pgss->free_chunks = pgss->free_chunks->next;
+ 	return chunk;
+ }
+ 
+ static void
+ chunk_free(Chunk *chunk)
+ {
+ 	Assert(chunk != NULL);
+ 
+ 	chunk->next = pgss->free_chunks;
+ 	pgss->free_chunks = chunk;
+ }
+ 
+ static void
+ chunk_reset(void)
+ {
+ 	Chunk  *chunk;
+ 	Chunk  *next;
+ 	int				i;
+ 
+ 	chunk = pgss->free_chunks = pgss->chunks;
+ 	for (i = 0; i < max_statements - 1; i++)
+ 	{
+ 		next = (Chunk *) ((char *)chunk + pgss->chunk_size);
+ 		chunk->next = next;
+ 		chunk = next;
+ 	}
+ 	chunk->next = NULL;
+ }
+ 
+ const char *
+ assign_saved_file(const char *newval, bool doit, GucSource source)
+ {
+ 	if (doit)
+ 	{
+ 		char *canon_val = strdup(newval);
+ 		if (canon_val == NULL)
+ 			ereport(ERROR,
+ 					(errcode(ERRCODE_OUT_OF_MEMORY),
+ 					 errmsg("out of memory")));
+ 		canonicalize_path(canon_val);
+ 		return canon_val;
+ 	}
+ 	else
+ 		return newval;
+ }
diff -cprN HEAD/contrib/pg_stat_statements/pg_stat_statements.sql.in pg_stat_statements/contrib/pg_stat_statements/pg_stat_statements.sql.in
*** HEAD/contrib/pg_stat_statements/pg_stat_statements.sql.in	Thu Jan  1 09:00:00 1970
--- pg_stat_statements/contrib/pg_stat_statements/pg_stat_statements.sql.in	Tue Dec  2 16:07:20 2008
***************
*** 0 ****
--- 1,36 ----
+ -- Adjust this setting to control where the objects get created.
+ SET search_path = public;
+ 
+ -- Register functions.
+ CREATE FUNCTION pg_stat_statements_reset()
+ RETURNS bool
+ AS 'MODULE_PATHNAME'
+ LANGUAGE C;
+ 
+ CREATE FUNCTION pg_stat_statements(
+     OUT userid oid,
+     OUT dbid oid,
+     OUT query text,
+     OUT calls int8,
+     OUT total_time float8,
+     OUT cpu_user float8,
+     OUT cpu_sys float8,
+     OUT gets int8,
+     OUT reads int8,
+     OUT local_reads int8,
+     OUT rows int8
+ )
+ RETURNS SETOF record
+ AS 'MODULE_PATHNAME'
+ LANGUAGE C;
+ 
+ -- Register a view.
+ CREATE VIEW pg_stat_statements AS
+     SELECT userid, dbid, query, calls,
+            (total_time * 1000)::int8 AS total_time,
+            ((cpu_user + cpu_sys) * 1000)::int8 AS cpu_time,
+            gets, reads, local_reads, rows
+       FROM pg_stat_statements();
+ 
+ -- Don't want these to be available at public.
+ REVOKE ALL ON FUNCTION pg_stat_statements_reset() FROM PUBLIC;
diff -cprN HEAD/contrib/pg_stat_statements/uninstall_pg_stat_statements.sql pg_stat_statements/contrib/pg_stat_statements/uninstall_pg_stat_statements.sql
*** HEAD/contrib/pg_stat_statements/uninstall_pg_stat_statements.sql	Thu Jan  1 09:00:00 1970
--- pg_stat_statements/contrib/pg_stat_statements/uninstall_pg_stat_statements.sql	Mon Jul 14 18:03:04 2008
***************
*** 0 ****
--- 1,6 ----
+ -- Adjust this setting to control where the objects get dropped.
+ SET search_path = public;
+ 
+ DROP VIEW pg_stat_statements;
+ DROP FUNCTION pg_stat_statements();
+ DROP FUNCTION pg_stat_statements_reset();
diff -cprN HEAD/doc/src/sgml/contrib.sgml pg_stat_statements/doc/src/sgml/contrib.sgml
*** HEAD/doc/src/sgml/contrib.sgml	Sat Nov 22 11:15:56 2008
--- pg_stat_statements/doc/src/sgml/contrib.sgml	Fri Dec 12 18:26:03 2008
*************** psql -d dbname -f <replaceable>SHAREDIR<
*** 103,108 ****
--- 103,109 ----
   &pgfreespacemap;
   &pgrowlocks;
   &pgstandby;
+  &pgstatstatements;
   &pgstattuple;
   &pgtrgm;
   &seg;
diff -cprN HEAD/doc/src/sgml/filelist.sgml pg_stat_statements/doc/src/sgml/filelist.sgml
*** HEAD/doc/src/sgml/filelist.sgml	Sat Nov 22 11:15:56 2008
--- pg_stat_statements/doc/src/sgml/filelist.sgml	Fri Dec 12 18:26:03 2008
***************
*** 116,121 ****
--- 116,122 ----
  <!entity pgfreespacemap  SYSTEM "pgfreespacemap.sgml">
  <!entity pgrowlocks      SYSTEM "pgrowlocks.sgml">
  <!entity pgstandby       SYSTEM "pgstandby.sgml">
+ <!entity pgstatstatements SYSTEM "pgstatstatements.sgml">
  <!entity pgstattuple     SYSTEM "pgstattuple.sgml">
  <!entity pgtrgm          SYSTEM "pgtrgm.sgml">
  <!entity seg             SYSTEM "seg.sgml">
diff -cprN HEAD/doc/src/sgml/pgstatstatements.sgml pg_stat_statements/doc/src/sgml/pgstatstatements.sgml
*** HEAD/doc/src/sgml/pgstatstatements.sgml	Thu Jan  1 09:00:00 1970
--- pg_stat_statements/doc/src/sgml/pgstatstatements.sgml	Mon Dec  8 11:48:40 2008
***************
*** 0 ****
--- 1,281 ----
+ <sect1 id="pgstatstatements">
+  <title>pg_stat_statements</title>
+ 
+  <indexterm zone="pgstatstatements">
+   <primary>pg_stat_statements</primary>
+  </indexterm>
+ 
+  <para>
+   The <filename>pg_stat_statements</filename> module provides a means for
+   tracing and analyzing SQL statements executed in a server.
+  </para>
+ 
+  <para>
+   The module should be loaded through <varname>shared_preload_libraries</>
+   because it requires additional shared memory. You might need to restart
+   servers to enable the module.
+  </para>
+ 
+  <para>
+   NOTE: It'd be better to to execute statements using prepared statements
+   or extended protocol if you want to get a better report from the module.
+   If simple protocol is used, statements that have differences only in the
+   query parameters are not grouped in the report.
+  </para>
+ 
+  <sect2>
+   <title>The <structname>pg_stat_statements</structname> view</title>
+ 
+   <para>
+    The definitions of the columns exposed by the view are:
+   </para>
+ 
+   <table>
+    <title><structname>pg_stat_statements</> columns</title>
+ 
+    <tgroup cols="4">
+     <thead>
+      <row>
+       <entry>Name</entry>
+       <entry>Type</entry>
+       <entry>References</entry>
+       <entry>Description</entry>
+      </row>
+     </thead>
+     <tbody>
+      <row>
+       <entry><structfield>userid</structfield></entry>
+       <entry><type>oid</type></entry>
+       <entry>pg_authid.oid</entry>
+       <entry>User who executed the statement</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>dbid</structfield></entry>
+       <entry><type>oid</type></entry>
+       <entry><literal>pg_class.oid</literal></entry>
+       <entry>Database in which the statement is executed</entry>
+      </row>
+ 
+     <row>
+       <entry><structfield>query</structfield></entry>
+       <entry><type>text</type></entry>
+       <entry></entry>
+       <entry>Query text of the statement</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>calls</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Number of times executed</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>total_time</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Total time spent for the statement in milliseconds</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>cpu_time</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>CPU time spent for the statement in milliseconds</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>gets</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Total buffer gets during execution</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>reads</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Total buffer reads during execution</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>local_reads</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Total direct reads during execution, for example disk sorting and materializing</entry>
+      </row>
+ 
+      <row>
+       <entry><structfield>rows</structfield></entry>
+       <entry><type>bigint</type></entry>
+       <entry></entry>
+       <entry>Number of rows retrieved or affected by the statement</entry>
+      </row>
+ 
+     </tbody>
+    </tgroup>
+   </table>
+ 
+   <para>
+    There is one row for each statement. Statements are grouped when they have
+    same SQL text, are in the same database, and are executed by the same user.
+   </para>
+ 
+   <para>
+    Because of security restriction, non-super users cannot see query strings
+    executed by other users.
+   </para>
+  </sect2>
+ 
+  <sect2>
+   <title>Functions</title>
+ 
+   <variablelist>
+    <varlistentry>
+     <term>
+      <function>pg_stat_statements_reset() returns bool</function>
+     </term>
+ 
+     <listitem>
+      <para>
+       <function>pg_stat_statements_reset</function> resets all of statement
+       statistics. <structname>pg_stat_statements</> view will be empty.
+      </para>
+     </listitem>
+    </varlistentry>
+ 
+   </variablelist>
+  </sect2>
+ 
+  <sect2>
+   <title>Configuration parameters</title>
+ 
+   <variablelist>
+    <varlistentry>
+     <term>
+      <varname>statistics.max_statements (<type>integer</type>)</varname>
+     </term>
+ 
+     <listitem>
+      <para>
+       <varname>statistics.max_statements</varname> is the maximum number of
+       statements tracked by the module. If variations of statements are larger
+       than the value, statistics of the least used statement is discarded.
+       The default value is 1000. The module requires addional shared memory
+       about <varname>statistics.max_statements</varname> * <varname>track_activity_query_size</varname>.
+       This parameter can only be set at server start.
+      </para>
+     </listitem>
+    </varlistentry>
+ 
+    <varlistentry>
+     <term>
+      <varname>statistics.track_statements (<type>string</type>)</varname>
+     </term>
+ 
+     <listitem>
+      <para>
+       <varname>statistics.track_statements</varname> enables collection of
+       statement statistics by the module. Specify top to count only top-level
+       statements, all to also track nested statements, and none to disable.
+       The default value is none.
+       Only superusers can change this setting.
+      </para>
+      <para>
+       NOTE: Shared memory allocated by the module is not released even if
+       statistics collection is disabled.
+      </para>
+     </listitem>
+    </varlistentry>
+ 
+    <varlistentry>
+     <term>
+      <varname>statistics.saved_file (<type>string</type>)</varname>
+     </term>
+ 
+     <listitem>
+      <para>
+       <varname>statistics.saved_file</varname> specifies the name of saved file
+       where the statement statistics are loaded or dumped. The default value is
+       'global/pg_stat_statements.dump'. If the value is an empty string,
+       statistics are neither loaded nor dumped. This parameter can only be set
+       in the postgresql.conf file or on the server command line.
+      </para>
+     </listitem>
+    </varlistentry>
+   </variablelist>
+ 
+   <para>
+    If you set the above configuration parameters, you also need to
+    add 'statistics' entry to <varname>custom_variable_classes</varname>.
+   </para>
+ 
+   <programlisting>
+   # postgresql.conf
+   shared_preload_libraries = 'pg_stat_statements'
+   
+   custom_variable_classes = 'statistics'
+   #statistics.max_statements = 1000
+   #statistics.track_statements = top
+   #statistics.saved_file = 'global/pg_stat_statements.dump'
+   </programlisting>
+  </sect2>
+ 
+  <sect2>
+   <title>Sample output</title>
+ 
+   <programlisting>
+   $ pgbench -i
+ 
+   postgres=# SELECT pg_stat_statements_reset();
+ 
+   $ pgbench -c10 -t300 -M prepared
+   
+   postgres=# \x
+   postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
+   -[ RECORD 1 ]+-------------------------------------------------------------
+   userid       | 10
+   dbid         | 16384
+   query        | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
+   calls        | 3000
+   total_time   | 34683
+   cpu_time     | 1843
+   gets         | 48166
+   reads        | 12
+   local_reads  | 0
+   rows         | 3000
+   -[ RECORD 2 ]+-------------------------------------------------------------
+   userid       | 10
+   dbid         | 16384
+   query        | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
+   calls        | 3000
+   total_time   | 34611
+   cpu_time     | 593
+   gets         | 26447
+   reads        | 7
+   local_reads  | 0
+   rows         | 3000
+   -[ RECORD 3 ]+-------------------------------------------------------------
+   userid       | 10
+   dbid         | 16384
+   query        | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
+   calls        | 3000
+   total_time   | 546
+   cpu_time     | 359
+   gets         | 18025
+   reads        | 274
+   local_reads  | 0
+   rows         | 3000
+   </programlisting>
+  </sect2>
+ 
+  <sect2>
+   <title>Authors</title>
+ 
+   <para>
+    Takahiro Itagaki <email>itagaki.takahiro@oss.ntt.co.jp</email>
+   </para>
+  </sect2>
+ 
+ </sect1>
