prepare.c 10.2 KB
Newer Older
1 2 3 4 5 6 7 8
/*-------------------------------------------------------------------------
 *
 * prepare.c
 *	  Prepareable SQL statements via PREPARE, EXECUTE and DEALLOCATE
 *
 * Copyright (c) 2002, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
9
 *	  $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.4 2002/09/20 03:45:08 momjian Exp $
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "commands/prepare.h"
#include "executor/executor.h"
#include "utils/guc.h"
#include "optimizer/planner.h"
#include "rewrite/rewriteHandler.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"


#define HASH_KEY_LEN NAMEDATALEN

/* All the data we need to remember about a stored query */
typedef struct
{
	/* dynahash.c requires key to be first field */
	char		key[HASH_KEY_LEN];
	List	   *query_list;		/* list of queries */
	List	   *plan_list;		/* list of plans */
	List	   *argtype_list;	/* list of parameter type OIDs */
Bruce Momjian's avatar
Bruce Momjian committed
37
	MemoryContext context;		/* context containing this query */
38 39 40 41 42 43 44 45 46 47 48 49
} QueryHashEntry;

/*
 * The hash table in which prepared queries are stored. This is
 * per-backend: query plans are not shared between backends.
 * The keys for this hash table are the arguments to PREPARE
 * and EXECUTE ("plan names"); the entries are QueryHashEntry structs.
 */
static HTAB *prepared_queries = NULL;

static void InitQueryHashTable(void);
static void StoreQuery(const char *stmt_name, List *query_list,
Bruce Momjian's avatar
Bruce Momjian committed
50
		   List *plan_list, List *argtype_list);
51 52 53 54 55 56 57 58 59 60
static QueryHashEntry *FetchQuery(const char *plan_name);
static void RunQuery(QueryDesc *qdesc, EState *state);


/*
 * Implements the 'PREPARE' utility statement.
 */
void
PrepareQuery(PrepareStmt *stmt)
{
Bruce Momjian's avatar
Bruce Momjian committed
61 62 63
	List	   *plan_list = NIL;
	List	   *query_list,
			   *query_list_item;
64 65 66 67 68 69 70 71 72 73 74 75

	if (!stmt->name)
		elog(ERROR, "No statement name given");

	if (stmt->query->commandType == CMD_UTILITY)
		elog(ERROR, "Utility statements cannot be prepared");

	/* Rewrite the query. The result could be 0, 1, or many queries. */
	query_list = QueryRewrite(stmt->query);

	foreach(query_list_item, query_list)
	{
Bruce Momjian's avatar
Bruce Momjian committed
76 77
		Query	   *query = (Query *) lfirst(query_list_item);
		Plan	   *plan;
78

79
		plan = pg_plan_query(query);
80 81 82 83 84 85 86 87 88 89 90 91 92

		plan_list = lappend(plan_list, plan);
	}

	StoreQuery(stmt->name, query_list, plan_list, stmt->argtype_oids);
}

/*
 * Implements the 'EXECUTE' utility statement.
 */
void
ExecuteQuery(ExecuteStmt *stmt, CommandDest outputDest)
{
Bruce Momjian's avatar
Bruce Momjian committed
93 94 95 96
	QueryHashEntry *entry;
	List	   *l,
			   *query_list,
			   *plan_list;
97 98 99 100 101 102 103 104 105 106 107 108 109 110
	ParamListInfo paramLI = NULL;

	/* Look it up in the hash table */
	entry = FetchQuery(stmt->name);

	/* Make working copies the executor can safely scribble on */
	query_list = (List *) copyObject(entry->query_list);
	plan_list = (List *) copyObject(entry->plan_list);

	Assert(length(query_list) == length(plan_list));

	/* Evaluate parameters, if any */
	if (entry->argtype_list != NIL)
	{
Bruce Momjian's avatar
Bruce Momjian committed
111 112
		int			nargs = length(entry->argtype_list);
		int			i = 0;
113 114 115 116 117 118 119 120 121
		ExprContext *econtext = MakeExprContext(NULL, CurrentMemoryContext);

		/* Parser should have caught this error, but check */
		if (nargs != length(stmt->params))
			elog(ERROR, "ExecuteQuery: wrong number of arguments");

		paramLI = (ParamListInfo) palloc((nargs + 1) * sizeof(ParamListInfoData));
		MemSet(paramLI, 0, (nargs + 1) * sizeof(ParamListInfoData));

Bruce Momjian's avatar
Bruce Momjian committed
122
		foreach(l, stmt->params)
123
		{
Bruce Momjian's avatar
Bruce Momjian committed
124 125
			Node	   *n = lfirst(l);
			bool		isNull;
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

			paramLI[i].value = ExecEvalExprSwitchContext(n,
														 econtext,
														 &isNull,
														 NULL);
			paramLI[i].kind = PARAM_NUM;
			paramLI[i].id = i + 1;
			paramLI[i].isnull = isNull;

			i++;
		}
		paramLI[i].kind = PARAM_INVALID;
	}

	/* Execute each query */
	foreach(l, query_list)
	{
Bruce Momjian's avatar
Bruce Momjian committed
143 144 145
		Query	   *query = lfirst(l);
		Plan	   *plan = lfirst(plan_list);
		bool		is_last_query;
146 147 148 149 150 151 152 153

		plan_list = lnext(plan_list);
		is_last_query = (plan_list == NIL);

		if (query->commandType == CMD_UTILITY)
			ProcessUtility(query->utilityStmt, outputDest, NULL);
		else
		{
Bruce Momjian's avatar
Bruce Momjian committed
154 155
			QueryDesc  *qdesc;
			EState	   *state;
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

			if (Show_executor_stats)
				ResetUsage();

			qdesc = CreateQueryDesc(query, plan, outputDest, NULL);
			state = CreateExecutorState();

			state->es_param_list_info = paramLI;

			if (stmt->into)
			{
				if (qdesc->operation != CMD_SELECT)
					elog(ERROR, "INTO clause specified for non-SELECT query");

				query->into = stmt->into;
				qdesc->dest = None;
			}

			RunQuery(qdesc, state);

			if (Show_executor_stats)
				ShowUsage("EXECUTOR STATISTICS");
		}

		/*
Bruce Momjian's avatar
Bruce Momjian committed
181 182 183
		 * If we're processing multiple queries, we need to increment the
		 * command counter between them. For the last query, there's no
		 * need to do this, it's done automatically.
184
		 */
Bruce Momjian's avatar
Bruce Momjian committed
185
		if (!is_last_query)
186 187 188 189 190 191 192 193 194 195 196 197
			CommandCounterIncrement();
	}

	/* No need to pfree memory, MemoryContext will be reset */
}

/*
 * Initialize query hash table upon first use.
 */
static void
InitQueryHashTable(void)
{
Bruce Momjian's avatar
Bruce Momjian committed
198
	HASHCTL		hash_ctl;
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

	MemSet(&hash_ctl, 0, sizeof(hash_ctl));

	hash_ctl.keysize = HASH_KEY_LEN;
	hash_ctl.entrysize = sizeof(QueryHashEntry);

	prepared_queries = hash_create("Prepared Queries",
								   32,
								   &hash_ctl,
								   HASH_ELEM);

	if (!prepared_queries)
		elog(ERROR, "InitQueryHashTable: unable to create hash table");
}

/*
 * Store all the data pertaining to a query in the hash table using
 * the specified key. A copy of the data is made in a memory context belonging
 * to the hash entry, so the caller can dispose of their copy.
 */
static void
StoreQuery(const char *stmt_name, List *query_list, List *plan_list,
		   List *argtype_list)
{
	QueryHashEntry *entry;
	MemoryContext oldcxt,
Bruce Momjian's avatar
Bruce Momjian committed
225 226 227
				entrycxt;
	char		key[HASH_KEY_LEN];
	bool		found;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

	/* Initialize the hash table, if necessary */
	if (!prepared_queries)
		InitQueryHashTable();

	/* Check for pre-existing entry of same name */
	/* See notes in FetchQuery */
	MemSet(key, 0, sizeof(key));
	strncpy(key, stmt_name, sizeof(key));

	hash_search(prepared_queries, key, HASH_FIND, &found);

	if (found)
		elog(ERROR, "Prepared statement with name \"%s\" already exists",
			 stmt_name);

Tom Lane's avatar
Tom Lane committed
244
	/* Make a permanent memory context for the hashtable entry */
245 246 247 248 249 250 251 252 253
	entrycxt = AllocSetContextCreate(TopMemoryContext,
									 stmt_name,
									 1024,
									 1024,
									 ALLOCSET_DEFAULT_MAXSIZE);

	oldcxt = MemoryContextSwitchTo(entrycxt);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
254 255 256 257
	 * We need to copy the data so that it is stored in the correct memory
	 * context.  Do this before making hashtable entry, so that an
	 * out-of-memory failure only wastes memory and doesn't leave us with
	 * an incomplete (ie corrupt) hashtable entry.
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
	 */
	query_list = (List *) copyObject(query_list);
	plan_list = (List *) copyObject(plan_list);
	argtype_list = listCopy(argtype_list);

	/* Now we can add entry to hash table */
	entry = (QueryHashEntry *) hash_search(prepared_queries,
										   key,
										   HASH_ENTER,
										   &found);

	/* Shouldn't get a failure, nor duplicate entry */
	if (!entry || found)
		elog(ERROR, "Unable to store prepared statement \"%s\"!",
			 stmt_name);

	/* Fill in the hash table entry with copied data */
	entry->query_list = query_list;
	entry->plan_list = plan_list;
	entry->argtype_list = argtype_list;
	entry->context = entrycxt;

	MemoryContextSwitchTo(oldcxt);
}

/*
 * Lookup an existing query in the hash table.
 */
static QueryHashEntry *
FetchQuery(const char *plan_name)
{
Bruce Momjian's avatar
Bruce Momjian committed
289
	char		key[HASH_KEY_LEN];
290 291 292 293 294 295 296 297 298 299 300 301
	QueryHashEntry *entry;

	/*
	 * If the hash table hasn't been initialized, it can't be storing
	 * anything, therefore it couldn't possibly store our plan.
	 */
	if (!prepared_queries)
		elog(ERROR, "Prepared statement with name \"%s\" does not exist",
			 plan_name);

	/*
	 * We can't just use the statement name as supplied by the user: the
Bruce Momjian's avatar
Bruce Momjian committed
302 303
	 * hash package is picky enough that it needs to be NULL-padded out to
	 * the appropriate length to work correctly.
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
	 */
	MemSet(key, 0, sizeof(key));
	strncpy(key, plan_name, sizeof(key));

	entry = (QueryHashEntry *) hash_search(prepared_queries,
										   key,
										   HASH_FIND,
										   NULL);

	if (!entry)
		elog(ERROR, "Prepared statement with name \"%s\" does not exist",
			 plan_name);

	return entry;
}

/*
 * Given a plan name, look up the stored plan (giving error if not found).
 * If found, return the list of argument type OIDs.
 */
List *
FetchQueryParams(const char *plan_name)
{
	QueryHashEntry *entry;

	entry = FetchQuery(plan_name);

	return entry->argtype_list;
}

/*
 * Actually execute a prepared query.
 */
static void
RunQuery(QueryDesc *qdesc, EState *state)
{
Bruce Momjian's avatar
Bruce Momjian committed
340
	TupleDesc	tupdesc;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

	tupdesc = ExecutorStart(qdesc, state);

	ExecutorRun(qdesc, state, state->es_direction, 0L);

	ExecutorEnd(qdesc, state);
}

/*
 * Implements the 'DEALLOCATE' utility statement: deletes the
 * specified plan from storage.
 *
 * The initial part of this routine is identical to FetchQuery(),
 * but we repeat the coding because we need to use the key twice.
 */
void
DeallocateQuery(DeallocateStmt *stmt)
{
Bruce Momjian's avatar
Bruce Momjian committed
359
	char		key[HASH_KEY_LEN];
360 361 362 363 364 365 366 367 368 369 370 371
	QueryHashEntry *entry;

	/*
	 * If the hash table hasn't been initialized, it can't be storing
	 * anything, therefore it couldn't possibly store our plan.
	 */
	if (!prepared_queries)
		elog(ERROR, "Prepared statement with name \"%s\" does not exist",
			 stmt->name);

	/*
	 * We can't just use the statement name as supplied by the user: the
Bruce Momjian's avatar
Bruce Momjian committed
372 373
	 * hash package is picky enough that it needs to be NULL-padded out to
	 * the appropriate length to work correctly.
374 375 376 377 378 379
	 */
	MemSet(key, 0, sizeof(key));
	strncpy(key, stmt->name, sizeof(key));

	/*
	 * First lookup the entry, so we can release all the subsidiary memory
Bruce Momjian's avatar
Bruce Momjian committed
380 381 382 383
	 * it has allocated (when it's removed, hash_search() will return a
	 * dangling pointer, so it needs to be done prior to HASH_REMOVE).
	 * This requires an extra hash-table lookup, but DEALLOCATE isn't
	 * exactly a performance bottleneck.
384 385 386 387 388 389 390 391 392 393 394
	 */
	entry = (QueryHashEntry *) hash_search(prepared_queries,
										   key,
										   HASH_FIND,
										   NULL);

	if (!entry)
		elog(ERROR, "Prepared statement with name \"%s\" does not exist",
			 stmt->name);

	/* Flush the context holding the subsidiary data */
Tom Lane's avatar
Tom Lane committed
395 396
	Assert(MemoryContextIsValid(entry->context));
	MemoryContextDelete(entry->context);
397 398 399 400

	/* Now we can remove the hash table entry */
	hash_search(prepared_queries, key, HASH_REMOVE, NULL);
}