pl_exec.c
来自「postgresql8.3.4源码,开源数据库」· C语言 代码 · 共 2,523 行 · 第 1/5 页
C
2,523 行
/*------------------------------------------------------------------------- * * pl_exec.c - Executor for the PL/pgSQL * procedural language * * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.202.2.1 2008/09/01 22:30:40 tgl Exp $ * *------------------------------------------------------------------------- */#include "plpgsql.h"#include "pl.tab.h"#include <ctype.h>#include "access/heapam.h"#include "access/transam.h"#include "catalog/pg_proc.h"#include "catalog/pg_type.h"#include "executor/spi_priv.h"#include "funcapi.h"#include "optimizer/clauses.h"#include "parser/parse_expr.h"#include "parser/scansup.h"#include "tcop/tcopprot.h"#include "utils/array.h"#include "utils/builtins.h"#include "utils/lsyscache.h"#include "utils/memutils.h"#include "utils/typcache.h"static const char *const raise_skip_msg = "RAISE";/* * All plpgsql function executions within a single transaction share the same * executor EState for evaluating "simple" expressions. Each function call * creates its own "eval_econtext" ExprContext within this estate for * per-evaluation workspace. eval_econtext is freed at normal function exit, * and the EState is freed at transaction end (in case of error, we assume * that the abort mechanisms clean it all up). In order to be sure * ExprContext callbacks are handled properly, each subtransaction has to have * its own such EState; hence we need a stack. We use a simple counter to * distinguish different instantiations of the EState, so that we can tell * whether we have a current copy of a prepared expression. * * This arrangement is a bit tedious to maintain, but it's worth the trouble * so that we don't have to re-prepare simple expressions on each trip through * a function. (We assume the case to optimize is many repetitions of a * function within a transaction.) */typedef struct SimpleEstateStackEntry{ EState *xact_eval_estate; /* EState for current xact level */ long int xact_estate_simple_id; /* ID for xact_eval_estate */ SubTransactionId xact_subxid; /* ID for current subxact */ struct SimpleEstateStackEntry *next; /* next stack entry up */} SimpleEstateStackEntry;static SimpleEstateStackEntry *simple_estate_stack = NULL;static long int simple_estate_id_counter = 0;/************************************************************ * Local function forward declarations ************************************************************/static void plpgsql_exec_error_callback(void *arg);static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);static int exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block);static int exec_stmts(PLpgSQL_execstate *estate, List *stmts);static int exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);static int exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt);static int exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt);static int exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt);static int exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt);static int exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt);static int exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt);static int exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt);static int exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt);static int exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt);static int exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt);static int exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt);static int exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt);static int exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt);static int exec_stmt_return_next(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_next *stmt);static int exec_stmt_return_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_query *stmt);static int exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt);static int exec_stmt_execsql(PLpgSQL_execstate *estate, PLpgSQL_stmt_execsql *stmt);static int exec_stmt_dynexecute(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynexecute *stmt);static int exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt);static void plpgsql_estate_setup(PLpgSQL_execstate *estate, PLpgSQL_function *func, ReturnSetInfo *rsi);static void exec_eval_cleanup(PLpgSQL_execstate *estate);static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions);static bool exec_simple_check_node(Node *node);static void exec_simple_check_plan(PLpgSQL_expr *expr);static bool exec_eval_simple_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, Datum *result, bool *isNull, Oid *rettype);static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr);static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, Oid valtype, bool *isNull);static void exec_eval_datum(PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid expectedtypeid, Oid *typeid, Datum *value, bool *isnull);static int exec_eval_integer(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull);static bool exec_eval_boolean(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull);static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype);static int exec_run_select(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, long maxtuples, Portal *portalP);static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, PLpgSQL_row *row, HeapTuple tup, TupleDesc tupdesc);static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate, PLpgSQL_row *row, TupleDesc tupdesc);static char *convert_value_to_string(Datum value, Oid valtype);static Datum exec_cast_value(Datum value, Oid valtype, Oid reqtype, FmgrInfo *reqinput, Oid reqtypioparam, int32 reqtypmod, bool isnull);static Datum exec_simple_cast_value(Datum value, Oid valtype, Oid reqtype, int32 reqtypmod, bool isnull);static void exec_init_tuple_store(PLpgSQL_execstate *estate);static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);static void exec_set_found(PLpgSQL_execstate *estate, bool state);static void plpgsql_create_econtext(PLpgSQL_execstate *estate);static void free_var(PLpgSQL_var *var);/* ---------- * plpgsql_exec_function Called by the call handler for * function execution. * ---------- */Datumplpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo){ PLpgSQL_execstate estate; ErrorContextCallback plerrcontext; int i; int rc; /* * Setup the execution state */ plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo); /* * Setup error traceback support for ereport() */ plerrcontext.callback = plpgsql_exec_error_callback; plerrcontext.arg = &estate; plerrcontext.previous = error_context_stack; error_context_stack = &plerrcontext; /* * Make local execution copies of all the datums */ estate.err_text = gettext_noop("during initialization of execution state"); for (i = 0; i < estate.ndatums; i++) estate.datums[i] = copy_plpgsql_datum(func->datums[i]); /* * Store the actual call argument values into the appropriate variables */ estate.err_text = gettext_noop("while storing call arguments into local variables"); for (i = 0; i < func->fn_nargs; i++) { int n = func->fn_argvarnos[i]; switch (estate.datums[n]->dtype) { case PLPGSQL_DTYPE_VAR: { PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n]; var->value = fcinfo->arg[i]; var->isnull = fcinfo->argnull[i]; var->freeval = false; } break; case PLPGSQL_DTYPE_ROW: { PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n]; if (!fcinfo->argnull[i]) { HeapTupleHeader td; Oid tupType; int32 tupTypmod; TupleDesc tupdesc; HeapTupleData tmptup; td = DatumGetHeapTupleHeader(fcinfo->arg[i]); /* Extract rowtype info and find a tupdesc */ tupType = HeapTupleHeaderGetTypeId(td); tupTypmod = HeapTupleHeaderGetTypMod(td); tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod); /* Build a temporary HeapTuple control structure */ tmptup.t_len = HeapTupleHeaderGetDatumLength(td); ItemPointerSetInvalid(&(tmptup.t_self)); tmptup.t_tableOid = InvalidOid; tmptup.t_data = td; exec_move_row(&estate, NULL, row, &tmptup, tupdesc); ReleaseTupleDesc(tupdesc); } else { /* If arg is null, treat it as an empty row */ exec_move_row(&estate, NULL, row, NULL, NULL); } } break; default: elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype); } } estate.err_text = gettext_noop("during function entry"); /* * Set the magic variable FOUND to false */ exec_set_found(&estate, false); /* * Let the instrumentation plugin peek at this function */ if (*plugin_ptr && (*plugin_ptr)->func_beg) ((*plugin_ptr)->func_beg) (&estate, func); /* * Now call the toplevel block of statements */ estate.err_text = NULL; estate.err_stmt = (PLpgSQL_stmt *) (func->action); rc = exec_stmt_block(&estate, func->action); if (rc != PLPGSQL_RC_RETURN) { estate.err_stmt = NULL; estate.err_text = NULL; /* * Provide a more helpful message if a CONTINUE has been used outside * a loop. */ if (rc == PLPGSQL_RC_CONTINUE) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("CONTINUE cannot be used outside a loop"))); else ereport(ERROR, (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT), errmsg("control reached end of function without RETURN"))); } /* * We got a return value - process it */ estate.err_stmt = NULL; estate.err_text = gettext_noop("while casting return value to function's return type"); fcinfo->isnull = estate.retisnull; if (estate.retisset) { ReturnSetInfo *rsi = estate.rsi; /* Check caller can handle a set result */ if (!rsi || !IsA(rsi, ReturnSetInfo) || (rsi->allowedModes & SFRM_Materialize) == 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("set-valued function called in context that cannot accept a set"))); rsi->returnMode = SFRM_Materialize; /* If we produced any tuples, send back the result */ if (estate.tuple_store) { rsi->setResult = estate.tuple_store; if (estate.rettupdesc) { MemoryContext oldcxt; oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt); rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc); MemoryContextSwitchTo(oldcxt); } } estate.retval = (Datum) 0; fcinfo->isnull = true; } else if (!estate.retisnull) { if (estate.retistuple) { /* * We have to check that the returned tuple actually matches the * expected result type. XXX would be better to cache the tupdesc * instead of repeating get_call_result_type() */ TupleDesc tupdesc; switch (get_call_result_type(fcinfo, NULL, &tupdesc)) { case TYPEFUNC_COMPOSITE: /* got the expected result rowtype, now check it */ if (estate.rettupdesc == NULL || !compatible_tupdesc(estate.rettupdesc, tupdesc)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("returned record type does not match expected record type"))); break; case TYPEFUNC_RECORD: /* * Failed to determine actual type of RECORD. We could * raise an error here, but what this means in practice is * that the caller is expecting any old generic rowtype, * so we don't really need to be restrictive. Pass back * the generated result type, instead. */ tupdesc = estate.rettupdesc; if (tupdesc == NULL) /* shouldn't happen */ elog(ERROR, "return type must be a row type"); break; default: /* shouldn't get here if retistuple is true ... */ elog(ERROR, "return type must be a row type"); break; } /* * Copy tuple to upper executor memory, as a tuple Datum. Make * sure it is labeled with the caller-supplied tuple type. */ estate.retval = PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval), tupdesc)); } else { /* Cast value to proper type */ estate.retval = exec_cast_value(estate.retval, estate.rettype, func->fn_rettype, &(func->fn_retinput), func->fn_rettypioparam, -1, fcinfo->isnull); /* * If the function's return type isn't by value, copy the value * into upper executor memory context. */ if (!fcinfo->isnull && !func->fn_retbyval) { Size len; void *tmp; len = datumGetSize(estate.retval, false, func->fn_rettyplen); tmp = SPI_palloc(len); memcpy(tmp, DatumGetPointer(estate.retval), len); estate.retval = PointerGetDatum(tmp); } } } estate.err_text = gettext_noop("during function exit"); /* * Let the instrumentation plugin peek at this function */ if (*plugin_ptr && (*plugin_ptr)->func_end) ((*plugin_ptr)->func_end) (&estate, func); /* Clean up any leftover temporary memory */ FreeExprContext(estate.eval_econtext); estate.eval_econtext = NULL; exec_eval_cleanup(&estate); /* * Pop the error context stack */ error_context_stack = plerrcontext.previous; /* * Return the function's result */ return estate.retval;}/* ---------- * plpgsql_exec_trigger Called by the call handler for * trigger execution. * ---------- */HeapTupleplpgsql_exec_trigger(PLpgSQL_function *func, TriggerData *trigdata){ PLpgSQL_execstate estate; ErrorContextCallback plerrcontext; int i; int rc; PLpgSQL_var *var; PLpgSQL_rec *rec_new, *rec_old; HeapTuple rettup; /* * Setup the execution state */ plpgsql_estate_setup(&estate, func, NULL); /* * Setup error traceback support for ereport() */ plerrcontext.callback = plpgsql_exec_error_callback; plerrcontext.arg = &estate; plerrcontext.previous = error_context_stack; error_context_stack = &plerrcontext; /* * Make local execution copies of all the datums */ estate.err_text = gettext_noop("during initialization of execution state"); for (i = 0; i < estate.ndatums; i++) estate.datums[i] = copy_plpgsql_datum(func->datums[i]); /* * Put the OLD and NEW tuples into record variables */ rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]); rec_new->freetup = false; rec_new->freetupdesc = false; rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]); rec_old->freetup = false; rec_old->freetupdesc = false; if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event)) { /* * Per-statement triggers don't use OLD/NEW variables */ rec_new->tup = NULL; rec_new->tupdesc = NULL; rec_old->tup = NULL; rec_old->tupdesc = NULL; } else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?