prepare.c 10.4 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
B
Bruce Momjian 已提交
9
 *	  $Header: /cvsroot/pgsql/src/backend/commands/prepare.c,v 1.2 2002/09/04 20:31:15 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 */
B
Bruce Momjian 已提交
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,
B
Bruce Momjian 已提交
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)
{
B
Bruce Momjian 已提交
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)
	{
B
Bruce Momjian 已提交
76 77
		Query	   *query = (Query *) lfirst(query_list_item);
		Plan	   *plan;
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

		/* We can't generate plans for utility statements. */
		if (query->commandType == CMD_UTILITY)
			plan = NULL;
		else
		{
			/* Call the query planner to generate a plan. */
			plan = planner(query);
		}

		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)
{
B
Bruce Momjian 已提交
100 101 102 103
	QueryHashEntry *entry;
	List	   *l,
			   *query_list,
			   *plan_list;
104 105 106 107 108 109 110 111 112 113 114 115 116 117
	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)
	{
B
Bruce Momjian 已提交
118 119
		int			nargs = length(entry->argtype_list);
		int			i = 0;
120 121 122 123 124 125 126 127 128
		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));

B
Bruce Momjian 已提交
129
		foreach(l, stmt->params)
130
		{
B
Bruce Momjian 已提交
131 132
			Node	   *n = lfirst(l);
			bool		isNull;
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

			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)
	{
B
Bruce Momjian 已提交
150 151 152
		Query	   *query = lfirst(l);
		Plan	   *plan = lfirst(plan_list);
		bool		is_last_query;
153 154 155 156 157 158 159 160

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

		if (query->commandType == CMD_UTILITY)
			ProcessUtility(query->utilityStmt, outputDest, NULL);
		else
		{
B
Bruce Momjian 已提交
161 162
			QueryDesc  *qdesc;
			EState	   *state;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

			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");
		}

		/*
B
Bruce Momjian 已提交
188 189 190
		 * 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.
191
		 */
B
Bruce Momjian 已提交
192
		if (!is_last_query)
193 194 195 196 197 198 199 200 201 202 203 204
			CommandCounterIncrement();
	}

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

/*
 * Initialize query hash table upon first use.
 */
static void
InitQueryHashTable(void)
{
B
Bruce Momjian 已提交
205
	HASHCTL		hash_ctl;
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

	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,
B
Bruce Momjian 已提交
232 233 234
				entrycxt;
	char		key[HASH_KEY_LEN];
	bool		found;
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

	/* 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);

	/* Okay. Make a permanent memory context for the hashtable entry */
	entrycxt = AllocSetContextCreate(TopMemoryContext,
									 stmt_name,
									 1024,
									 1024,
									 ALLOCSET_DEFAULT_MAXSIZE);

	oldcxt = MemoryContextSwitchTo(entrycxt);

	/*
B
Bruce Momjian 已提交
261 262 263 264
	 * 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.
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	 */
	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)
{
B
Bruce Momjian 已提交
296
	char		key[HASH_KEY_LEN];
297 298 299 300 301 302 303 304 305 306 307 308
	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
B
Bruce Momjian 已提交
309 310
	 * hash package is picky enough that it needs to be NULL-padded out to
	 * the appropriate length to work correctly.
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 340 341 342 343 344 345 346
	 */
	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)
{
B
Bruce Momjian 已提交
347
	TupleDesc	tupdesc;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365

	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)
{
B
Bruce Momjian 已提交
366
	char		key[HASH_KEY_LEN];
367 368 369 370 371 372 373 374 375 376 377 378
	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
B
Bruce Momjian 已提交
379 380
	 * hash package is picky enough that it needs to be NULL-padded out to
	 * the appropriate length to work correctly.
381 382 383 384 385 386
	 */
	MemSet(key, 0, sizeof(key));
	strncpy(key, stmt->name, sizeof(key));

	/*
	 * First lookup the entry, so we can release all the subsidiary memory
B
Bruce Momjian 已提交
387 388 389 390
	 * 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.
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
	 */
	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 */
	if (MemoryContextIsValid(entry->context))
		MemoryContextDelete(entry->context);

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